answer
stringlengths
15
1.25M
class DeviseMailer < ::ActionMailer::Base extend Devise::Controllers::InternalHelpers::ScopedViews # Deliver confirmation instructions when the user is created or its email is # updated, and also when confirmation is manually requested def <API key>(record) setup_mail(record, :<API key>) end # Deliver reset password instructions when manually requested def <API key>(record) setup_mail(record, :<API key>) end def unlock_instructions(record) setup_mail(record, :unlock_instructions) end private # Configure default email options def setup_mail(record, key) scope_name = Devise::Mapping.find_scope!(record) mapping = Devise.mappings[scope_name] subject translate(mapping, key) from mailer_sender(mapping) recipients record.email sent_on Time.now content_type Devise.mailer_content_type body render_with_scope(key, mapping, mapping.name => record, :resource => record) end def render_with_scope(key, mapping, assigns) if self.class.scoped_views begin render :file => "devise_mailer/#{mapping.as}/#{key}", :body => assigns rescue ActionView::MissingTemplate render :file => "devise_mailer/#{key}", :body => assigns end else render :file => "devise_mailer/#{key}", :body => assigns end end def mailer_sender(mapping) if Devise.mailer_sender.is_a?(Proc) block_args = mapping.name if Devise.mailer_sender.arity > 0 Devise.mailer_sender.call(block_args) else Devise.mailer_sender end end # Setup subject namespaced by model. It means you're able to setup your # messages using specific resource scope, or provide a default one. # Example (i18n locale file): # devise: # mailer: # <API key>: '...' # user: # <API key>: '...' def translate(mapping, key) I18n.t(:"#{mapping.name}.#{key}", :scope => [:devise, :mailer], :default => key) end end
import marked from 'marked'; marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, sanitize: true, smartLists: true, smartypants: false, highlight: function (code) { return require('highlight.js').highlightAuto(code).value; } }); export var asHtml = (markdown)=>{ return marked(markdown); } export var asTitle = (fileName)=>{ return fileName.substring(0, fileName.lastIndexOf('.md')); }
<? require_once("Model/Core/Util/Paging.php"); require_once("Model/Core/DataManager/DataHandler.php"); /** * , , , . * * @package Mangong * @subpackage Core/Util/Paging * @subpackage Core/DataManager/DataHandler * @property private resource $resBookDB : DB * @property public object $objPaging : * @category Book */ class Book{ public $objPaging; public $resBookDB; /** * * * @param resource $resMangongDB DB * @return null */ public function __construct($resMangongDB=null){ $this->objPaging = new Paging(); $this->resBookDB = $resMangongDB; } public function __destruct(){} /** * . * * @param integer $intWriterSeq OMR ("/Controller/_Lib/Constant.php" define ) * @param integer $intSubWriterSeq * @param string $strTitle * @param string $strPubName * @param string $strPubDate * @param string $strCoverUrl Url * @param string $strIsbnCode ISBN * @param integer &$intBookSeq Insert * @param integer $intCategorySeq * @param string $strAuthor * * @return boolean . (false true) */ public function setBook($intWriterSeq,$intSubWriterSeq,$strTitle,$strPubName=null,$strPubDate=null,$strCoverUrl=null,$strIsbnCode=null,&$intBookSeq=null,$intCategorySeq=null,$strAuthor=null){ include("Model/ManGong/SQL/MySQL/Book/setBook.php"); $boolReturn = $this->resBookDB->DB_access($this->resBookDB,$strQuery); $intBookSeq = mysql_insert_id($this->resBookDB->res_DB); return($boolReturn); } /** * . * * @param array $arrSearch * @param array $arrQueId * @param array $arrPaging * * @return array book_info table */ public function getBook($arrSearch=array(),$arrQueId=array(),&$arrPaging=null){ if(!is_null($arrPaging)){ $intTotalCount = $this->getBookCnt($arrSearch); $arrPaging = $this->objPaging->getPaging( $intTotalCount, $arrPaging['page']?$arrPaging['page']:1, $arrPaging['result_number'], $arrPaging['block_number'], $arrPaging['param'] ); } include("Model/ManGong/SQL/MySQL/Book/getBook.php"); $arrResult = $this->resBookDB->DB_access($this->resBookDB,$strQuery); return($arrResult); } /** * * * @param array $arrSearch * * @return integer */ public function getBookCnt($arrSearch=array()){ include("Model/ManGong/SQL/MySQL/Book/getBookCnt.php"); $arrResult = $this->resBookDB->DB_access($this->resBookDB,$strQuery); return($arrResult[0]['cnt']); } /** * * * @param string $strMemberSeq md5 * * @return array book_info,test_join_user table */ public function getUserJoinBookList($strMemberSeq){ include("Model/ManGong/SQL/MySQL/Book/getUserJoinBookList.php"); $arrResult = $this->resBookDB->DB_access($this->resBookDB,$strQuery); return($arrResult); } /** * * * @param string $strBookSeq md5 * * @return array test,,test_published table */ public function getTestListByBook($strBookSeq){ include("Model/ManGong/SQL/MySQL/Book/getTestListByBook.php"); $arrResult = $this->resBookDB->DB_access($this->resBookDB,$strQuery); return($arrResult); } /** * * * @param integer $intBookSeq * * @return string */ public function getTestSeqByBook($intBookSeq){ include("Model/ManGong/SQL/MySQL/Book/getTestSeqByBook.php"); $arrResult = $this->resBookDB->DB_access($this->resBookDB,$strQuery); return($arrResult[0]['group_seq']); } /** * test_published book_seq . * * @param integer $intPublishedSeq test_published * @param string $strBookSeq md5 * * @return boolean false true */ public function <API key>($intPublishedSeq,$strBookSeq){ include("Model/ManGong/SQL/MySQL/Book/<API key>.php"); $boolResult = $this->resBookDB->DB_access($this->resBookDB,$strQuery); return($boolResult); } /** * . * * @param integer $intTestSeq * * @return integer */ public function <API key>($intTestSeq){ include("Model/ManGong/SQL/MySQL/Book/<API key>.php"); $arrResult = $this->resBookDB->DB_access($this->resBookDB,$strQuery); return($arrResult[0]['book_seq']); } /** * curl . * * @param string $url API Url * * @return string */ public function get_xml_from_url($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, <API key>, 1); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); $xmlstr = curl_exec($ch); curl_close($ch); return $xmlstr; } } ?>
.cust-profile { font-size: 250px; } .cust-list { font-size: 125px; } .checkbox-left { width: 10%; text-align: left; } .text-pink { color: #ec407a; } .extra-space{ padding-bottom: 15px; padding-top: 15px; } input[type="radio"], input[type="checkbox"] { margin: 0 0 0 !important; }
namespace MLifter.AudioTools { partial class LanguageForm { <summary> Required designer variable. </summary> private System.ComponentModel.IContainer components = null; <summary> Clean up any resources being used. </summary> <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent() { System.ComponentModel.<API key> resources = new System.ComponentModel.<API key>(typeof(LanguageForm)); this.<API key> = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.<API key> = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.buttonOk = new System.Windows.Forms.Button(); this.SuspendLayout(); // <API key> this.<API key>.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.<API key>, "<API key>"); this.<API key>.FormattingEnabled = true; this.<API key>.Name = "<API key>"; this.<API key>.Sorted = true; // label3 resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // <API key> this.<API key>.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.<API key>, "<API key>"); this.<API key>.FormattingEnabled = true; this.<API key>.Name = "<API key>"; this.<API key>.Sorted = true; // label1 resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // buttonOk resources.ApplyResources(this.buttonOk, "buttonOk"); this.buttonOk.Name = "buttonOk"; this.buttonOk.<API key> = true; this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click); // LanguageForm this.AcceptButton = this.buttonOk; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ControlBox = false; this.Controls.Add(this.buttonOk); this.Controls.Add(this.<API key>); this.Controls.Add(this.label3); this.Controls.Add(this.<API key>); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "LanguageForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.TopMost = true; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox <API key>; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox <API key>; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonOk; } }
@font-face { font-family: 'FontAwesome'; src: url('../fonts/fontawesome-webfont.ttf?v=4.6.1') format('truetype'); font-weight: normal; font-style: normal; } .fa { display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -<API key>: antialiased; -<API key>: grayscale; } /* makes the font 33% larger relative to the icon container */ .fa-lg { font-size: 1.33333333em; line-height: 0.75em; vertical-align: -15%; } .fa-2x { font-size: 2em; } .fa-3x { font-size: 3em; } .fa-4x { font-size: 4em; } .fa-5x { font-size: 5em; } .fa-fw { width: 1.28571429em; text-align: center; } .fa-ul { padding-left: 0; margin-left: 2.14285714em; list-style-type: none; } .fa-ul > li { position: relative; } .fa-li { position: absolute; left: -2.14285714em; width: 2.14285714em; top: 0.14285714em; text-align: center; } .fa-li.fa-lg { left: -1.85714286em; } .fa-border { padding: .2em .25em .15em; border: solid 0.08em #eeeeee; border-radius: .1em; } .fa-pull-left { float: left; } .fa-pull-right { float: right; } .fa.fa-pull-left { margin-right: .3em; } .fa.fa-pull-right { margin-left: .3em; } /* Deprecated as of 4.4.0 */ .pull-right { float: right; } .pull-left { float: left; } .fa.pull-left { margin-right: .3em; } .fa.pull-right { margin-left: .3em; } .fa-spin { -webkit-animation: fa-spin 2s infinite linear; animation: fa-spin 2s infinite linear; } .fa-pulse { -webkit-animation: fa-spin 1s infinite steps(8); animation: fa-spin 1s infinite steps(8); } @-webkit-keyframes fa-spin { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(359deg); transform: rotate(359deg); } } @keyframes fa-spin { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(359deg); transform: rotate(359deg); } } .fa-rotate-90 { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .fa-rotate-180 { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2)"; -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .fa-rotate-270 { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=3)"; -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .fa-flip-horizontal { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)"; -webkit-transform: scale(-1, 1); -ms-transform: scale(-1, 1); transform: scale(-1, 1); } .fa-flip-vertical { -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"; -webkit-transform: scale(1, -1); -ms-transform: scale(1, -1); transform: scale(1, -1); } :root .fa-rotate-90, :root .fa-rotate-180, :root .fa-rotate-270, :root .fa-flip-horizontal, :root .fa-flip-vertical { filter: none; } .fa-stack { position: relative; display: inline-block; width: 2em; height: 2em; line-height: 2em; vertical-align: middle; } .fa-stack-1x, .fa-stack-2x { position: absolute; left: 0; width: 100%; text-align: center; } .fa-stack-1x { line-height: inherit; } .fa-stack-2x { font-size: 2em; } .fa-inverse { color: #ffffff; } /* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen readers do not read off random characters that represent icons */ .fa-glass:before { content: "\f000"; } .fa-music:before { content: "\f001"; } .fa-search:before { content: "\f002"; } .fa-envelope-o:before { content: "\f003"; } .fa-heart:before { content: "\f004"; } .fa-star:before { content: "\f005"; } .fa-star-o:before { content: "\f006"; } .fa-user:before { content: "\f007"; } .fa-film:before { content: "\f008"; } .fa-th-large:before { content: "\f009"; } .fa-th:before { content: "\f00a"; } .fa-th-list:before { content: "\f00b"; } .fa-check:before { content: "\f00c"; } .fa-remove:before, .fa-close:before, .fa-times:before { content: "\f00d"; } .fa-search-plus:before { content: "\f00e"; } .fa-search-minus:before { content: "\f010"; } .fa-power-off:before { content: "\f011"; } .fa-signal:before { content: "\f012"; } .fa-gear:before, .fa-cog:before { content: "\f013"; } .fa-trash-o:before { content: "\f014"; } .fa-home:before { content: "\f015"; } .fa-file-o:before { content: "\f016"; } .fa-clock-o:before { content: "\f017"; } .fa-road:before { content: "\f018"; } .fa-download:before { content: "\f019"; } .<API key>:before { content: "\f01a"; } .<API key>:before { content: "\f01b"; } .fa-inbox:before { content: "\f01c"; } .fa-play-circle-o:before { content: "\f01d"; } .fa-rotate-right:before, .fa-repeat:before { content: "\f01e"; } .fa-refresh:before { content: "\f021"; } .fa-list-alt:before { content: "\f022"; } .fa-lock:before { content: "\f023"; } .fa-flag:before { content: "\f024"; } .fa-headphones:before { content: "\f025"; } .fa-volume-off:before { content: "\f026"; } .fa-volume-down:before { content: "\f027"; } .fa-volume-up:before { content: "\f028"; } .fa-qrcode:before { content: "\f029"; } .fa-barcode:before { content: "\f02a"; } .fa-tag:before { content: "\f02b"; } .fa-tags:before { content: "\f02c"; } .fa-book:before { content: "\f02d"; } .fa-bookmark:before { content: "\f02e"; } .fa-print:before { content: "\f02f"; } .fa-camera:before { content: "\f030"; } .fa-font:before { content: "\f031"; } .fa-bold:before { content: "\f032"; } .fa-italic:before { content: "\f033"; } .fa-text-height:before { content: "\f034"; } .fa-text-width:before { content: "\f035"; } .fa-align-left:before { content: "\f036"; } .fa-align-center:before { content: "\f037"; } .fa-align-right:before { content: "\f038"; } .fa-align-justify:before { content: "\f039"; } .fa-list:before { content: "\f03a"; } .fa-dedent:before, .fa-outdent:before { content: "\f03b"; } .fa-indent:before { content: "\f03c"; } .fa-video-camera:before { content: "\f03d"; } .fa-photo:before, .fa-image:before, .fa-picture-o:before { content: "\f03e"; } .fa-pencil:before { content: "\f040"; } .fa-map-marker:before { content: "\f041"; } .fa-adjust:before { content: "\f042"; } .fa-tint:before { content: "\f043"; } .fa-edit:before, .fa-pencil-square-o:before { content: "\f044"; } .fa-share-square-o:before { content: "\f045"; } .fa-check-square-o:before { content: "\f046"; } .fa-arrows:before { content: "\f047"; } .fa-step-backward:before { content: "\f048"; } .fa-fast-backward:before { content: "\f049"; } .fa-backward:before { content: "\f04a"; } .fa-play:before { content: "\f04b"; } .fa-pause:before { content: "\f04c"; } .fa-stop:before { content: "\f04d"; } .fa-forward:before { content: "\f04e"; } .fa-fast-forward:before { content: "\f050"; } .fa-step-forward:before { content: "\f051"; } .fa-eject:before { content: "\f052"; } .fa-chevron-left:before { content: "\f053"; } .fa-chevron-right:before { content: "\f054"; } .fa-plus-circle:before { content: "\f055"; } .fa-minus-circle:before { content: "\f056"; } .fa-times-circle:before { content: "\f057"; } .fa-check-circle:before { content: "\f058"; } .fa-question-circle:before { content: "\f059"; } .fa-info-circle:before { content: "\f05a"; } .fa-crosshairs:before { content: "\f05b"; } .fa-times-circle-o:before { content: "\f05c"; } .fa-check-circle-o:before { content: "\f05d"; } .fa-ban:before { content: "\f05e"; } .fa-arrow-left:before { content: "\f060"; } .fa-arrow-right:before { content: "\f061"; } .fa-arrow-up:before { content: "\f062"; } .fa-arrow-down:before { content: "\f063"; } .fa-mail-forward:before, .fa-share:before { content: "\f064"; } .fa-expand:before { content: "\f065"; } .fa-compress:before { content: "\f066"; } .fa-plus:before { content: "\f067"; } .fa-minus:before { content: "\f068"; } .fa-asterisk:before { content: "\f069"; } .<API key>:before { content: "\f06a"; } .fa-gift:before { content: "\f06b"; } .fa-leaf:before { content: "\f06c"; } .fa-fire:before { content: "\f06d"; } .fa-eye:before { content: "\f06e"; } .fa-eye-slash:before { content: "\f070"; } .fa-warning:before, .<API key>:before { content: "\f071"; } .fa-plane:before { content: "\f072"; } .fa-calendar:before { content: "\f073"; } .fa-random:before { content: "\f074"; } .fa-comment:before { content: "\f075"; } .fa-magnet:before { content: "\f076"; } .fa-chevron-up:before { content: "\f077"; } .fa-chevron-down:before { content: "\f078"; } .fa-retweet:before { content: "\f079"; } .fa-shopping-cart:before { content: "\f07a"; } .fa-folder:before { content: "\f07b"; } .fa-folder-open:before { content: "\f07c"; } .fa-arrows-v:before { content: "\f07d"; } .fa-arrows-h:before { content: "\f07e"; } .fa-bar-chart-o:before, .fa-bar-chart:before { content: "\f080"; } .fa-twitter-square:before { content: "\f081"; } .fa-facebook-square:before { content: "\f082"; } .fa-camera-retro:before { content: "\f083"; } .fa-key:before { content: "\f084"; } .fa-gears:before, .fa-cogs:before { content: "\f085"; } .fa-comments:before { content: "\f086"; } .fa-thumbs-o-up:before { content: "\f087"; } .fa-thumbs-o-down:before { content: "\f088"; } .fa-star-half:before { content: "\f089"; } .fa-heart-o:before { content: "\f08a"; } .fa-sign-out:before { content: "\f08b"; } .fa-linkedin-square:before { content: "\f08c"; } .fa-thumb-tack:before { content: "\f08d"; } .fa-external-link:before { content: "\f08e"; } .fa-sign-in:before { content: "\f090"; } .fa-trophy:before { content: "\f091"; } .fa-github-square:before { content: "\f092"; } .fa-upload:before { content: "\f093"; } .fa-lemon-o:before { content: "\f094"; } .fa-phone:before { content: "\f095"; } .fa-square-o:before { content: "\f096"; } .fa-bookmark-o:before { content: "\f097"; } .fa-phone-square:before { content: "\f098"; } .fa-twitter:before { content: "\f099"; } .fa-facebook-f:before, .fa-facebook:before { content: "\f09a"; } .fa-github:before { content: "\f09b"; } .fa-unlock:before { content: "\f09c"; } .fa-credit-card:before { content: "\f09d"; } .fa-feed:before, .fa-rss:before { content: "\f09e"; } .fa-hdd-o:before { content: "\f0a0"; } .fa-bullhorn:before { content: "\f0a1"; } .fa-bell:before { content: "\f0f3"; } .fa-certificate:before { content: "\f0a3"; } .fa-hand-o-right:before { content: "\f0a4"; } .fa-hand-o-left:before { content: "\f0a5"; } .fa-hand-o-up:before { content: "\f0a6"; } .fa-hand-o-down:before { content: "\f0a7"; } .<API key>:before { content: "\f0a8"; } .<API key>:before { content: "\f0a9"; } .fa-arrow-circle-up:before { content: "\f0aa"; } .<API key>:before { content: "\f0ab"; } .fa-globe:before { content: "\f0ac"; } .fa-wrench:before { content: "\f0ad"; } .fa-tasks:before { content: "\f0ae"; } .fa-filter:before { content: "\f0b0"; } .fa-briefcase:before { content: "\f0b1"; } .fa-arrows-alt:before { content: "\f0b2"; } .fa-group:before, .fa-users:before { content: "\f0c0"; } .fa-chain:before, .fa-link:before { content: "\f0c1"; } .fa-cloud:before { content: "\f0c2"; } .fa-flask:before { content: "\f0c3"; } .fa-cut:before, .fa-scissors:before { content: "\f0c4"; } .fa-copy:before, .fa-files-o:before { content: "\f0c5"; } .fa-paperclip:before { content: "\f0c6"; } .fa-save:before, .fa-floppy-o:before { content: "\f0c7"; } .fa-square:before { content: "\f0c8"; } .fa-navicon:before, .fa-reorder:before, .fa-bars:before { content: "\f0c9"; } .fa-list-ul:before { content: "\f0ca"; } .fa-list-ol:before { content: "\f0cb"; } .fa-strikethrough:before { content: "\f0cc"; } .fa-underline:before { content: "\f0cd"; } .fa-table:before { content: "\f0ce"; } .fa-magic:before { content: "\f0d0"; } .fa-truck:before { content: "\f0d1"; } .fa-pinterest:before { content: "\f0d2"; } .fa-pinterest-square:before { content: "\f0d3"; } .<API key>:before { content: "\f0d4"; } .fa-google-plus:before { content: "\f0d5"; } .fa-money:before { content: "\f0d6"; } .fa-caret-down:before { content: "\f0d7"; } .fa-caret-up:before { content: "\f0d8"; } .fa-caret-left:before { content: "\f0d9"; } .fa-caret-right:before { content: "\f0da"; } .fa-columns:before { content: "\f0db"; } .fa-unsorted:before, .fa-sort:before { content: "\f0dc"; } .fa-sort-down:before, .fa-sort-desc:before { content: "\f0dd"; } .fa-sort-up:before, .fa-sort-asc:before { content: "\f0de"; } .fa-envelope:before { content: "\f0e0"; } .fa-linkedin:before { content: "\f0e1"; } .fa-rotate-left:before, .fa-undo:before { content: "\f0e2"; } .fa-legal:before, .fa-gavel:before { content: "\f0e3"; } .fa-dashboard:before, .fa-tachometer:before { content: "\f0e4"; } .fa-comment-o:before { content: "\f0e5"; } .fa-comments-o:before { content: "\f0e6"; } .fa-flash:before, .fa-bolt:before { content: "\f0e7"; } .fa-sitemap:before { content: "\f0e8"; } .fa-umbrella:before { content: "\f0e9"; } .fa-paste:before, .fa-clipboard:before { content: "\f0ea"; } .fa-lightbulb-o:before { content: "\f0eb"; } .fa-exchange:before { content: "\f0ec"; } .fa-cloud-download:before { content: "\f0ed"; } .fa-cloud-upload:before { content: "\f0ee"; } .fa-user-md:before { content: "\f0f0"; } .fa-stethoscope:before { content: "\f0f1"; } .fa-suitcase:before { content: "\f0f2"; } .fa-bell-o:before { content: "\f0a2"; } .fa-coffee:before { content: "\f0f4"; } .fa-cutlery:before { content: "\f0f5"; } .fa-file-text-o:before { content: "\f0f6"; } .fa-building-o:before { content: "\f0f7"; } .fa-hospital-o:before { content: "\f0f8"; } .fa-ambulance:before { content: "\f0f9"; } .fa-medkit:before { content: "\f0fa"; } .fa-fighter-jet:before { content: "\f0fb"; } .fa-beer:before { content: "\f0fc"; } .fa-h-square:before { content: "\f0fd"; } .fa-plus-square:before { content: "\f0fe"; } .<API key>:before { content: "\f100"; } .<API key>:before { content: "\f101"; } .fa-angle-double-up:before { content: "\f102"; } .<API key>:before { content: "\f103"; } .fa-angle-left:before { content: "\f104"; } .fa-angle-right:before { content: "\f105"; } .fa-angle-up:before { content: "\f106"; } .fa-angle-down:before { content: "\f107"; } .fa-desktop:before { content: "\f108"; } .fa-laptop:before { content: "\f109"; } .fa-tablet:before { content: "\f10a"; } .fa-mobile-phone:before, .fa-mobile:before { content: "\f10b"; } .fa-circle-o:before { content: "\f10c"; } .fa-quote-left:before { content: "\f10d"; } .fa-quote-right:before { content: "\f10e"; } .fa-spinner:before { content: "\f110"; } .fa-circle:before { content: "\f111"; } .fa-mail-reply:before, .fa-reply:before { content: "\f112"; } .fa-github-alt:before { content: "\f113"; } .fa-folder-o:before { content: "\f114"; } .fa-folder-open-o:before { content: "\f115"; } .fa-smile-o:before { content: "\f118"; } .fa-frown-o:before { content: "\f119"; } .fa-meh-o:before { content: "\f11a"; } .fa-gamepad:before { content: "\f11b"; } .fa-keyboard-o:before { content: "\f11c"; } .fa-flag-o:before { content: "\f11d"; } .fa-flag-checkered:before { content: "\f11e"; } .fa-terminal:before { content: "\f120"; } .fa-code:before { content: "\f121"; } .fa-mail-reply-all:before, .fa-reply-all:before { content: "\f122"; } .fa-star-half-empty:before, .fa-star-half-full:before, .fa-star-half-o:before { content: "\f123"; } .fa-location-arrow:before { content: "\f124"; } .fa-crop:before { content: "\f125"; } .fa-code-fork:before { content: "\f126"; } .fa-unlink:before, .fa-chain-broken:before { content: "\f127"; } .fa-question:before { content: "\f128"; } .fa-info:before { content: "\f129"; } .fa-exclamation:before { content: "\f12a"; } .fa-superscript:before { content: "\f12b"; } .fa-subscript:before { content: "\f12c"; } .fa-eraser:before { content: "\f12d"; } .fa-puzzle-piece:before { content: "\f12e"; } .fa-microphone:before { content: "\f130"; } .fa-microphone-slash:before { content: "\f131"; } .fa-shield:before { content: "\f132"; } .fa-calendar-o:before { content: "\f133"; } .<API key>:before { content: "\f134"; } .fa-rocket:before { content: "\f135"; } .fa-maxcdn:before { content: "\f136"; } .<API key>:before { content: "\f137"; } .<API key>:before { content: "\f138"; } .<API key>:before { content: "\f139"; } .<API key>:before { content: "\f13a"; } .fa-html5:before { content: "\f13b"; } .fa-css3:before { content: "\f13c"; } .fa-anchor:before { content: "\f13d"; } .fa-unlock-alt:before { content: "\f13e"; } .fa-bullseye:before { content: "\f140"; } .fa-ellipsis-h:before { content: "\f141"; } .fa-ellipsis-v:before { content: "\f142"; } .fa-rss-square:before { content: "\f143"; } .fa-play-circle:before { content: "\f144"; } .fa-ticket:before { content: "\f145"; } .fa-minus-square:before { content: "\f146"; } .fa-minus-square-o:before { content: "\f147"; } .fa-level-up:before { content: "\f148"; } .fa-level-down:before { content: "\f149"; } .fa-check-square:before { content: "\f14a"; } .fa-pencil-square:before { content: "\f14b"; } .<API key>:before { content: "\f14c"; } .fa-share-square:before { content: "\f14d"; } .fa-compass:before { content: "\f14e"; } .fa-toggle-down:before, .<API key>:before { content: "\f150"; } .fa-toggle-up:before, .<API key>:before { content: "\f151"; } .fa-toggle-right:before, .<API key>:before { content: "\f152"; } .fa-euro:before, .fa-eur:before { content: "\f153"; } .fa-gbp:before { content: "\f154"; } .fa-dollar:before, .fa-usd:before { content: "\f155"; } .fa-rupee:before, .fa-inr:before { content: "\f156"; } .fa-cny:before, .fa-rmb:before, .fa-yen:before, .fa-jpy:before { content: "\f157"; } .fa-ruble:before, .fa-rouble:before, .fa-rub:before { content: "\f158"; } .fa-won:before, .fa-krw:before { content: "\f159"; } .fa-bitcoin:before, .fa-btc:before { content: "\f15a"; } .fa-file:before { content: "\f15b"; } .fa-file-text:before { content: "\f15c"; } .fa-sort-alpha-asc:before { content: "\f15d"; } .fa-sort-alpha-desc:before { content: "\f15e"; } .fa-sort-amount-asc:before { content: "\f160"; } .fa-sort-amount-desc:before { content: "\f161"; } .fa-sort-numeric-asc:before { content: "\f162"; } .<API key>:before { content: "\f163"; } .fa-thumbs-up:before { content: "\f164"; } .fa-thumbs-down:before { content: "\f165"; } .fa-youtube-square:before { content: "\f166"; } .fa-youtube:before { content: "\f167"; } .fa-xing:before { content: "\f168"; } .fa-xing-square:before { content: "\f169"; } .fa-youtube-play:before { content: "\f16a"; } .fa-dropbox:before { content: "\f16b"; } .fa-stack-overflow:before { content: "\f16c"; } .fa-instagram:before { content: "\f16d"; } .fa-flickr:before { content: "\f16e"; } .fa-adn:before { content: "\f170"; } .fa-bitbucket:before { content: "\f171"; } .fa-bitbucket-square:before { content: "\f172"; } .fa-tumblr:before { content: "\f173"; } .fa-tumblr-square:before { content: "\f174"; } .fa-long-arrow-down:before { content: "\f175"; } .fa-long-arrow-up:before { content: "\f176"; } .fa-long-arrow-left:before { content: "\f177"; } .fa-long-arrow-right:before { content: "\f178"; } .fa-apple:before { content: "\f179"; } .fa-windows:before { content: "\f17a"; } .fa-android:before { content: "\f17b"; } .fa-linux:before { content: "\f17c"; } .fa-dribbble:before { content: "\f17d"; } .fa-skype:before { content: "\f17e"; } .fa-foursquare:before { content: "\f180"; } .fa-trello:before { content: "\f181"; } .fa-female:before { content: "\f182"; } .fa-male:before { content: "\f183"; } .fa-gittip:before, .fa-gratipay:before { content: "\f184"; } .fa-sun-o:before { content: "\f185"; } .fa-moon-o:before { content: "\f186"; } .fa-archive:before { content: "\f187"; } .fa-bug:before { content: "\f188"; } .fa-vk:before { content: "\f189"; } .fa-weibo:before { content: "\f18a"; } .fa-renren:before { content: "\f18b"; } .fa-pagelines:before { content: "\f18c"; } .fa-stack-exchange:before { content: "\f18d"; } .<API key>:before { content: "\f18e"; } .<API key>:before { content: "\f190"; } .fa-toggle-left:before, .<API key>:before { content: "\f191"; } .fa-dot-circle-o:before { content: "\f192"; } .fa-wheelchair:before { content: "\f193"; } .fa-vimeo-square:before { content: "\f194"; } .fa-turkish-lira:before, .fa-try:before { content: "\f195"; } .fa-plus-square-o:before { content: "\f196"; } .fa-space-shuttle:before { content: "\f197"; } .fa-slack:before { content: "\f198"; } .fa-envelope-square:before { content: "\f199"; } .fa-wordpress:before { content: "\f19a"; } .fa-openid:before { content: "\f19b"; } .fa-institution:before, .fa-bank:before, .fa-university:before { content: "\f19c"; } .fa-mortar-board:before, .fa-graduation-cap:before { content: "\f19d"; } .fa-yahoo:before { content: "\f19e"; } .fa-google:before { content: "\f1a0"; } .fa-reddit:before { content: "\f1a1"; } .fa-reddit-square:before { content: "\f1a2"; } .<API key>:before { content: "\f1a3"; } .fa-stumbleupon:before { content: "\f1a4"; } .fa-delicious:before { content: "\f1a5"; } .fa-digg:before { content: "\f1a6"; } .fa-pied-piper:before { content: "\f1a7"; } .fa-pied-piper-alt:before { content: "\f1a8"; } .fa-drupal:before { content: "\f1a9"; } .fa-joomla:before { content: "\f1aa"; } .fa-language:before { content: "\f1ab"; } .fa-fax:before { content: "\f1ac"; } .fa-building:before { content: "\f1ad"; } .fa-child:before { content: "\f1ae"; } .fa-paw:before { content: "\f1b0"; } .fa-spoon:before { content: "\f1b1"; } .fa-cube:before { content: "\f1b2"; } .fa-cubes:before { content: "\f1b3"; } .fa-behance:before { content: "\f1b4"; } .fa-behance-square:before { content: "\f1b5"; } .fa-steam:before { content: "\f1b6"; } .fa-steam-square:before { content: "\f1b7"; } .fa-recycle:before { content: "\f1b8"; } .fa-automobile:before, .fa-car:before { content: "\f1b9"; } .fa-cab:before, .fa-taxi:before { content: "\f1ba"; } .fa-tree:before { content: "\f1bb"; } .fa-spotify:before { content: "\f1bc"; } .fa-deviantart:before { content: "\f1bd"; } .fa-soundcloud:before { content: "\f1be"; } .fa-database:before { content: "\f1c0"; } .fa-file-pdf-o:before { content: "\f1c1"; } .fa-file-word-o:before { content: "\f1c2"; } .fa-file-excel-o:before { content: "\f1c3"; } .<API key>:before { content: "\f1c4"; } .fa-file-photo-o:before, .fa-file-picture-o:before, .fa-file-image-o:before { content: "\f1c5"; } .fa-file-zip-o:before, .fa-file-archive-o:before { content: "\f1c6"; } .fa-file-sound-o:before, .fa-file-audio-o:before { content: "\f1c7"; } .fa-file-movie-o:before, .fa-file-video-o:before { content: "\f1c8"; } .fa-file-code-o:before { content: "\f1c9"; } .fa-vine:before { content: "\f1ca"; } .fa-codepen:before { content: "\f1cb"; } .fa-jsfiddle:before { content: "\f1cc"; } .fa-life-bouy:before, .fa-life-buoy:before, .fa-life-saver:before, .fa-support:before, .fa-life-ring:before { content: "\f1cd"; } .fa-circle-o-notch:before { content: "\f1ce"; } .fa-ra:before, .fa-rebel:before { content: "\f1d0"; } .fa-ge:before, .fa-empire:before { content: "\f1d1"; } .fa-git-square:before { content: "\f1d2"; } .fa-git:before { content: "\f1d3"; } .<API key>:before, .fa-yc-square:before, .fa-hacker-news:before { content: "\f1d4"; } .fa-tencent-weibo:before { content: "\f1d5"; } .fa-qq:before { content: "\f1d6"; } .fa-wechat:before, .fa-weixin:before { content: "\f1d7"; } .fa-send:before, .fa-paper-plane:before { content: "\f1d8"; } .fa-send-o:before, .fa-paper-plane-o:before { content: "\f1d9"; } .fa-history:before { content: "\f1da"; } .fa-circle-thin:before { content: "\f1db"; } .fa-header:before { content: "\f1dc"; } .fa-paragraph:before { content: "\f1dd"; } .fa-sliders:before { content: "\f1de"; } .fa-share-alt:before { content: "\f1e0"; } .fa-share-alt-square:before { content: "\f1e1"; } .fa-bomb:before { content: "\f1e2"; } .fa-soccer-ball-o:before, .fa-futbol-o:before { content: "\f1e3"; } .fa-tty:before { content: "\f1e4"; } .fa-binoculars:before { content: "\f1e5"; } .fa-plug:before { content: "\f1e6"; } .fa-slideshare:before { content: "\f1e7"; } .fa-twitch:before { content: "\f1e8"; } .fa-yelp:before { content: "\f1e9"; } .fa-newspaper-o:before { content: "\f1ea"; } .fa-wifi:before { content: "\f1eb"; } .fa-calculator:before { content: "\f1ec"; } .fa-paypal:before { content: "\f1ed"; } .fa-google-wallet:before { content: "\f1ee"; } .fa-cc-visa:before { content: "\f1f0"; } .fa-cc-mastercard:before { content: "\f1f1"; } .fa-cc-discover:before { content: "\f1f2"; } .fa-cc-amex:before { content: "\f1f3"; } .fa-cc-paypal:before { content: "\f1f4"; } .fa-cc-stripe:before { content: "\f1f5"; } .fa-bell-slash:before { content: "\f1f6"; } .fa-bell-slash-o:before { content: "\f1f7"; } .fa-trash:before { content: "\f1f8"; } .fa-copyright:before { content: "\f1f9"; } .fa-at:before { content: "\f1fa"; } .fa-eyedropper:before { content: "\f1fb"; } .fa-paint-brush:before { content: "\f1fc"; } .fa-birthday-cake:before { content: "\f1fd"; } .fa-area-chart:before { content: "\f1fe"; } .fa-pie-chart:before { content: "\f200"; } .fa-line-chart:before { content: "\f201"; } .fa-lastfm:before { content: "\f202"; } .fa-lastfm-square:before { content: "\f203"; } .fa-toggle-off:before { content: "\f204"; } .fa-toggle-on:before { content: "\f205"; } .fa-bicycle:before { content: "\f206"; } .fa-bus:before { content: "\f207"; } .fa-ioxhost:before { content: "\f208"; } .fa-angellist:before { content: "\f209"; } .fa-cc:before { content: "\f20a"; } .fa-shekel:before, .fa-sheqel:before, .fa-ils:before { content: "\f20b"; } .fa-meanpath:before { content: "\f20c"; } .fa-buysellads:before { content: "\f20d"; } .fa-connectdevelop:before { content: "\f20e"; } .fa-dashcube:before { content: "\f210"; } .fa-forumbee:before { content: "\f211"; } .fa-leanpub:before { content: "\f212"; } .fa-sellsy:before { content: "\f213"; } .fa-shirtsinbulk:before { content: "\f214"; } .fa-simplybuilt:before { content: "\f215"; } .fa-skyatlas:before { content: "\f216"; } .fa-cart-plus:before { content: "\f217"; } .fa-cart-arrow-down:before { content: "\f218"; } .fa-diamond:before { content: "\f219"; } .fa-ship:before { content: "\f21a"; } .fa-user-secret:before { content: "\f21b"; } .fa-motorcycle:before { content: "\f21c"; } .fa-street-view:before { content: "\f21d"; } .fa-heartbeat:before { content: "\f21e"; } .fa-venus:before { content: "\f221"; } .fa-mars:before { content: "\f222"; } .fa-mercury:before { content: "\f223"; } .fa-intersex:before, .fa-transgender:before { content: "\f224"; } .fa-transgender-alt:before { content: "\f225"; } .fa-venus-double:before { content: "\f226"; } .fa-mars-double:before { content: "\f227"; } .fa-venus-mars:before { content: "\f228"; } .fa-mars-stroke:before { content: "\f229"; } .fa-mars-stroke-v:before { content: "\f22a"; } .fa-mars-stroke-h:before { content: "\f22b"; } .fa-neuter:before { content: "\f22c"; } .fa-genderless:before { content: "\f22d"; } .<API key>:before { content: "\f230"; } .fa-pinterest-p:before { content: "\f231"; } .fa-whatsapp:before { content: "\f232"; } .fa-server:before { content: "\f233"; } .fa-user-plus:before { content: "\f234"; } .fa-user-times:before { content: "\f235"; } .fa-hotel:before, .fa-bed:before { content: "\f236"; } .fa-viacoin:before { content: "\f237"; } .fa-train:before { content: "\f238"; } .fa-subway:before { content: "\f239"; } .fa-medium:before { content: "\f23a"; } .fa-yc:before, .fa-y-combinator:before { content: "\f23b"; } .fa-optin-monster:before { content: "\f23c"; } .fa-opencart:before { content: "\f23d"; } .fa-expeditedssl:before { content: "\f23e"; } .fa-battery-4:before, .fa-battery-full:before { content: "\f240"; } .fa-battery-3:before, .<API key>:before { content: "\f241"; } .fa-battery-2:before, .fa-battery-half:before { content: "\f242"; } .fa-battery-1:before, .fa-battery-quarter:before { content: "\f243"; } .fa-battery-0:before, .fa-battery-empty:before { content: "\f244"; } .fa-mouse-pointer:before { content: "\f245"; } .fa-i-cursor:before { content: "\f246"; } .fa-object-group:before { content: "\f247"; } .fa-object-ungroup:before { content: "\f248"; } .fa-sticky-note:before { content: "\f249"; } .fa-sticky-note-o:before { content: "\f24a"; } .fa-cc-jcb:before { content: "\f24b"; } .fa-cc-diners-club:before { content: "\f24c"; } .fa-clone:before { content: "\f24d"; } .fa-balance-scale:before { content: "\f24e"; } .fa-hourglass-o:before { content: "\f250"; } .fa-hourglass-1:before, .fa-hourglass-start:before { content: "\f251"; } .fa-hourglass-2:before, .fa-hourglass-half:before { content: "\f252"; } .fa-hourglass-3:before, .fa-hourglass-end:before { content: "\f253"; } .fa-hourglass:before { content: "\f254"; } .fa-hand-grab-o:before, .fa-hand-rock-o:before { content: "\f255"; } .fa-hand-stop-o:before, .fa-hand-paper-o:before { content: "\f256"; } .fa-hand-scissors-o:before { content: "\f257"; } .fa-hand-lizard-o:before { content: "\f258"; } .fa-hand-spock-o:before { content: "\f259"; } .fa-hand-pointer-o:before { content: "\f25a"; } .fa-hand-peace-o:before { content: "\f25b"; } .fa-trademark:before { content: "\f25c"; } .fa-registered:before { content: "\f25d"; } .fa-creative-commons:before { content: "\f25e"; } .fa-gg:before { content: "\f260"; } .fa-gg-circle:before { content: "\f261"; } .fa-tripadvisor:before { content: "\f262"; } .fa-odnoklassniki:before { content: "\f263"; } .<API key>:before { content: "\f264"; } .fa-get-pocket:before { content: "\f265"; } .fa-wikipedia-w:before { content: "\f266"; } .fa-safari:before { content: "\f267"; } .fa-chrome:before { content: "\f268"; } .fa-firefox:before { content: "\f269"; } .fa-opera:before { content: "\f26a"; } .<API key>:before { content: "\f26b"; } .fa-tv:before, .fa-television:before { content: "\f26c"; } .fa-contao:before { content: "\f26d"; } .fa-500px:before { content: "\f26e"; } .fa-amazon:before { content: "\f270"; } .fa-calendar-plus-o:before { content: "\f271"; } .fa-calendar-minus-o:before { content: "\f272"; } .fa-calendar-times-o:before { content: "\f273"; } .fa-calendar-check-o:before { content: "\f274"; } .fa-industry:before { content: "\f275"; } .fa-map-pin:before { content: "\f276"; } .fa-map-signs:before { content: "\f277"; } .fa-map-o:before { content: "\f278"; } .fa-map:before { content: "\f279"; } .fa-commenting:before { content: "\f27a"; } .fa-commenting-o:before { content: "\f27b"; } .fa-houzz:before { content: "\f27c"; } .fa-vimeo:before { content: "\f27d"; } .fa-black-tie:before { content: "\f27e"; } .fa-fonticons:before { content: "\f280"; } .fa-reddit-alien:before { content: "\f281"; } .fa-edge:before { content: "\f282"; } .fa-credit-card-alt:before { content: "\f283"; } .fa-codiepie:before { content: "\f284"; } .fa-modx:before { content: "\f285"; } .fa-fort-awesome:before { content: "\f286"; } .fa-usb:before { content: "\f287"; } .fa-product-hunt:before { content: "\f288"; } .fa-mixcloud:before { content: "\f289"; } .fa-scribd:before { content: "\f28a"; } .fa-pause-circle:before { content: "\f28b"; } .fa-pause-circle-o:before { content: "\f28c"; } .fa-stop-circle:before { content: "\f28d"; } .fa-stop-circle-o:before { content: "\f28e"; } .fa-shopping-bag:before { content: "\f290"; } .fa-shopping-basket:before { content: "\f291"; } .fa-hashtag:before { content: "\f292"; } .fa-bluetooth:before { content: "\f293"; } .fa-bluetooth-b:before { content: "\f294"; } .fa-percent:before { content: "\f295"; } .fa-gitlab:before { content: "\f296"; } .fa-wpbeginner:before { content: "\f297"; } .fa-wpforms:before { content: "\f298"; } .fa-envira:before { content: "\f299"; } .fa-universal-access:before { content: "\f29a"; } .fa-wheelchair-alt:before { content: "\f29b"; } .<API key>:before { content: "\f29c"; } .fa-blind:before { content: "\f29d"; } .<API key>:before { content: "\f29e"; } .<API key>:before { content: "\f2a0"; } .fa-braille:before { content: "\f2a1"; } .<API key>:before { content: "\f2a2"; } .fa-asl-interpreting:before, .<API key>:before { content: "\f2a3"; } .fa-deafness:before, .fa-hard-of-hearing:before, .fa-deaf:before { content: "\f2a4"; } .fa-glide:before { content: "\f2a5"; } .fa-glide-g:before { content: "\f2a6"; } .fa-signing:before, .fa-sign-language:before { content: "\f2a7"; } .fa-low-vision:before { content: "\f2a8"; } .fa-viadeo:before { content: "\f2a9"; } .fa-viadeo-square:before { content: "\f2aa"; } .fa-snapchat:before { content: "\f2ab"; } .fa-snapchat-ghost:before { content: "\f2ac"; } .fa-snapchat-square:before { content: "\f2ad"; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; } .sr-only-focusable:active, .sr-only-focusable:focus { position: static; width: auto; height: auto; margin: 0; overflow: visible; clip: auto; }
<?php /* Template Name: Default */ ?> <?php get_header(); ?> <div class="container"> <?php
// <API key>.h // ZYChat #import <Foundation/Foundation.h> #import "ZYDatabaseConst.h" @interface <API key> : NSObject @property (nonatomic,strong)NSString *colunmName; @property (nonatomic,assign)<API key> operation; @property (nonatomic,readonly)NSString *sqlString; @end
package aima.test.core.unit.search.online; import aima.core.agent.*; import aima.core.agent.impl.DynamicPercept; import aima.core.environment.map.ExtendableMap; import aima.core.environment.map.MapEnvironment; import aima.core.environment.map.MapFunctions; import aima.core.environment.map.MoveToAction; import aima.core.search.framework.problem.GeneralProblem; import aima.core.search.framework.problem.OnlineSearchProblem; import aima.core.search.online.LRTAStarAgent; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.function.Predicate; import java.util.function.ToDoubleFunction; public class LRTAStarAgentTest { private ExtendableMap aMap; private StringBuffer envChanges; private ToDoubleFunction<String> h; @Before public void setUp() { aMap = new ExtendableMap(); aMap.<API key>("A", "B", 4.0); aMap.<API key>("B", "C", 4.0); aMap.<API key>("C", "D", 4.0); aMap.<API key>("D", "E", 4.0); aMap.<API key>("E", "F", 4.0); h = (state) -> 1.0; envChanges = new StringBuffer(); } @Test public void testAlreadyAtGoal() { MapEnvironment me = new MapEnvironment(aMap); OnlineSearchProblem<String, MoveToAction> problem = new GeneralProblem<>(null, MapFunctions.<API key>(aMap), null, Predicate.isEqual("A"), MapFunctions.<API key>(aMap)); LRTAStarAgent<DynamicPercept, String, MoveToAction> agent = new LRTAStarAgent<> (problem, MapFunctions.<API key>(), h); me.addAgent(agent, "A"); me.<API key>(new TestEnvironmentView()); me.stepUntilDone(); Assert.assertEquals("", envChanges.toString()); } @Test public void testNormalSearch() { MapEnvironment me = new MapEnvironment(aMap); OnlineSearchProblem<String, MoveToAction> problem = new GeneralProblem<>(null, MapFunctions.<API key>(aMap), null, Predicate.isEqual("F"), MapFunctions.<API key>(aMap)); LRTAStarAgent<DynamicPercept, String, MoveToAction> agent = new LRTAStarAgent<> (problem, MapFunctions.<API key>(), h); me.addAgent(agent, "A"); me.<API key>(new TestEnvironmentView()); me.stepUntilDone(); Assert.assertEquals( "Action[name=moveTo, location=B]:Action[name=moveTo, location=A]:Action[name=moveTo, location=B]:Action[name=moveTo, location=C]:Action[name=moveTo, location=B]:Action[name=moveTo, location=C]:Action[name=moveTo, location=D]:Action[name=moveTo, location=C]:Action[name=moveTo, location=D]:Action[name=moveTo, location=E]:Action[name=moveTo, location=D]:Action[name=moveTo, location=E]:Action[name=moveTo, location=F]:", envChanges.toString()); } @Test public void testNoPath() { MapEnvironment me = new MapEnvironment(aMap); OnlineSearchProblem<String, MoveToAction> problem = new GeneralProblem<>(null, MapFunctions.<API key>(aMap), null, Predicate.isEqual("G"), MapFunctions.<API key>(aMap)); LRTAStarAgent<DynamicPercept, String, MoveToAction> agent = new LRTAStarAgent<> (problem, MapFunctions.<API key>(), h); me.addAgent(agent, "A"); me.<API key>(new TestEnvironmentView()); // Note: Will search forever if no path is possible, // Therefore restrict the number of steps to something // reasonablbe, against which to test. me.step(14); Assert.assertEquals( "Action[name=moveTo, location=B]:Action[name=moveTo, location=A]:Action[name=moveTo, location=B]:Action[name=moveTo, location=C]:Action[name=moveTo, location=B]:Action[name=moveTo, location=C]:Action[name=moveTo, location=D]:Action[name=moveTo, location=C]:Action[name=moveTo, location=D]:Action[name=moveTo, location=E]:Action[name=moveTo, location=D]:Action[name=moveTo, location=E]:Action[name=moveTo, location=F]:Action[name=moveTo, location=E]:", envChanges.toString()); } private class TestEnvironmentView implements EnvironmentListener<Object, Object> { public void notify(String msg) { envChanges.append(msg).append(":"); } public void agentAdded(Agent agent, Environment source) { // Nothing } public void agentActed(Agent agent, Object percept, Object action, Environment source) { envChanges.append(action).append(":"); } } }
# NOTICE: THIS FILE IS AUTOGENERATED # MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY # PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/reactor/<API key>.iff" result.<API key> = 8 result.stfName("space/space_item","<API key>") return result
import {browser, by, element} from 'protractor'; describe('button-toggle', () => { beforeEach(async () => await browser.get('/button-toggle')); it('should show a button-toggle', async () => { expect(await element(by.tagName('mat-button-toggle')).isPresent()).toBe(true); }); });
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Opgave 3</title> </head> <body> <h1>Controleer je lotnummer</h1> <form> <table> <tr> <td><label for="txt_lotnummer">Lotnummer:</label></td> <td><input id="txt_lotnummer" name="txt_lotnummer" type="text" value=""></td> </tr> <tr> <td>&nbsp;</td> <td><input type="button" id="knop" value="controleer"></td> </tr> <tr> <td>&nbsp;</td> <td><textarea id="txt_uitkomst" name="txt_uitkomst" type="text" value=""></textarea></td> </tr> </table> </form> <script> var winnendeLoten = ["123456","234567","345678","098765","876543"]; </script> </body> </html>
<?php include('mp.class.php'); $mpBox = new mpClass($user); ?> <div class="chat"> <div class="chat-header"> <h4 class="chat-title">Messagerie</h4> </div> <div class="chatbox"> <?php $mpBox->displayUserFollowed(); ?> </div> </div> <div class="messageBoxSpec"> <div class="messager"> <input type="hidden" value="" class="idConv" id="idConv"> <div class="messager-header"> <img src="" alt="chatter-img" class="messager-img"> <h5 class="messager-name"><div class="userName"></div></h5> <span class="chatter-closer">X</span> </div> <div class="messager-messages"> </div> <form action="" method="" class="messager-sender"> <input type="text" name="messenger" class="messager-input" placeholder="Message"> </form> </div> </div> <script src="js/chatter.js" type="text/javascript"></script>
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Text; using System.Xml; public static class PsdLayerPrefs { public static bool verbose = true; private static string filePath; private static XmlDocument xml = new XmlDocument(); private static XmlNode root; static PsdLayerPrefs() { var pathes = Directory.GetFiles(Directory.GetCurrentDirectory(), "PsdLayerPrefs.cs", SearchOption.AllDirectories); PsdLayerPrefs.filePath = Path.GetDirectoryName(pathes[0]) + "/PsdLayerPrefs.xml"; if (File.Exists(PsdLayerPrefs.filePath)) { PsdLayerPrefs.xml.Load(PsdLayerPrefs.filePath); } else { var node = PsdLayerPrefs.xml.CreateNode(XmlNodeType.Element, "Keys", null); PsdLayerPrefs.xml.AppendChild(node); PsdLayerPrefs.xml.Save(PsdLayerPrefs.filePath); } PsdLayerPrefs.root = PsdLayerPrefs.xml.DocumentElement; } public static void Load() { PsdLayerPrefs.xml.Load(PsdLayerPrefs.filePath); } public static void Save() { PsdLayerPrefs.xml.Save(PsdLayerPrefs.filePath); } public static bool HasKey(string key) { try { var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']"); return node != null; } catch (Exception e) { if (PsdLayerPrefs.verbose) Debug.LogError(e.Message); return false; } } public static bool DeleteKey(string key) { try { var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']"); PsdLayerPrefs.root.RemoveChild(node); return node != null; } catch (Exception e) { if (PsdLayerPrefs.verbose) Debug.LogError(e.Message); return false; } } #region Default SetTypes public static bool SetInt(string key, int v) { return PsdLayerPrefs.SetString(key, v.ToString()); } public static bool SetFloat(string key, float v) { return PsdLayerPrefs.SetString(key, v.ToString()); } public static bool SetString(string key, string v) { try { var child = PsdLayerPrefs.xml.CreateNode(XmlNodeType.Element, "Key", null); var name = PsdLayerPrefs.xml.CreateAttribute("Name"); var val = PsdLayerPrefs.xml.CreateAttribute("Value"); name.Value = key; val.Value = v; child.Attributes.Append(name); child.Attributes.Append(val); var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']"); if (node != null) node = PsdLayerPrefs.root.ReplaceChild(child, node); else node = PsdLayerPrefs.root.AppendChild(child); PsdLayerPrefs.Save(); } catch (Exception e) { if (PsdLayerPrefs.verbose) Debug.LogError(e.Message); return false; } return true; } #endregion #region Default GetTypes public static int GetInt(string key) { return PsdLayerPrefs.GetInt(key, 0); } public static float GetFloat(string key) { return PsdLayerPrefs.GetFloat(key, 0); } public static string GetString(string key) { return PsdLayerPrefs.GetString(key, ""); } public static int GetInt(string key, int defaultValue) { var ret = PsdLayerPrefs.GetString(key); return !string.IsNullOrEmpty(ret) ? int.Parse(ret) : defaultValue; } public static float GetFloat(string key, float defaultValue) { var ret = PsdLayerPrefs.GetString(key); return !string.IsNullOrEmpty(ret) ? float.Parse(ret) : defaultValue; } public static string GetString(string key, string defaultValue) { try { var node = PsdLayerPrefs.root.SelectSingleNode("//Key[@Name='" + key + "']"); return node != null ? node.Attributes["Value"].Value : defaultValue; } catch (Exception e) { if (PsdLayerPrefs.verbose) Debug.LogError(e.Message); return defaultValue; } } #endregion #region String Array public static bool SetStringArray(string key, char separator, params string[] strings) { try { if (strings.Length == 0) PsdLayerPrefs.SetString(key, ""); else PsdLayerPrefs.SetString(key, string.Join(separator.ToString(), strings)); } catch (Exception e) { if (PsdLayerPrefs.verbose) Debug.LogError(e.Message); return false; } return true; } public static bool SetStringArray(string key, params string[] strings) { if (!PsdLayerPrefs.SetStringArray(key, "\n"[0], strings)) return false; return true; } public static string[] GetStringArray(string key, char separator) { if (PsdLayerPrefs.HasKey(key)) return PsdLayerPrefs.GetString(key).Split(separator); return new string[0]; } public static string[] GetStringArray(string key) { if (PsdLayerPrefs.HasKey(key)) return PsdLayerPrefs.GetString(key).Split("\n"[0]); return new string[0]; } public static string[] GetStringArray(string key, char separator, string defaultValue, int defaultSize) { if (PsdLayerPrefs.HasKey(key)) return PsdLayerPrefs.GetString(key).Split(separator); var strings = new string[defaultSize]; for (int i = 0; i < defaultSize; i++) strings[i] = defaultValue; return strings; } public static string[] GetStringArray(string key, string defaultValue, int defaultSize) { return PsdLayerPrefs.GetStringArray(key, "\n"[0], defaultValue, defaultSize); } #endregion };
using UnityEngine; using System.Collections; public class <API key> : MonoBehaviour { [SerializeField] private iGUI.iGUIImage m_image; [SerializeField] private Texture2D m_white; public void FadeoutFromBlack(float tFadeSec, float tFadeDelaySec = 0.0f, CommandChain cc = null) { StartCoroutine(_Fade(1.0f,0.0f, m_white, true, Color.black,tFadeSec,tFadeDelaySec, cc)); } public void FadeinToBlack(float tFadeSec, float tFadeDelaySec = 0.0f, CommandChain cc = null) { StartCoroutine(_Fade(0.0f,1.0f, m_white, true, Color.black,tFadeSec,tFadeDelaySec, cc)); } public void FadeInImage(Texture img, float tFadeSec, float tFadeDelaySec = 0.0f, CommandChain cc = null) { StartCoroutine(_Fade(0.0f,1.0f, img, true, Color.white,tFadeSec,tFadeDelaySec, cc)); } public void Fadeout(float tFadeSec, float tFadeDelaySec = 0.0f, CommandChain cc = null) { StartCoroutine(_Fade(1.0f,0.0f, null, false, Color.white, tFadeSec,tFadeDelaySec, cc)); } private IEnumerator _Fade(float from, float to, Texture img, bool applyBgColor, Color bgColor, float tFadeSec, float tFadeDelaySec, CommandChain cc) { if( applyBgColor ) { m_image.setBackgroundColor(bgColor); } if(img != null) { m_image.image = img; } m_image.opacity = from; m_image.enabled = true; if( tFadeDelaySec > 0.0f ) { yield return new WaitForSeconds(tFadeDelaySec); } float tStart = Time.time; while( Time.time - tStart < tFadeSec ) { float t = (Time.time - tStart) / tFadeSec; float v = (to - from) * t; if( to < from && v <= 0.0f) v = 1.0f + v; // v is negative m_image.opacity = v; yield return new WaitForEndOfFrame(); } m_image.opacity = to; m_image.enabled = to > 0.0f; if(cc) { cc.FireCommand(); } } }
#include "../include/pubsub_app.h" mal_actor_t *subscriber_actor = NULL; mal_actor_t *publisher_actor = NULL; mal_actor_t *broker_actor = NULL; // Selftest int <API key>( bool verbose, mal_ctx_t *mal_ctx, mal_uri_t *provider_uri, mal_uri_t *broker_uri, mal_encoder_t *encoder, mal_decoder_t *decoder) { int rc = 0; printf(" * <API key>: \n"); mal_blob_t *authentication_id = mal_blob_new(0); mal_qoslevel_t qoslevel = <API key>; mal_uinteger_t priority = 4; <API key> *domain = <API key>(0); mal_identifier_t *network_zone = mal_identifier_new("Network Zone"); mal_sessiontype_t session = <API key>; mal_identifier_t *session_name = mal_identifier_new("LIVE"); <API key> *provider = <API key>(broker_uri, authentication_id, qoslevel, priority, domain, network_zone, session, session_name, encoder, decoder); publisher_actor = mal_actor_new( mal_ctx, provider_uri, provider, <API key>, <API key>); printf(" * pubsub_app create provider actor: %s\n", mal_actor_get_uri(publisher_actor)); return rc; } int <API key>( bool verbose, mal_ctx_t *mal_ctx, mal_uri_t *consumer_uri, mal_uri_t *broker_uri, mal_encoder_t *encoder, mal_decoder_t *decoder) { int rc = 0; printf(" * <API key>: \n"); mal_blob_t *authentication_id = mal_blob_new(0); mal_qoslevel_t qoslevel = <API key>; mal_uinteger_t priority = 4; <API key> *domain = <API key>(0); mal_identifier_t *network_zone = mal_identifier_new("Network Zone"); mal_sessiontype_t session = <API key>; mal_identifier_t *session_name = mal_identifier_new("LIVE"); <API key> *consumer = <API key>(broker_uri, authentication_id, qoslevel, priority, domain, network_zone, session, session_name, encoder, decoder); subscriber_actor = mal_actor_new( mal_ctx, consumer_uri, consumer, <API key>, <API key>); printf(" * pubsub_app create consumer actor: %s\n", mal_actor_get_uri(subscriber_actor)); return rc; } int <API key>( bool verbose, mal_ctx_t *mal_ctx, mal_uri_t *consumer_uri, mal_uri_t *provider_uri, mal_uri_t *broker_uri, mal_encoder_t *encoder, mal_decoder_t *decoder) { int rc = 0; printf(" * <API key>: \n"); mal_blob_t *authentication_id = mal_blob_new(0); mal_qoslevel_t qoslevel = <API key>; mal_uinteger_t priority = 4; <API key> *domain = <API key>(0); mal_identifier_t *network_zone = mal_identifier_new("Network Zone"); mal_sessiontype_t session = <API key>; mal_identifier_t *session_name = mal_identifier_new("LIVE"); pubsub_app_broker_t *broker = <API key>(provider_uri, authentication_id, qoslevel, priority, domain, network_zone, session, session_name, encoder, decoder); assert(broker); broker_actor = mal_actor_new( mal_ctx, broker_uri, broker, <API key>, <API key>); printf(" * pubsub_app create broker actor: %s\n", mal_actor_get_uri(broker_actor)); return rc; } void pubsub_app_test(bool verbose) { printf(" * pubsub_app: \n"); // @selftest mal_ctx_t *mal_ctx = mal_ctx_new(); mal_encoder_t *encoder = <API key>(false); mal_decoder_t *decoder = <API key>(false); // All the MAL header fields are passed malzmq_header_t *malzmq_header = malzmq_header_new(NULL, true, 0, true, NULL, NULL, NULL, NULL); // Enables the internal broker mechanism <API key>(malzmq_header, false); // Change the logging level of malzmq transport <API key>(CLOG_DEBUG_LEVEL); // This test uses the same encoding configuration at the MAL/ZMQ transport level // (MAL header encoding) and at the application level (MAL message body encoding) malzmq_ctx_new( mal_ctx, NULL, // Use default transformation of MAL URI to ZMQ URI "localhost", "6666", malzmq_header, true); mal_uri_t *provider_uri = mal_ctx_create_uri(mal_ctx, "pubsub_app/myprovider"); printf("pubsub_app: provider URI: %s\n", provider_uri); mal_uri_t *consumer_uri = mal_ctx_create_uri(mal_ctx, "pubsub_app/mysubscriber"); printf("pubsub_app: mysubscriber URI: %s\n", consumer_uri); mal_uri_t *broker_uri = mal_ctx_create_uri(mal_ctx, "pubsub_app/broker"); printf("pubsub_app: broker URI: %s\n", broker_uri); <API key>(verbose, mal_ctx, consumer_uri, provider_uri, broker_uri, encoder, decoder); <API key>(verbose, mal_ctx, consumer_uri, broker_uri, encoder, decoder); <API key>(verbose, mal_ctx, provider_uri, broker_uri, encoder, decoder); // @end printf("OK\n"); // Start blocks until interrupted (see zloop). mal_ctx_start(mal_ctx); printf("Stopped.\n"); mal_actor_join(subscriber_actor); mal_actor_destroy(mal_ctx, &subscriber_actor); mal_actor_join(publisher_actor); mal_actor_destroy(mal_ctx, &publisher_actor); mal_actor_join(broker_actor); mal_actor_destroy(mal_ctx, &broker_actor); mal_ctx_destroy(&mal_ctx); printf("destroyed.\n"); }
body { background-image: url("/images/<API key>.jpg"); background-repeat: no-repeat; background-size: cover; background-position: center center; } .periodic-item { 1background-repeat: no-repeat; background-size: 100% 100%; width: 120px; height: 160px; -<API key>: 3px; border-radius: 3px; -webkit-box-shadow: 0 0 12px rgba(231,254,237,0.6); box-shadow: 0 0 12px rgba(231,254,237,0.6); color: rgba(240,240,240,0.8); text-align: center; -<API key>: visible; backface-visibility: visible; } .periodic-item-hq { 1background-repeat: no-repeat; background-size: 100% 100%; width: 360px; height: 480px; -<API key>: 9px; -webkit-box-shadow: 0 0 36px rgba(231,254,237,0.6); border-radius: 9px; box-shadow: 0 0 36px rgba(231,254,237,0.6); color: rgba(240,240,240,0.8); text-align: center; -<API key>: hidden; backface-visibility: hidden; } .periodic-item-back { width: 240px; height: 360px; padding: 60px 60px; -<API key>: hidden; backface-visibility: hidden; overflow: hidden; } .periodic-item .name { position: absolute; bottom: 4px; left: 0px; right: 0px; font-size: 12px; font-weight: bold; color: #fff; background-color: rgba(120, 125, 115, 0.7); } .periodic-item-hq .name { position: absolute; bottom: 10px; left: 0px; right: 0px; font-size: 36px; font-weight: bold; } .periodic-item .mass { position: absolute; bottom: 15px; left: 0px; right: 0px; font-size: 12px; } .periodic-item-hq .mass { position: absolute; bottom: 45px; left: 0px; right: 0px; font-size: 36px; } .caption { width: 200px; height: 32px; text-align: center; font-family: helvetica, sans-serif; font-size: 32px; text-shadow: 0 0 10px #3cf; -webkit-text-stroke: .2px #3cf; color: #fff; } .play-button { width: 200px; height: 200px; background-repeat: no-repeat; background-position: center center; cursor: pointer; } .overlay-text { color: #fff; font-size: 20px; line-height: 20px; padding: 20px 20px; text-shadow: 0 0 10px #3cf; -webkit-text-stroke: .2px #3cf; text-align: left; } .info-button { color: #fff; font-size: 13px; line-height: 20px; padding: 20px 20px; text-align: right; cursor: pointer; } .shape-button { text-align: center; font-size: 20px; line-height: 30px; padding: 15px 15px; cursor: pointer; } .<API key> { pointer-events: none; } .<API key> { -webkit-box-shadow: 0px 0px 3px #3cf; box-shadow: 0px 0px 10px #3cf; border: 1px solid #fff; width: 30px; height: 30px; margin: 14px 14px; } .shape-button img { width: 30px; height: 30px; } .shape-flash { color: #fff; font-size: 50px; line-height: 50px; text-align: center; text-shadow: 0 0 10px #3cf; } .clickable-text { cursor: pointer; } .copyright { color: rgba(255,255,255,0.6); font-size: 10px; line-height: 20px; padding: 20px 20px; pointer-events: none; } .info { background-color: rgba(255,255,255,0.8); margin: 0px; padding: 30px; overflow: hidden; border-radius: 10px; color: #333; font-size: 20px; -webkit-box-shadow: 0px 0px 10px #3cf; box-shadow: 0px 0px 10px #3cf; } .info h3 { text-align: center; } .info .control { display: block; width: 100%; margin: 30px 0px; text-align: center; } .info button { font-size: 20px; border-radius: 5px; color: #fff; padding: 4px 10px; -webkit-box-shadow: inset 0 0 3px #60cbfa, 0 0 50px rgb(50,200,255, 0.5); text-shadow: 0 -1px rgba(0,0,0,0.5); border-color: #34BFF3 rgba(0,0,0,0.05) #003C8B; background: #34BFF3; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #34BFF3), color-stop(100%, #074AA2)); background: -<API key>(#34BFF3,#074AA2); background: -moz-linear-gradient(#34BFF3,#074AA2); background: -o-linear-gradient(#34BFF3,#074AA2); background: -ms-linear-gradient(#34BFF3,#074AA2); background: linear-gradient(#34BFF3,#074AA2); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-9 */ -webkit-user-select: none; } .obscure { background-color: rgba(0,0,0,0.5); } .bottom-bar { background-color: rgba(0,0,0,0.7); pointer-events: none; } .signup-box { background-color: rgba(52, 56, 63, 0.88); border: 3px solid #fff; padding: 30px 50px; border-radius: 10px; color: #fff; font-size: 20px; line-height: 40px; -webkit-box-shadow: 0 0 20px #F1D6DC; box-shadow: 0 0 20px #F1D6DC; text-align: center; } .signup-box h3 { font-size: 45px; font-weight: normal; margin: 10px; } .signup-box .sub { font-size: 13px; font-style: italic; } .centralImg{ background-image: url("/images/martijn.jpg"); height: 200px; width: 400px; background-size: contain; margin-left: auto; margin-right: auto; } #video{ height: 200px; width: 400px; } .signup-box p { text-align: right; padding-bottom: 1em; } .signup-box .experience { font-weight: bold; margin: 0; padding: 0; } .signup-hide { font-size: 20px; line-height: 80px; padding: 10px; text-align: center; cursor: pointer; color: #fff; } .signup-hide img { width: 15px; height: 15px; display: none; } .signup-show { font-size: 13px; line-height: 20px; padding: 3px; text-align: center; cursor: pointer; color: #fff; background-color: rgba(52, 56, 63, 0.88); border-radius: 3px 3px 0px 0px; border-top: 1px solid #fff; border-left: 1px solid #fff; border-bottom: none; border-right: 1px solid #fff; } .signup { text-align: center; margin-left: 10px; } .signup p { padding: 0px 30px 20px 30px; margin: 0; color: #fff; } .signup input { border: 1px solid #fff; border-radius: 5px; font-size: 15px; margin: 20px 10px; } .input { float: left; margin-left: 110px; } .signup input[type=text] { -webkit-appearance: none; width: 400px; height: 20px; padding: 5px; margin: 5px; float: left; background-color: #fff; border: none; -webkit-box-shadow: inset 0 0 3px #000; box-shadow: inset 0 0 3px #000; } .signup input[type=text].half { width: 190px; } #cameraBtn{ background-image: url("/images/cam.png"); } .camLabel{ width:160px; height:130px; display: inline-block; overflow:hidden; position:relative; cursor: pointer; _cursor: hand; margin-left: auto; margin-right: auto; margin-top: 50px; -webkit-box-shadow: inset 0 0 3px #60cbfa, 0 0 50px rgb(50,200,255, 0.5); box-shadow: inset 0 0 3px #60cbfa, 0 0 50px rgb(50,200,255, 0.5); text-shadow: 0 -1px rgba(0,0,0,0.5); border-color: #34BFF3 rgba(0,0,0,0.05) #003C8B; background: #D8DFE2; border-radius: 15px; font-size: 16px; } .camLabel img{ display: block; margin-left: auto; margin-right: auto; } label span input { z-index: 999; line-height: 0; font-size: 50px; position: absolute; top: -2px; left: -700px; opacity: 0; filter: alpha(opacity = 0); -ms-filter: "alpha(opacity=0)"; cursor: pointer; _cursor: hand; margin: 0; padding:0; } .signup input[type=submit] { width: 410px; height: 100px; clear: both; float: left; color: #fff; font-size: 36px; padding: 4px; margin-left: 80px; margin-top: 50px; -webkit-box-shadow: inset 0 0 3px #60cbfa, 0 0 50px rgb(50,200,255, 0.5); box-shadow: inset 0 0 3px #60cbfa, 0 0 50px rgb(50,200,255, 0.5); text-shadow: 0 -1px rgba(0,0,0,0.5); border-color: #34BFF3 rgba(0,0,0,0.05) #003C8B; background: #34BFF3; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #34BFF3), color-stop(100%, #074AA2)); background: -<API key>(#34BFF3,#074AA2); background: -moz-linear-gradient(#34BFF3,#074AA2); background: -o-linear-gradient(#34BFF3,#074AA2); background: -ms-linear-gradient(#34BFF3,#074AA2); background: linear-gradient(#34BFF3,#074AA2); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-9 */ cursor: pointer; } .signup-error { color: #fc0; font-size: 18px; text-align: center; } a, a:visited { color: #fff; text-decoration: none; } #overlay { /*background-image: -<API key>(rgba(0,0,0,0), rgba(0,0,0,0.5));*/ -webkit-transform: translateZ(999px); -webkit-perspective: 0px; perspective: 0px; } @media only screen and (min-device-width: 768px) and (max-device-width: 1024px), only screen and (max-device-width: 480px) { #overlay { -webkit-transform: translateZ(99999px); } }
import time import functools import itertools as it import requests from requests.exceptions import ConnectTimeout, ReadTimeout, ConnectionError from circuit import CircuitOpenError import logging from .breaker import CircuitBreakerSet from .exceptions import <API key>, MaxRetriesReached logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class Retriable(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, **new_kwargs): kwargs = self.kwargs.copy() kwargs.update(new_kwargs) return self.func(*self.args, **kwargs) def __repr__(self): return '<Retriable (%s, %s, %s)>' % (self.func, self.args, self.kwargs) class SmartClient(object): '''This client is used when dealing with existing client libraries that issue their own requests (whether HTTP or some other protocol). This client then provides To create an instance, you need to let it know about the types of errors that it can catch in order to retry. For HTTP, this is typically connection releated errors, however your library might wrap them. There are 2 ways to make a function retriable. The first is by creating a retriable object:: # create the signature retriable = smart_client.Retriable(my_client.retrieve, id) # now execute it item = smart_client.retry(retriable, max_tries=5) The second is using retry() as as decorator: @smart_client.retry def get_object(id): return my_client.retrieve(id) @smart_client.retry(max_tries=5) def get_object(id): return my_client.retrieve(id) ''' Retriable = Retriable def __init__(self, name, error_types=None, hosts_provider=None, hosts=None): self.name = name self.error_types = error_types self.breakers = CircuitBreakerSet(error_types or []) # TODO: Check that one and only one of these is specified. self._hosts_iter = it.cycle(hosts) if hosts else None self._hosts_provider = hosts_provider def get_hostname(self): if self._hosts_provider: return self._hosts_provider.get_hostname() else: return next(self._hosts_iter) def retry(self, retriable=None, max_tries=3, backoff=None, send_host=False): # Creating a decorator: @client.retry(max_tries=5) if retriable is None: return functools.partial(self.retry, max_tries=max_tries, backoff=backoff, send_host=send_host) # Being used as a decorator: @client.retry if not isinstance(retriable, Retriable): @functools.wraps(retriable) def wrapper(*args, **kwargs): _retriable = Retriable(retriable, *args, **kwargs) self.retry(_retriable, max_tries=max_tries, backoff=backoff, send_host=send_host) return wrapper # actually do the retries for i in xrange(1, max_tries + 1): host = self.get_hostname() try: logger.info('Attempting %s for host %s ...' % (retriable, host)) with self.breakers.context(host): if send_host: return retriable(host=host) else: return retriable() except CircuitOpenError: if self.breakers.all_closed(): raise AllHostsUnreachable('All hosts unreachable for %s' % self.name) logger.warning('Silenced request failure for host %s due to CircuitOpenError.', host) except tuple(self.breakers.error_types) as e: logger.warning('Silenced %s for host %s.', e, host) if backoff and i < max_tries: # Don't sleep after last attempt time.sleep(backoff() if callable(backoff) else backoff) raise MaxRetriesReached('Attempted %d times for %s' % (max_tries, self.name)) class SmartHTTPClient(SmartClient): '''A smart HTTP client that knows about the requests library's error types. You must provided a hosts_provider or a host list. ''' HTTP_ERROR_TYPES = (ConnectTimeout, ReadTimeout, ConnectionError) def __init__(self, name, hosts_provider=None, hosts=None): super(SmartHTTPClient, self).__init__(name, self.HTTP_ERROR_TYPES, hosts_provider, hosts) # Keep a session per host self._sessions = {} def get(self, path, *args, **kwargs): req = self.Retriable(self._send, 'GET', path, *args, **kwargs) return self.retry(req, send_host=True) def _send(self, method, path, host=None, **kwargs): url = 'http://' + host + '/' + path.lstrip('/') session = self.get_session(host) prepared = session.prepare_request(requests.Request(method, url, **kwargs)) return session.send(prepared) def get_session(self, hostname): session = self._sessions.get(hostname) if not session: session = self._sessions[hostname] = requests.Session() return session
package May2021PrepLeetcode; public class <API key> { public static void main(String[] args) { System.out.println(compress(new char[] { 'a', 'a', 'b', 'b', 'c', 'c', 'c' })); } public static int compress(char[] chars) { if (chars == null || chars.length == 0) return 0; int index = 0; char prevChar = chars[0]; int count = 1; for (int i = 1; i < chars.length; i++) { if (chars[i] == prevChar) { count++; } else { chars[index++] = prevChar; if (count > 1) { String str = String.valueOf(count); for (int j = 0; j < str.length(); j++) { chars[index++] = str.charAt(j); } } prevChar = chars[i]; count = 1; } } chars[index++] = prevChar; if (count > 1) { String str = String.valueOf(count); for (int j = 0; j < str.length(); j++) { chars[index++] = str.charAt(j); } } return index; } }
import logging import homeassistant.components.rfxtrx as rfxtrx from homeassistant.components.light import ATTR_BRIGHTNESS, Light from homeassistant.components.rfxtrx import ( ATTR_FIREEVENT, ATTR_NAME, ATTR_PACKETID, ATTR_STATE, <API key>) from homeassistant.const import ATTR_ENTITY_ID from homeassistant.util import slugify DEPENDENCIES = ['rfxtrx'] SIGNAL_REPETITIONS = 1 _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, <API key>, discovery_info=None): """Setup the RFXtrx platform.""" import RFXtrx as rfxtrxmod lights = [] signal_repetitions = config.get('signal_repetitions', SIGNAL_REPETITIONS) for device_id, entity_info in config.get('devices', {}).items(): if device_id in rfxtrx.RFX_DEVICES: continue _LOGGER.info("Add %s rfxtrx.light", entity_info[ATTR_NAME]) # Check if i must fire event fire_event = entity_info.get(ATTR_FIREEVENT, False) datas = {ATTR_STATE: False, ATTR_FIREEVENT: fire_event} rfxobject = rfxtrx.get_rfx_object(entity_info[ATTR_PACKETID]) new_light = RfxtrxLight( entity_info[ATTR_NAME], rfxobject, datas, signal_repetitions) rfxtrx.RFX_DEVICES[device_id] = new_light lights.append(new_light) <API key>(lights) def light_update(event): """Callback for light updates from the RFXtrx gateway.""" if not isinstance(event.device, rfxtrxmod.LightingDevice) or \ not event.device.<API key>: return # Add entity if not exist and the automatic_add is True device_id = slugify(event.device.id_string.lower()) if device_id not in rfxtrx.RFX_DEVICES: automatic_add = config.get('automatic_add', False) if not automatic_add: return _LOGGER.info( "Automatic add %s rfxtrx.light (Class: %s Sub: %s)", device_id, event.device.__class__.__name__, event.device.subtype ) pkt_id = "".join("{0:02x}".format(x) for x in event.data) entity_name = "%s : %s" % (device_id, pkt_id) datas = {ATTR_STATE: False, ATTR_FIREEVENT: False} signal_repetitions = config.get('signal_repetitions', SIGNAL_REPETITIONS) new_light = RfxtrxLight(entity_name, event, datas, signal_repetitions) rfxtrx.RFX_DEVICES[device_id] = new_light <API key>([new_light]) # Check if entity exists or previously added automatically if device_id in rfxtrx.RFX_DEVICES: _LOGGER.debug( "EntityID: %s light_update. Command: %s", device_id, event.values['Command'] ) if event.values['Command'] == 'On'\ or event.values['Command'] == 'Off': # Update the rfxtrx device state is_on = event.values['Command'] == 'On' # pylint: disable=protected-access rfxtrx.RFX_DEVICES[device_id]._state = is_on rfxtrx.RFX_DEVICES[device_id].update_ha_state() elif event.values['Command'] == 'Set level': # pylint: disable=protected-access rfxtrx.RFX_DEVICES[device_id]._brightness = \ (event.values['Dim level'] * 255 // 100) # Update the rfxtrx device state is_on = rfxtrx.RFX_DEVICES[device_id]._brightness > 0 rfxtrx.RFX_DEVICES[device_id]._state = is_on rfxtrx.RFX_DEVICES[device_id].update_ha_state() else: return # Fire event if rfxtrx.RFX_DEVICES[device_id].should_fire_event: rfxtrx.RFX_DEVICES[device_id].hass.bus.fire( <API key>, { ATTR_ENTITY_ID: rfxtrx.RFX_DEVICES[device_id].entity_id, ATTR_STATE: event.values['Command'].lower() } ) # Subscribe to main rfxtrx events if light_update not in rfxtrx.<API key>: rfxtrx.<API key>.append(light_update) class RfxtrxLight(Light): """Represenation of a RFXtrx light.""" def __init__(self, name, event, datas, signal_repetitions): """Initialize the light.""" self._name = name self._event = event self._state = datas[ATTR_STATE] self._should_fire_event = datas[ATTR_FIREEVENT] self.signal_repetitions = signal_repetitions self._brightness = 0 @property def should_poll(self): """No polling needed for a light.""" return False @property def name(self): """Return the name of the light if any.""" return self._name @property def should_fire_event(self): """Return true if the device must fire event.""" return self._should_fire_event @property def is_on(self): """Return true if light is on.""" return self._state @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def assumed_state(self): """Return True if unable to access real state of entity.""" return True def turn_on(self, **kwargs): """Turn the light on.""" brightness = kwargs.get(ATTR_BRIGHTNESS) if not self._event: return if brightness is None: self._brightness = 255 for _ in range(self.signal_repetitions): self._event.device.send_on(rfxtrx.RFXOBJECT.transport) else: self._brightness = brightness _brightness = (brightness * 100 // 255) for _ in range(self.signal_repetitions): self._event.device.send_dim(rfxtrx.RFXOBJECT.transport, _brightness) self._state = True self.update_ha_state() def turn_off(self, **kwargs): """Turn the light off.""" if not self._event: return for _ in range(self.signal_repetitions): self._event.device.send_off(rfxtrx.RFXOBJECT.transport) self._brightness = 0 self._state = False self.update_ha_state()
import org.scalatest.{Matchers, FunSuite} /** @version 1.1.0 */ class SayTest extends FunSuite with Matchers { test("zero") { Say.inEnglish(0) should be(Some("zero")) } test("one") { pending Say.inEnglish(1) should be(Some("one")) } test("fourteen") { pending Say.inEnglish(14) should be(Some("fourteen")) } test("twenty") { pending Say.inEnglish(20) should be(Some("twenty")) } test("twenty-two") { pending Say.inEnglish(22) should be(Some("twenty-two")) } test("one hundred") { pending Say.inEnglish(100) should be(Some("one hundred")) } test("one hundred twenty-three") { pending Say.inEnglish(123) should be(Some("one hundred twenty-three")) } test("one thousand") { pending Say.inEnglish(1000) should be(Some("one thousand")) } test("one thousand two hundred thirty-four") { pending Say.inEnglish(1234) should be(Some("one thousand two hundred thirty-four")) } test("one million") { pending Say.inEnglish(1000000) should be(Some("one million")) } test("one million two thousand three hundred forty-five") { pending Say.inEnglish(1002345) should be(Some("one million two thousand three hundred forty-five")) } test("one billion") { pending Say.inEnglish(1000000000) should be(Some("one billion")) } test("a big number") { pending Say.inEnglish(987654321123l) should be(Some("nine hundred eighty-seven billion six hundred fifty-four million three hundred twenty-one thousand one hundred twenty-three")) } test("numbers below zero are out of range") { pending Say.inEnglish(-1) should be(None) } test("numbers above 999,999,999,999 are out of range") { pending Say.inEnglish(1000000000000l) should be(None) } }
<!DOCTYPE html> <html lang="en"> <head> <title>PresenterObjc Class Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset='utf-8'> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> </head> <body> <a name="//apple_ref/swift/Class/PresenterObjc" class="dashAnchor"></a> <a title="PresenterObjc Class Reference"></a> <header> <div class="content-wrapper"> <p><a href="../index.html">VISPER-Objc Docs</a> (18% documented)</p> <p class="header-right"><a href="https://github.com/barteljan/VISPER.git"><img src="../img/gh.png"/>View on GitHub</a></p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="../index.html">VISPER-Objc Reference</a> <img id="carat" src="../img/carat.png" /> PresenterObjc Class Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/ObjcWrapper.html">ObjcWrapper</a> </li> <li class="nav-group-task"> <a href="../Classes/PresenterObjc.html">PresenterObjc</a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/RouteResultObjc.html">RouteResultObjc</a> </li> <li class="nav-group-task"> <a href="../Classes/RoutingDelegateObjc.html">RoutingDelegateObjc</a> </li> <li class="nav-group-task"> <a href="../Classes/RoutingObserverObjc.html">RoutingObserverObjc</a> </li> <li class="nav-group-task"> <a href="../Classes/RoutingOptionObjc.html">RoutingOptionObjc</a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Classes/WireframeObjc.html">WireframeObjc</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Protocols/ObjcWrapperProvider.html">ObjcWrapperProvider</a> </li> <li class="nav-group-task"> <a href="../Protocols/PresenterObjcType.html">PresenterObjcType</a> </li> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Protocols/RouteResultObjcType.html">RouteResultObjcType</a> </li> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> <li class="nav-group-task"> <a href="../Protocols/<API key>.html"><API key></a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>PresenterObjc</h1> <div class="declaration"> <div class="language"> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">open</span> <span class="kd">class</span> <span class="kt">PresenterObjc</span> <span class="p">:</span> <span class="kt">NSObject</span><span class="p">,</span> <span class="kt">Presenter</span><span class="p">,</span> <span class="kt"><a href="../Protocols/PresenterObjcType.html">PresenterObjcType</a></span></code></pre> </div> </div> <p>Undocumented</p> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:<API key>"></a> <a name="//apple_ref/swift/Property/presenter" class="dashAnchor"></a> <a class="token" href="#/s:<API key>">presenter</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="k">let</span> <span class="nv">presenter</span><span class="p">:</span> <span class="kt">Presenter</span><span class="p">?</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:<API key>"></a> <a name="//apple_ref/swift/Property/presenterObjc" class="dashAnchor"></a> <a class="token" href="#/s:<API key>">presenterObjc</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="k">let</span> <span class="nv">presenterObjc</span><span class="p">:</span> <span class="kt"><a href="../Protocols/PresenterObjcType.html">PresenterObjcType</a></span><span class="p">?</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:<API key>"></a> <a name="//apple_ref/swift/Method/init(presenter:)" class="dashAnchor"></a> <a class="token" href="#/s:<API key>">init(presenter:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">presenter</span><span class="p">:</span> <span class="kt">Presenter</span><span class="p">)</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:<API key>"></a> <a name="//apple_ref/swift/Method/init(presenter:)" class="dashAnchor"></a> <a class="token" href="#/s:<API key>">init(presenter:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">presenter</span><span class="p">:</span> <span class="kt"><a href="../Protocols/PresenterObjcType.html">PresenterObjcType</a></span><span class="p">)</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:11VISPER_Objc09PresenterB0C13isResponsible11routeResult10controllerSb0A5_Core05RouteG0_p_So16UIViewControllerCtF"></a> <a name="//apple_ref/swift/Method/isResponsible(routeResult:controller:)" class="dashAnchor"></a> <a class="token" href="#/s:11VISPER_Objc09PresenterB0C13isResponsible11routeResult10controllerSb0A5_Core05RouteG0_p_So16UIViewControllerCtF">isResponsible(routeResult:controller:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">isResponsible</span><span class="p">(</span><span class="nv">routeResult</span><span class="p">:</span> <span class="kt">RouteResult</span><span class="p">,</span> <span class="nv">controller</span><span class="p">:</span> <span class="kt">UIViewController</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@VISPER_Objc@objc(cs)PresenterObjc(im)<API key>:controller:"></a> <a name="//apple_ref/swift/Method/isResponsible(routeResult:controller:)" class="dashAnchor"></a> <a class="token" href="#/c:@M@VISPER_Objc@objc(cs)PresenterObjc(im)<API key>:controller:">isResponsible(routeResult:controller:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">open</span> <span class="kd">func</span> <span class="nf">isResponsible</span><span class="p">(</span><span class="nv">routeResult</span><span class="p">:</span> <span class="kt"><a href="../Classes/RouteResultObjc.html">RouteResultObjc</a></span><span class="p">,</span> <span class="nv">controller</span><span class="p">:</span> <span class="kt">UIViewController</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:11VISPER_Core9PresenterP20addPresentationLogic11routeResult10controlleryAA05RouteH0_p_So16UIViewControllerCtKF"></a> <a name="//apple_ref/swift/Method/<API key>(routeResult:controller:)" class="dashAnchor"></a> <a class="token" href="#/s:11VISPER_Core9PresenterP20addPresentationLogic11routeResult10controlleryAA05RouteH0_p_So16UIViewControllerCtKF"><API key>(routeResult:controller:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">open</span> <span class="kd">func</span> <span class="nf"><API key></span><span class="p">(</span><span class="nv">routeResult</span><span class="p">:</span> <span class="kt">RouteResult</span><span class="p">,</span> <span class="nv">controller</span><span class="p">:</span> <span class="kt">UIViewController</span><span class="p">)</span> <span class="k">throws</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@VISPER_Objc@objc(cs)PresenterObjc(im)<API key>:controller:error:"></a> <a name="//apple_ref/swift/Method/<API key>(routeResult:controller:)" class="dashAnchor"></a> <a class="token" href="#/c:@M@VISPER_Objc@objc(cs)PresenterObjc(im)<API key>:controller:error:"><API key>(routeResult:controller:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">open</span> <span class="kd">func</span> <span class="nf"><API key></span><span class="p">(</span><span class="nv">routeResult</span><span class="p">:</span> <span class="kt"><a href="../Classes/RouteResultObjc.html">RouteResultObjc</a></span><span class="p">,</span> <span class="nv">controller</span><span class="p">:</span> <span class="kt">UIViewController</span><span class="p">)</span> <span class="k">throws</span></code></pre> </div> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2019 <a class="link" href="https: <p>Generated by <a class="link" href="https: </section> </article> </div> </body> </div> </html>
#region Usings using System.Collections.Generic; using System.Globalization; using Utilities.Web.ExtensionMethods; using Utilities.Web.Google.BaseClasses; using Utilities.Web.Google.Enums; using Utilities.Web.Google.HelperClasses; using Utilities.Web.Google.Interfaces; #endregion namespace Utilities.Web.Google.StaticMaps { <summary> Static Maps API helper </summary> public class Map:APIBase { #region Constructor <summary> Constructor </summary> public Map() : base() { Zoom = 12; Width = 100; Height = 100; Scale = 1; Format = ImageFormat.PNG; MapType = MapType.RoadMap; Sensor = false; Markers = new List<Markers>(); } #endregion #region Properties <summary> API location </summary> public override string APILocation { get { return (UseHTTPS ? "https: <summary> Center of the map </summary> public ILocation Center { get; set; } <summary> Zoom level (should be between 0 and 21 </summary> public int Zoom { get; set; } <summary> Width of the map </summary> public int Width { get; set; } <summary> Height of the map </summary> public int Height { get; set; } <summary> Scale of the map (values are 1, 2, and 4 for business customers) </summary> public int Scale { get; set; } <summary> Image format </summary> public ImageFormat Format { get; set; } <summary> Map type </summary> public MapType MapType { get; set; } <summary> Language for the map to use </summary> public string Language { get; set; } <summary> Displays appropriate borders based on geo-political sensitivities (uses two-character ccTLD values) </summary> public string Region { get; set; } <summary> A list of markers </summary> public ICollection<Markers> Markers { get; private set; } <summary> Determines if a sensor is used to determine the user's location </summary> public bool Sensor { get; set; } #endregion #region Functions <summary> Converts the map data to a URL </summary> <returns>The map as a URL</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:<API key>")] public override string ToString() { string Result = "sensor=" + Sensor.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture).URLEncode() + (Center==null ? "" : ("&center=" + Center.ToString().URLEncode())) + "&zoom=" + Zoom.ToString(CultureInfo.InvariantCulture).URLEncode() + "&size=" + (Width.ToString(CultureInfo.InvariantCulture) + "x" + Height.ToString(CultureInfo.InvariantCulture)).URLEncode() + "&scale=" + Scale.ToString(CultureInfo.InvariantCulture).URLEncode() + "&format=" + Format.ToString().ToLower(CultureInfo.InvariantCulture).URLEncode() + "&maptype=" + MapType.ToString().ToLower(CultureInfo.InvariantCulture).URLEncode() + (string.IsNullOrEmpty(Language) ? "" : "&language=" + Language.URLEncode()) + (string.IsNullOrEmpty(Region) ? "" : "&region=" + Region.URLEncode()); foreach (Markers Marker in Markers) Result += "&" + Marker.ToString(); Result += base.ToString(); return APILocation + "?" + Result; } #endregion } }
MobileUserEdit = { init : function() { $("#delete_button").click(function() { MobileUserIndex.<API key>($(this).attr("user_id")); }); } } $(MobileUserEdit.init);
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Monitor { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; <summary> Extension methods for <API key>. </summary> public static partial class <API key> { <summary> Retrieve alert rule definitions in a subscription. </summary> <param name='operations'> The operations group for this extension method. </param> public static IEnumerable<MetricAlertResource> ListBySubscription(this <API key> operations) { return operations.<API key>().GetAwaiter().GetResult(); } <summary> Retrieve alert rule definitions in a subscription. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='cancellationToken'> The cancellation token. </param> public static async Task<IEnumerable<MetricAlertResource>> <API key>(this <API key> operations, Cancellation<API key> = default(CancellationToken)) { using (var _result = await operations.<API key>(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } <summary> Retrieve alert rule definitions in a resource group. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> public static IEnumerable<MetricAlertResource> ListByResourceGroup(this <API key> operations, string resourceGroupName) { return operations.<API key>(resourceGroupName).GetAwaiter().GetResult(); } <summary> Retrieve alert rule definitions in a resource group. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='cancellationToken'> The cancellation token. </param> public static async Task<IEnumerable<MetricAlertResource>> <API key>(this <API key> operations, string resourceGroupName, Cancellation<API key> = default(CancellationToken)) { using (var _result = await operations.<API key>(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } <summary> Retrieve an alert rule definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> public static MetricAlertResource Get(this <API key> operations, string resourceGroupName, string ruleName) { return operations.GetAsync(resourceGroupName, ruleName).GetAwaiter().GetResult(); } <summary> Retrieve an alert rule definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> <param name='cancellationToken'> The cancellation token. </param> public static async Task<MetricAlertResource> GetAsync(this <API key> operations, string resourceGroupName, string ruleName, Cancellation<API key> = default(CancellationToken)) { using (var _result = await operations.<API key>(resourceGroupName, ruleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } <summary> Create or update an metric alert definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> <param name='parameters'> The parameters of the rule to create or update. </param> public static MetricAlertResource CreateOrUpdate(this <API key> operations, string resourceGroupName, string ruleName, MetricAlertResource parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, ruleName, parameters).GetAwaiter().GetResult(); } <summary> Create or update an metric alert definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> <param name='parameters'> The parameters of the rule to create or update. </param> <param name='cancellationToken'> The cancellation token. </param> public static async Task<MetricAlertResource> CreateOrUpdateAsync(this <API key> operations, string resourceGroupName, string ruleName, MetricAlertResource parameters, Cancellation<API key> = default(CancellationToken)) { using (var _result = await operations.<API key>(resourceGroupName, ruleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } <summary> Update an metric alert definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> <param name='parameters'> The parameters of the rule to update. </param> public static MetricAlertResource Update(this <API key> operations, string resourceGroupName, string ruleName, <API key> parameters) { return operations.UpdateAsync(resourceGroupName, ruleName, parameters).GetAwaiter().GetResult(); } <summary> Update an metric alert definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> <param name='parameters'> The parameters of the rule to update. </param> <param name='cancellationToken'> The cancellation token. </param> public static async Task<MetricAlertResource> UpdateAsync(this <API key> operations, string resourceGroupName, string ruleName, <API key> parameters, Cancellation<API key> = default(CancellationToken)) { using (var _result = await operations.<API key>(resourceGroupName, ruleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } <summary> Delete an alert rule definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> public static void Delete(this <API key> operations, string resourceGroupName, string ruleName) { operations.DeleteAsync(resourceGroupName, ruleName).GetAwaiter().GetResult(); } <summary> Delete an alert rule definition. </summary> <param name='operations'> The operations group for this extension method. </param> <param name='resourceGroupName'> The name of the resource group. The name is case insensitive. </param> <param name='ruleName'> The name of the rule. </param> <param name='cancellationToken'> The cancellation token. </param> public static async Task DeleteAsync(this <API key> operations, string resourceGroupName, string ruleName, Cancellation<API key> = default(CancellationToken)) { (await operations.<API key>(resourceGroupName, ruleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
"use strict"; var <API key> = require("@babel/runtime/helpers/<API key>"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = <API key>(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M5 19h14v-6.5h-1.5V14h-1v-1.5H15v-1h1.5V10h1v1.5H19V5H5v14zm6-10h1.5v2.25L14.25 9H16l-2.25 3L16 15h-1.75l-1.75-2.25V15H11V9zm-5 4.5h2.5v-1H6V9h4v1.5H7.5v1H9c.55 0 1 .45 1 1V14c0 .55-.45 1-1 1H6v-1.5z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 8.5h-1.5V10h-1v1.5H15v1h1.5V14h1v-1.5H19V19H5V5h14v6.5z" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M10 14v-1.5c0-.55-.45-1-1-1H7.5v-1H10V9H6v3.5h2.5v1H6V15h3c.55 0 1-.45 1-1zm2.5-1.25L14.25 15H16l-2.25-3L16 9h-1.75l-1.75 2.25V9H11v6h1.5z" }, "2")], 'FiveKPlusTwoTone'); exports.default = _default;
#include "src/execution/frames.h" #include <memory> #include <sstream> #include "src/base/bits.h" #include "src/codegen/<API key>.h" #include "src/codegen/macro-assembler.h" #include "src/codegen/<API key>.h" #include "src/codegen/safepoint-table.h" #include "src/deoptimizer/deoptimizer.h" #include "src/execution/frames-inl.h" #include "src/execution/vm-state-inl.h" #include "src/ic/ic-stats.h" #include "src/logging/counters.h" #include "src/objects/code.h" #include "src/objects/slots.h" #include "src/objects/smi.h" #include "src/objects/visitors.h" #include "src/snapshot/snapshot.h" #include "src/strings/string-stream.h" #include "src/wasm/wasm-code-manager.h" #include "src/wasm/wasm-engine.h" #include "src/wasm/wasm-objects-inl.h" #include "src/zone/zone-containers.h" namespace v8 { namespace internal { <API key> StackFrame::<API key> = nullptr; namespace { Address AddressOf(const StackHandler* handler) { Address raw = handler->address(); #ifdef <API key> // ASan puts C++-allocated StackHandler markers onto its fake stack. // We work around that by storing the real stack address in the "padding" // field. StackHandlers allocated from generated code have 0 as padding. Address padding = base::Memory<Address>(raw + <API key>::kPaddingOffset); if (padding != 0) return padding; #endif return raw; } } // namespace // Iterator that supports traversing the stack handlers of a // particular frame. Needs to know the top of the handler chain. class <API key> { public: <API key>(const StackFrame* frame, StackHandler* handler) : limit_(frame->fp()), handler_(handler) { // Make sure the handler has already been unwound to this frame. DCHECK(frame->sp() <= AddressOf(handler)); // For CWasmEntry frames, the handler was registered by the last C++ // frame (Execution::CallWasm), so even though its address is already // beyond the limit, we know we always want to unwind one handler. if (frame->type() == StackFrame::C_WASM_ENTRY) { handler_ = handler_->next(); } } StackHandler* handler() const { return handler_; } bool done() { return handler_ == nullptr || AddressOf(handler_) > limit_; } void Advance() { DCHECK(!done()); handler_ = handler_->next(); } private: const Address limit_; StackHandler* handler_; }; #define <API key>(type, field) field##_(this), <API key>::<API key>(Isolate* isolate, bool <API key>) : isolate_(isolate), <API key>(<API key>) frame_(nullptr), handler_(nullptr), <API key>(<API key>) {} #undef <API key> StackFrameIterator::StackFrameIterator(Isolate* isolate) : StackFrameIterator(isolate, isolate->thread_local_top()) {} StackFrameIterator::StackFrameIterator(Isolate* isolate, ThreadLocalTop* t) : <API key>(isolate, true) { Reset(t); } void StackFrameIterator::Advance() { DCHECK(!done()); // Compute the state of the calling frame before restoring // callee-saved registers and unwinding handlers. This allows the // frame code that computes the caller state to access the top // handler and the value of any callee-saved register if needed. StackFrame::State state; StackFrame::Type type = frame_->GetCallerState(&state); // Unwind handlers corresponding to the current frame. <API key> it(frame_, handler_); while (!it.done()) it.Advance(); handler_ = it.handler(); // Advance to the calling frame. frame_ = SingletonFor(type, &state); // When we're done iterating over the stack frames, the handler // chain must have been completely unwound. DCHECK(!done() || handler_ == nullptr); } void StackFrameIterator::Reset(ThreadLocalTop* top) { StackFrame::State state; StackFrame::Type type = ExitFrame::<API key>(Isolate::c_entry_fp(top), &state); handler_ = StackHandler::FromAddress(Isolate::handler(top)); frame_ = SingletonFor(type, &state); } StackFrame* <API key>::SingletonFor(StackFrame::Type type, StackFrame::State* state) { StackFrame* result = SingletonFor(type); DCHECK((!result) == (type == StackFrame::NONE)); if (result) result->state_ = *state; return result; } StackFrame* <API key>::SingletonFor(StackFrame::Type type) { #define FRAME_TYPE_CASE(type, field) \ case StackFrame::type: \ return &field switch (type) { case StackFrame::NONE: return nullptr; <API key>(FRAME_TYPE_CASE) default: break; } return nullptr; #undef FRAME_TYPE_CASE } void <API key>::Advance() { do { iterator_.Advance(); } while (!iterator_.done() && !iterator_.frame()->is_java_script()); } <API key>::<API key>(Isolate* isolate) : iterator_(isolate) { if (!done() && !IsValidFrame(iterator_.frame())) Advance(); } <API key>::<API key>(Isolate* isolate, StackFrameId id) : <API key>(isolate) { while (!done() && frame()->id() != id) Advance(); } void <API key>::Advance() { do { iterator_.Advance(); } while (!done() && !IsValidFrame(iterator_.frame())); } bool <API key>::IsValidFrame(StackFrame* frame) const { if (frame->is_java_script()) { JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame); if (!js_frame->function().IsJSFunction()) return false; return js_frame->function().shared().<API key>(); } // Apart from JavaScript frames, only Wasm frames are valid. return frame->is_wasm(); } namespace { bool <API key>(Isolate* isolate, Address pc, StackFrame::State* state) { Code <API key> = isolate->builtins()->builtin(Builtins::<API key>); Code <API key> = isolate->builtins()->builtin(Builtins::<API key>); Code <API key> = isolate->builtins()->builtin(Builtins::<API key>); if (<API key>.contains(pc) || <API key>.contains(pc) || <API key>.contains(pc)) { return true; } else if (<API key>) { intptr_t marker = Memory<intptr_t>( state->fp + <API key>::<API key>); <API key>( state->fp + <API key>::kFunctionOffset, kSystemPointerSize); Object maybe_function = Object( Memory<Address>(state->fp + <API key>::kFunctionOffset)); // There's no need to run a full ContainsSlow if we know the frame can't be // an InterpretedFrame, so we do these fast checks first if (StackFrame::IsTypeMarker(marker) || maybe_function.IsSmi()) { return false; } else if (!isolate->heap()->InSpaceSlow(pc, CODE_SPACE)) { return false; } <API key> = isolate->heap()-><API key>(pc); return <API key>.<API key>(); } else { return false; } } } // namespace bool <API key>::<API key>(Isolate* isolate, Address pc, Address fp) const { // Return false for builds with non-embedded bytecode handlers. if (Isolate::CurrentEmbeddedBlob() == nullptr) return false; EmbeddedData d = EmbeddedData::FromBlob(); if (pc < d.<API key>() || pc >= d.<API key>()) { // Not a bytecode handler pc address. return false; } if (!IsValidStackAddress(fp + <API key>::<API key>)) { return false; } // Check if top stack frame is a bytecode handler stub frame. <API key>( fp + <API key>::<API key>, kSystemPointerSize); intptr_t marker = Memory<intptr_t>(fp + <API key>::<API key>); if (StackFrame::IsTypeMarker(marker) && StackFrame::MarkerToType(marker) == StackFrame::STUB) { // Bytecode handler built a frame. return false; } return true; } <API key>::<API key>(Isolate* isolate, Address pc, Address fp, Address sp, Address lr, Address js_entry_sp) : <API key>(isolate, false), low_bound_(sp), high_bound_(js_entry_sp), top_frame_type_(StackFrame::NONE), <API key>(kNullAddress), <API key>(isolate-><API key>()), top_link_register_(lr) { StackFrame::State state; StackFrame::Type type; ThreadLocalTop* top = isolate->thread_local_top(); bool advance_frame = true; Address fast_c_fp = isolate->isolate_data()-><API key>(); uint8_t stack_is_iterable = isolate->isolate_data()->stack_is_iterable(); if (!stack_is_iterable) { frame_ = nullptr; return; } // 'Fast C calls' are a special type of C call where we call directly from JS // to C without an exit frame inbetween. The CEntryStub is responsible for // setting Isolate::c_entry_fp, meaning that it won't be set for fast C calls. // To keep the stack iterable, we store the FP and PC of the caller of the // fast C call on the isolate. This is guaranteed to be the topmost JS frame, // because fast C calls cannot call back into JS. We start iterating the stack // from this topmost JS frame. if (fast_c_fp) { DCHECK_NE(kNullAddress, isolate->isolate_data()-><API key>()); type = StackFrame::Type::OPTIMIZED; top_frame_type_ = type; state.fp = fast_c_fp; state.sp = sp; state.pc_address = isolate->isolate_data()-><API key>(); advance_frame = false; } else if (IsValidTop(top)) { type = ExitFrame::<API key>(Isolate::c_entry_fp(top), &state); top_frame_type_ = type; } else if (IsValidStackAddress(fp)) { DCHECK_NE(fp, kNullAddress); state.fp = fp; state.sp = sp; state.pc_address = StackFrame::<API key>( reinterpret_cast<Address*>(StandardFrame::ComputePCAddress(fp))); // If the current PC is in a bytecode handler, the top stack frame isn't // the bytecode handler's frame and the top of stack or link register is a // return address into the interpreter entry trampoline, then we are likely // in a bytecode handler with elided frame. In that case, set the PC // properly and make sure we do not drop the frame. if (<API key>(isolate, pc, fp)) { Address* tos_location = nullptr; if (top_link_register_) { tos_location = &top_link_register_; } else if (IsValidStackAddress(sp)) { <API key>(sp, kSystemPointerSize); tos_location = reinterpret_cast<Address*>(sp); } if (<API key>(isolate, *tos_location, &state)) { state.pc_address = tos_location; advance_frame = false; } } // StackFrame::ComputeType will read both kContextOffset and kMarkerOffset, // we check only that kMarkerOffset is within the stack bounds and do // compile time check that kContextOffset slot is pushed on the stack before // kMarkerOffset. STATIC_ASSERT(<API key>::kFunctionOffset < <API key>::kContextOffset); Address frame_marker = fp + <API key>::kFunctionOffset; if (IsValidStackAddress(frame_marker)) { type = StackFrame::ComputeType(this, &state); top_frame_type_ = type; // We only keep the top frame if we believe it to be interpreted frame. if (type != StackFrame::INTERPRETED) { advance_frame = true; } <API key>( fp + <API key>::<API key>, kSystemPointerSize); Address <API key> = Memory<Address>(fp + <API key>::<API key>); if (!StackFrame::IsTypeMarker(<API key>)) <API key> = <API key>; } else { // Mark the frame as OPTIMIZED if we cannot determine its type. // We chose OPTIMIZED rather than INTERPRETED because it's closer to // the original value of StackFrame::JAVA_SCRIPT here, in that JAVA_SCRIPT // referred to full-codegen frames (now removed from the tree), and // OPTIMIZED refers to turbofan frames, both of which are generated // code. INTERPRETED frames refer to bytecode. // The frame anyways will be skipped. type = StackFrame::OPTIMIZED; // Top frame is incomplete so we cannot reliably determine its type. top_frame_type_ = StackFrame::NONE; } } else { return; } frame_ = SingletonFor(type, &state); if (advance_frame && frame_) Advance(); } bool <API key>::IsValidTop(ThreadLocalTop* top) const { Address c_entry_fp = Isolate::c_entry_fp(top); if (!IsValidExitFrame(c_entry_fp)) return false; // There should be at least one JS_ENTRY stack handler. Address handler = Isolate::handler(top); if (handler == kNullAddress) return false; // Check that there are no js frames on top of the native frames. return c_entry_fp < handler; } void <API key>::AdvanceOneFrame() { DCHECK(!done()); StackFrame* last_frame = frame_; Address last_sp = last_frame->sp(), last_fp = last_frame->fp(); // Before advancing to the next stack frame, perform pointer validity tests. if (!IsValidFrame(last_frame) || !IsValidCaller(last_frame)) { frame_ = nullptr; return; } // Advance to the previous frame. StackFrame::State state; StackFrame::Type type = frame_->GetCallerState(&state); frame_ = SingletonFor(type, &state); if (!frame_) return; // Check that we have actually moved to the previous frame in the stack. if (frame_->sp() <= last_sp || frame_->fp() <= last_fp) { frame_ = nullptr; } } bool <API key>::IsValidFrame(StackFrame* frame) const { return IsValidStackAddress(frame->sp()) && IsValidStackAddress(frame->fp()); } bool <API key>::IsValidCaller(StackFrame* frame) { StackFrame::State state; if (frame->is_entry() || frame->is_construct_entry()) { // See EntryFrame::GetCallerState. It computes the caller FP address // and calls ExitFrame::<API key> on it. We need to be // sure that caller FP address is valid. Address caller_fp = Memory<Address>(frame->fp() + EntryFrameConstants::kCallerFPOffset); if (!IsValidExitFrame(caller_fp)) return false; } else if (frame-><API key>()) { // See <API key>::<API key>. It assumes that // the number of arguments is stored on stack as Smi. We need to check // that it really an Smi. Object number_of_args = reinterpret_cast<<API key>*>(frame)->GetExpression(0); if (!number_of_args.IsSmi()) { return false; } } frame->ComputeCallerState(&state); return IsValidStackAddress(state.sp) && IsValidStackAddress(state.fp) && SingletonFor(frame->GetCallerState(&state)) != nullptr; } bool <API key>::IsValidExitFrame(Address fp) const { if (!IsValidStackAddress(fp)) return false; Address sp = ExitFrame::ComputeStackPointer(fp); if (!IsValidStackAddress(sp)) return false; StackFrame::State state; ExitFrame::FillState(fp, sp, &state); <API key>(state.pc_address, sizeof(state.pc_address)); return *state.pc_address != kNullAddress; } void <API key>::Advance() { while (true) { AdvanceOneFrame(); if (done()) break; <API key>* last_callback_scope = nullptr; while (<API key> != nullptr && <API key>->scope_address() < frame_->fp()) { // As long as the setup of a frame is not atomic, we may happen to be // in an interval where an <API key> is already created, // but the frame is not yet entered. So we are actually observing // the previous frame. // Skip all the <API key>'s that are below the current fp. last_callback_scope = <API key>; <API key> = <API key>->previous(); } if (frame_->is_java_script() || frame_->is_wasm()) break; if (frame_->is_exit() || frame_->is_builtin_exit()) { // Some of the EXIT frames may have <API key> allocated on // top of them. In that case the scope corresponds to the first EXIT // frame beneath it. There may be other EXIT frames on top of the // <API key>, just skip them as we cannot collect any useful // information about them. if (last_callback_scope) { frame_->state_.pc_address = last_callback_scope-><API key>(); } break; } } } namespace { Code GetContainingCode(Isolate* isolate, Address pc) { return isolate-><API key>()->GetCacheEntry(pc)->code; } } // namespace Code StackFrame::LookupCode() const { Code result = GetContainingCode(isolate(), pc()); DCHECK_GE(pc(), result.InstructionStart()); DCHECK_LT(pc(), result.InstructionEnd()); return result; } void StackFrame::IteratePc(RootVisitor* v, Address* pc_address, Address* <API key>, Code holder) { Address pc = *pc_address; DCHECK(holder.GetHeap()->GcSafeCodeContains(holder, pc)); unsigned pc_offset = static_cast<unsigned>(pc - holder.InstructionStart()); Object code = holder; v->VisitRootPointer(Root::kTop, nullptr, FullObjectSlot(&code)); if (code == holder) return; holder = Code::unchecked_cast(code); pc = holder.InstructionStart() + pc_offset; *pc_address = pc; if (<API key> && <API key>) { *<API key> = holder.constant_pool(); } } void StackFrame::<API key>( <API key> resolver) { DCHECK_NULL(<API key>); <API key> = resolver; } StackFrame::Type StackFrame::ComputeType(const <API key>* iterator, State* state) { DCHECK_NE(state->fp, kNullAddress); <API key>( state->fp + <API key>::<API key>, kSystemPointerSize); intptr_t marker = Memory<intptr_t>( state->fp + <API key>::<API key>); if (!iterator-><API key>) { // TODO(titzer): "<API key>" is kind of bogus. It really // means that we are being called from the profiler, which can interrupt // the VM with a signal at any arbitrary instruction, with essentially // anything on the stack. So basically none of these checks are 100% // reliable. <API key>( state->fp + <API key>::kFunctionOffset, kSystemPointerSize); Object maybe_function = Object( Memory<Address>(state->fp + <API key>::kFunctionOffset)); if (!StackFrame::IsTypeMarker(marker)) { if (maybe_function.IsSmi()) { return NATIVE; } else if (<API key>(iterator->isolate(), *(state->pc_address), state)) { return INTERPRETED; } else { return OPTIMIZED; } } } else { Address pc = *(state->pc_address); // If the {pc} does not point into WebAssembly code we can rely on the // returned {wasm_code} to be null and fall back to {GetContainingCode}. wasm::WasmCodeRefScope code_ref_scope; wasm::WasmCode* wasm_code = iterator->isolate()->wasm_engine()->code_manager()->LookupCode(pc); if (wasm_code != nullptr) { switch (wasm_code->kind()) { case wasm::WasmCode::kFunction: return WASM_COMPILED; case wasm::WasmCode::kWasmToCapiWrapper: return WASM_EXIT; case wasm::WasmCode::kWasmToJsWrapper: return WASM_TO_JS; case wasm::WasmCode::kRuntimeStub: // Some stubs, like e.g. {WasmCode::kWasmCompileLazy} build their own // specialized frame which already carries a type marker. // TODO(mstarzinger): This is only needed for the case where embedded // builtins are disabled. It can be removed once all non-embedded // builtins are gone. if (StackFrame::IsTypeMarker(marker)) break; return STUB; case wasm::WasmCode::kInterpreterEntry: return <API key>; default: UNREACHABLE(); } } else { // Look up the code object to figure out the type of the stack frame. Code code_obj = GetContainingCode(iterator->isolate(), pc); if (!code_obj.is_null()) { switch (code_obj.kind()) { case Code::BUILTIN: if (StackFrame::IsTypeMarker(marker)) break; if (code_obj.<API key>()) { return INTERPRETED; } if (code_obj.is_turbofanned()) { // TODO(bmeurer): We treat frames for BUILTIN Code objects as // OptimizedFrame for now (all the builtins with JavaScript // linkage are actually generated with TurboFan currently, so // this is sound). return OPTIMIZED; } return BUILTIN; case Code::OPTIMIZED_FUNCTION: return OPTIMIZED; case Code::JS_TO_WASM_FUNCTION: return JS_TO_WASM; case Code::JS_TO_JS_FUNCTION: return STUB; case Code::C_WASM_ENTRY: return C_WASM_ENTRY; case Code::WASM_FUNCTION: case Code::<API key>: case Code::WASM_TO_JS_FUNCTION: case Code::<API key>: // Never appear as on-heap {Code} objects. UNREACHABLE(); default: // All other types should have an explicit marker break; } } else { return NATIVE; } } } DCHECK(StackFrame::IsTypeMarker(marker)); StackFrame::Type candidate = StackFrame::MarkerToType(marker); switch (candidate) { case ENTRY: case CONSTRUCT_ENTRY: case EXIT: case <API key>: case <API key>: case <API key>: case BUILTIN_EXIT: case STUB: case INTERNAL: case CONSTRUCT: case ARGUMENTS_ADAPTOR: case WASM_TO_JS: case WASM_COMPILED: case WASM_COMPILE_LAZY: case WASM_EXIT: return candidate; case JS_TO_WASM: case OPTIMIZED: case INTERPRETED: default: // Unoptimized and optimized JavaScript frames, including // interpreted frames, should never have a StackFrame::Type // marker. If we find one, we're likely being called from the // profiler in a bogus stack frame. return NATIVE; } } #ifdef DEBUG bool StackFrame::<API key>() const { return iterator_-><API key>; } #endif StackFrame::Type StackFrame::GetCallerState(State* state) const { ComputeCallerState(state); return ComputeType(iterator_, state); } Address StackFrame::UnpaddedFP() const { return fp(); } Code NativeFrame::unchecked_code() const { return Code(); } void NativeFrame::ComputeCallerState(State* state) const { state->sp = caller_sp(); state->fp = Memory<Address>(fp() + <API key>::kCallerFPOffset); state->pc_address = <API key>( reinterpret_cast<Address*>(fp() + <API key>::kCallerPCOffset)); state->callee_pc_address = nullptr; state-><API key> = nullptr; } Code EntryFrame::unchecked_code() const { return isolate()->heap()->builtin(Builtins::kJSEntry); } void EntryFrame::ComputeCallerState(State* state) const { GetCallerState(state); } StackFrame::Type EntryFrame::GetCallerState(State* state) const { const int offset = EntryFrameConstants::kCallerFPOffset; Address fp = Memory<Address>(this->fp() + offset); return ExitFrame::<API key>(fp, state); } StackFrame::Type CWasmEntryFrame::GetCallerState(State* state) const { const int offset = <API key>::kCEntryFPOffset; Address fp = Memory<Address>(this->fp() + offset); return ExitFrame::<API key>(fp, state); } Code ConstructEntryFrame::unchecked_code() const { return isolate()->heap()->builtin(Builtins::kJSConstructEntry); } Code ExitFrame::unchecked_code() const { return Code(); } void ExitFrame::ComputeCallerState(State* state) const { // Set up the caller state. state->sp = caller_sp(); state->fp = Memory<Address>(fp() + ExitFrameConstants::kCallerFPOffset); state->pc_address = <API key>( reinterpret_cast<Address*>(fp() + ExitFrameConstants::kCallerPCOffset)); state->callee_pc_address = nullptr; if (<API key>) { state-><API key> = reinterpret_cast<Address*>( fp() + ExitFrameConstants::kConstantPoolOffset); } } void ExitFrame::Iterate(RootVisitor* v) const { // The arguments are traversed as part of the expression stack of // the calling frame. IteratePc(v, pc_address(), <API key>(), LookupCode()); } Address ExitFrame::<API key>() const { return fp() + ExitFrameConstants::kCallerSPOffset; } StackFrame::Type ExitFrame::<API key>(Address fp, State* state) { if (fp == 0) return NONE; StackFrame::Type type = ComputeFrameType(fp); Address sp = (type == WASM_EXIT) ? WasmExitFrame::ComputeStackPointer(fp) : ExitFrame::ComputeStackPointer(fp); FillState(fp, sp, state); DCHECK_NE(*state->pc_address, kNullAddress); return type; } StackFrame::Type ExitFrame::ComputeFrameType(Address fp) { // Distinguish between between regular and builtin exit frames. // Default to EXIT in all hairy cases (e.g., when called from profiler). const int offset = ExitFrameConstants::kFrameTypeOffset; Object marker(Memory<Address>(fp + offset)); if (!marker.IsSmi()) { return EXIT; } intptr_t marker_int = bit_cast<intptr_t>(marker); StackFrame::Type frame_type = static_cast<StackFrame::Type>(marker_int >> 1); if (frame_type == EXIT || frame_type == BUILTIN_EXIT || frame_type == WASM_EXIT) { return frame_type; } return EXIT; } Address ExitFrame::ComputeStackPointer(Address fp) { <API key>(fp + ExitFrameConstants::kSPOffset, kSystemPointerSize); return Memory<Address>(fp + ExitFrameConstants::kSPOffset); } Address WasmExitFrame::ComputeStackPointer(Address fp) { // For WASM_EXIT frames, {sp} is only needed for finding the PC slot, // everything else is handled via safepoint information. Address sp = fp + <API key>::kWasmInstanceOffset; DCHECK_EQ(sp - 1 * kPCOnStackSize, fp + <API key>::kCallingPCOffset); return sp; } void ExitFrame::FillState(Address fp, Address sp, State* state) { state->sp = sp; state->fp = fp; state->pc_address = <API key>( reinterpret_cast<Address*>(sp - 1 * kPCOnStackSize)); state->callee_pc_address = nullptr; // The constant pool recorded in the exit frame is not associated // with the pc in this state (the return address into a C entry // stub). ComputeCallerState will retrieve the constant pool // together with the associated caller pc. state-><API key> = nullptr; } JSFunction BuiltinExitFrame::function() const { return JSFunction::cast(target_slot_object()); } Object BuiltinExitFrame::receiver() const { return <API key>(); } bool BuiltinExitFrame::IsConstructor() const { return !<API key>().IsUndefined(isolate()); } Object BuiltinExitFrame::GetParameter(int i) const { DCHECK(i >= 0 && i < <API key>()); int offset = <API key>::<API key> + i * kSystemPointerSize; return Object(Memory<Address>(fp() + offset)); } int BuiltinExitFrame::<API key>() const { Object argc_slot = argc_slot_object(); DCHECK(argc_slot.IsSmi()); // Argc also counts the receiver, target, new target, and argc itself as args, // therefore the real argument count is argc - 4. int argc = Smi::ToInt(argc_slot) - 4; DCHECK_GE(argc, 0); return argc; } namespace { void PrintIndex(StringStream* accumulator, StackFrame::PrintMode mode, int index) { accumulator->Add((mode == StackFrame::OVERVIEW) ? "%5d: " : "[%d]: ", index); } const char* <API key>(StackFrame::Type type) { switch (type) { #define CASE(value, name) \ case StackFrame::value: \ return #name; <API key>(CASE) #undef CASE default: UNREACHABLE(); } } } // namespace void StackFrame::Print(StringStream* accumulator, PrintMode mode, int index) const { <API key> no_gc; PrintIndex(accumulator, mode, index); accumulator->Add(<API key>(type())); accumulator->Add(" [pc: %p]\n", reinterpret_cast<void*>(pc())); } void BuiltinExitFrame::Print(StringStream* accumulator, PrintMode mode, int index) const { <API key> no_gc; Object receiver = this->receiver(); JSFunction function = this->function(); accumulator-><API key>(function); PrintIndex(accumulator, mode, index); accumulator->Add("builtin exit frame: "); Code code; if (IsConstructor()) accumulator->Add("new "); accumulator->PrintFunction(function, receiver, &code); accumulator->Add("(this=%o", receiver); // Print the parameters. int parameters_count = <API key>(); for (int i = 0; i < parameters_count; i++) { accumulator->Add(",%o", GetParameter(i)); } accumulator->Add(")\n\n"); } Address StandardFrame::<API key>(int n) const { const int offset = <API key>::kExpressionsOffset; return fp() + offset - n * kSystemPointerSize; } Address InterpretedFrame::<API key>(int n) const { const int offset = <API key>::kExpressionsOffset; return fp() + offset - n * kSystemPointerSize; } Script StandardFrame::script() const { // This should only be called on frames which override this method. UNREACHABLE(); return Script(); } Object StandardFrame::receiver() const { return ReadOnlyRoots(isolate()).undefined_value(); } Object StandardFrame::context() const { return ReadOnlyRoots(isolate()).undefined_value(); } int StandardFrame::position() const { AbstractCode code = AbstractCode::cast(LookupCode()); int code_offset = static_cast<int>(pc() - code.InstructionStart()); return code.SourcePosition(code_offset); } int StandardFrame::<API key>() const { Address base = <API key>(0); Address limit = sp() - kSystemPointerSize; DCHECK(base >= limit); // stack grows downwards // Include register-allocated locals in number of expressions. return static_cast<int>((base - limit) / kSystemPointerSize); } Object StandardFrame::GetParameter(int index) const { // StandardFrame does not define any parameters. UNREACHABLE(); } int StandardFrame::<API key>() const { return 0; } void StandardFrame::ComputeCallerState(State* state) const { state->sp = caller_sp(); state->fp = caller_fp(); state->pc_address = <API key>( reinterpret_cast<Address*>(ComputePCAddress(fp()))); state->callee_pc_address = pc_address(); state-><API key> = reinterpret_cast<Address*>(<API key>(fp())); } bool StandardFrame::IsConstructor() const { return false; } void StandardFrame::Summarize(std::vector<FrameSummary>* functions) const { // This should only be called on frames which override this method. UNREACHABLE(); } void StandardFrame::<API key>(RootVisitor* v) const { // Make sure that we're not doing "safe" stack frame iteration. We cannot // possibly find pointers in optimized frames in that state. DCHECK(<API key>()); // Find the code and compute the safepoint information. Address inner_pointer = pc(); const wasm::WasmCode* wasm_code = isolate()->wasm_engine()->code_manager()->LookupCode(inner_pointer); SafepointEntry safepoint_entry; uint32_t stack_slots; Code code; bool has_tagged_params = false; uint32_t <API key> = 0; if (wasm_code != nullptr) { SafepointTable table(wasm_code->instruction_start(), wasm_code-><API key>(), wasm_code->stack_slots()); safepoint_entry = table.FindEntry(inner_pointer); stack_slots = wasm_code->stack_slots(); has_tagged_params = wasm_code->kind() != wasm::WasmCode::kFunction && wasm_code->kind() != wasm::WasmCode::kWasmToCapiWrapper; <API key> = wasm_code-><API key>(); } else { <API key>::<API key>* entry = isolate()-><API key>()->GetCacheEntry(inner_pointer); if (!entry->safepoint_entry.is_valid()) { entry->safepoint_entry = entry->code.GetSafepointEntry(inner_pointer); DCHECK(entry->safepoint_entry.is_valid()); } else { DCHECK(entry->safepoint_entry.Equals( entry->code.GetSafepointEntry(inner_pointer))); } code = entry->code; safepoint_entry = entry->safepoint_entry; stack_slots = code.stack_slots(); has_tagged_params = code.has_tagged_params(); } uint32_t slot_space = stack_slots * kSystemPointerSize; // Determine the fixed header and spill slot area size. int frame_header_size = <API key>::<API key>; intptr_t marker = Memory<intptr_t>(fp() + <API key>::<API key>); if (StackFrame::IsTypeMarker(marker)) { StackFrame::Type candidate = StackFrame::MarkerToType(marker); switch (candidate) { case ENTRY: case CONSTRUCT_ENTRY: case EXIT: case <API key>: case <API key>: case <API key>: case BUILTIN_EXIT: case ARGUMENTS_ADAPTOR: case STUB: case INTERNAL: case CONSTRUCT: case JS_TO_WASM: case C_WASM_ENTRY: frame_header_size = TypedFrameConstants::<API key>; break; case WASM_TO_JS: case WASM_COMPILED: case <API key>: case WASM_COMPILE_LAZY: frame_header_size = <API key>::<API key>; break; case WASM_EXIT: // The last value in the frame header is the calling PC, which should // not be visited. static_assert(<API key>::<API key> == <API key>::<API key> + 1, "WasmExitFrame has one slot more than WasmCompiledFrame"); frame_header_size = <API key>::<API key>; break; case OPTIMIZED: case INTERPRETED: case BUILTIN: // These frame types have a context, but they are actually stored // in the place on the stack that one finds the frame type. UNREACHABLE(); break; case NATIVE: case NONE: case NUMBER_OF_TYPES: case MANUAL: UNREACHABLE(); break; } } slot_space -= (frame_header_size + <API key>::<API key>); FullObjectSlot frame_header_base(&Memory<Address>(fp() - frame_header_size)); FullObjectSlot frame_header_limit( &Memory<Address>(fp() - <API key>::kCPSlotSize)); FullObjectSlot parameters_base(&Memory<Address>(sp())); FullObjectSlot parameters_limit(frame_header_base.address() - slot_space); // Visit the rest of the parameters if they are tagged. if (has_tagged_params) { v->VisitRootPointers(Root::kTop, nullptr, parameters_base, parameters_limit); } // Visit pointer spill slots and locals. uint8_t* safepoint_bits = safepoint_entry.bits(); for (unsigned index = 0; index < stack_slots; index++) { int byte_index = index >> kBitsPerByteLog2; int bit_index = index & (kBitsPerByte - 1); if ((safepoint_bits[byte_index] & (1U << bit_index)) != 0) { FullObjectSlot spill_slot = parameters_limit + index; #ifdef <API key> // Spill slots may contain compressed values in which case the upper // 32-bits will contain zeros. In order to simplify handling of such // slots in GC we ensure that the slot always contains full value. // The spill slot may actually contain weak references so we load/store // values using spill_slot.location() in order to avoid dealing with // <API key> here. Tagged_t compressed_value = static_cast<Tagged_t>(*spill_slot.location()); if (!HAS_SMI_TAG(compressed_value)) { // We don't need to update smi values. *spill_slot.location() = <API key>(isolate(), compressed_value); } #endif v->VisitRootPointer(Root::kTop, nullptr, spill_slot); } } // Visit tagged parameters that have been passed to the function of this // frame. Conceptionally these parameters belong to the parent frame. However, // the exact count is only known by this frame (in the presence of tail calls, // this information cannot be derived from the call site). if (<API key> > 0) { FullObjectSlot <API key>(&Memory<Address>(caller_sp())); FullObjectSlot <API key> = <API key> + <API key>; v->VisitRootPointers(Root::kTop, nullptr, <API key>, <API key>); } // For the off-heap code cases, we can skip this. if (!code.is_null()) { // Visit the return address in the callee and incoming arguments. IteratePc(v, pc_address(), <API key>(), code); } // If this frame has JavaScript ABI, visit the context (in stub and JS // frames) and the function (in JS frames). If it has WebAssembly ABI, visit // the instance object. v->VisitRootPointers(Root::kTop, nullptr, frame_header_base, frame_header_limit); } void StubFrame::Iterate(RootVisitor* v) const { <API key>(v); } Code StubFrame::unchecked_code() const { return isolate()->FindCodeObject(pc()); } Address StubFrame::<API key>() const { return fp() + ExitFrameConstants::kCallerSPOffset; } int StubFrame::<API key>(int* stack_slots) { Code code = LookupCode(); DCHECK(code.is_turbofanned()); DCHECK_EQ(code.kind(), Code::BUILTIN); HandlerTable table(code); int pc_offset = static_cast<int>(pc() - code.InstructionStart()); *stack_slots = code.stack_slots(); return table.LookupReturn(pc_offset); } void OptimizedFrame::Iterate(RootVisitor* v) const { <API key>(v); } void JavaScriptFrame::SetParameterValue(int index, Object value) const { Memory<Address>(GetParameterSlot(index)) = value.ptr(); } bool JavaScriptFrame::IsConstructor() const { Address fp = caller_fp(); if (<API key>()) { // Skip the arguments adaptor frame and look at the real caller. fp = Memory<Address>(fp + <API key>::kCallerFPOffset); } return IsConstructFrame(fp); } bool JavaScriptFrame::HasInlinedFrames() const { std::vector<SharedFunctionInfo> functions; GetFunctions(&functions); return functions.size() > 1; } Code JavaScriptFrame::unchecked_code() const { return function().code(); } int OptimizedFrame::<API key>() const { Code code = LookupCode(); if (code.kind() == Code::BUILTIN) { return static_cast<int>( Memory<intptr_t>(fp() + <API key>::kArgCOffset)); } else { return JavaScriptFrame::<API key>(); } } Address JavaScriptFrame::<API key>() const { return fp() + <API key>::kCallerSPOffset; } void JavaScriptFrame::GetFunctions( std::vector<SharedFunctionInfo>* functions) const { DCHECK(functions->empty()); functions->push_back(function().shared()); } void JavaScriptFrame::GetFunctions( std::vector<Handle<SharedFunctionInfo>>* functions) const { DCHECK(functions->empty()); std::vector<SharedFunctionInfo> raw_functions; GetFunctions(&raw_functions); for (const auto& raw_function : raw_functions) { functions->push_back( Handle<SharedFunctionInfo>(raw_function, function().GetIsolate())); } } void JavaScriptFrame::Summarize(std::vector<FrameSummary>* functions) const { DCHECK(functions->empty()); Code code = LookupCode(); int offset = static_cast<int>(pc() - code.InstructionStart()); Handle<AbstractCode> abstract_code(AbstractCode::cast(code), isolate()); Handle<FixedArray> params = GetParameters(); FrameSummary::<API key> summary( isolate(), receiver(), function(), *abstract_code, offset, IsConstructor(), *params); functions->push_back(summary); } JSFunction JavaScriptFrame::function() const { return JSFunction::cast(<API key>()); } Object JavaScriptFrame::unchecked_function() const { // During deoptimization of an optimized function, we may have yet to // materialize some closures on the stack. The arguments marker object // marks this case. DCHECK(<API key>().IsJSFunction() || ReadOnlyRoots(isolate()).arguments_marker() == <API key>()); return <API key>(); } Object JavaScriptFrame::receiver() const { return GetParameter(-1); } Object JavaScriptFrame::context() const { const int offset = <API key>::kContextOffset; Object maybe_result(Memory<Address>(fp() + offset)); DCHECK(!maybe_result.IsSmi()); return maybe_result; } Script JavaScriptFrame::script() const { return Script::cast(function().shared().script()); } int JavaScriptFrame::<API key>( int* stack_depth, HandlerTable::CatchPrediction* prediction) { DCHECK(!LookupCode().has_handler_table()); DCHECK(!LookupCode().is_optimized_code()); return -1; } void JavaScriptFrame::<API key>(JSFunction function, AbstractCode code, int code_offset, FILE* file, bool print_line_number) { PrintF(file, "%s", function.IsOptimized() ? "*" : "~"); function.PrintName(file); PrintF(file, "+%d", code_offset); if (print_line_number) { SharedFunctionInfo shared = function.shared(); int source_pos = code.SourcePosition(code_offset); Object maybe_script = shared.script(); if (maybe_script.IsScript()) { Script script = Script::cast(maybe_script); int line = script.GetLineNumber(source_pos) + 1; Object script_name_raw = script.name(); if (script_name_raw.IsString()) { String script_name = String::cast(script.name()); std::unique_ptr<char[]> c_script_name = script_name.ToCString(DISALLOW_NULLS, <API key>); PrintF(file, " at %s:%d", c_script_name.get(), line); } else { PrintF(file, " at <unknown>:%d", line); } } else { PrintF(file, " at <unknown>:<unknown>"); } } } void JavaScriptFrame::PrintTop(Isolate* isolate, FILE* file, bool print_args, bool print_line_number) { // constructor calls <API key> no_allocation; <API key> it(isolate); while (!it.done()) { if (it.frame()->is_java_script()) { JavaScriptFrame* frame = it.frame(); if (frame->IsConstructor()) PrintF(file, "new "); JSFunction function = frame->function(); int code_offset = 0; if (frame->is_interpreted()) { InterpretedFrame* iframe = reinterpret_cast<InterpretedFrame*>(frame); code_offset = iframe->GetBytecodeOffset(); } else { Code code = frame->unchecked_code(); code_offset = static_cast<int>(frame->pc() - code.InstructionStart()); } <API key>(function, function.abstract_code(), code_offset, file, print_line_number); if (print_args) { // function arguments // (we are intentionally only printing the actually // supplied parameters, not all parameters required) PrintF(file, "(this="); frame->receiver().ShortPrint(file); const int length = frame-><API key>(); for (int i = 0; i < length; i++) { PrintF(file, ", "); frame->GetParameter(i).ShortPrint(file); } PrintF(file, ")"); } break; } it.Advance(); } } void JavaScriptFrame::<API key>(JSFunction function, AbstractCode code, int code_offset) { auto ic_stats = ICStats::instance(); ICInfo& ic_info = ic_stats->Current(); SharedFunctionInfo shared = function.shared(); ic_info.function_name = ic_stats-><API key>(function); ic_info.script_offset = code_offset; int source_pos = code.SourcePosition(code_offset); Object maybe_script = shared.script(); if (maybe_script.IsScript()) { Script script = Script::cast(maybe_script); ic_info.line_num = script.GetLineNumber(source_pos) + 1; ic_info.script_name = ic_stats-><API key>(script); } } Object JavaScriptFrame::GetParameter(int index) const { return Object(Memory<Address>(GetParameterSlot(index))); } int JavaScriptFrame::<API key>() const { DCHECK(<API key>() && isolate()->heap()->gc_state() == Heap::NOT_IN_GC); return function().shared().<API key>(); } Handle<FixedArray> JavaScriptFrame::GetParameters() const { if (V8_LIKELY(!<API key>)) { return isolate()->factory()->empty_fixed_array(); } int param_count = <API key>(); Handle<FixedArray> parameters = isolate()->factory()->NewFixedArray(param_count); for (int i = 0; i < param_count; i++) { parameters->set(i, GetParameter(i)); } return parameters; } int <API key>::<API key>() const { // Assert that the first allocatable register is also the argument count // register. DCHECK_EQ(<API key>::Default()-><API key>(0), <API key>.code()); Object argc_object( Memory<Address>(fp() + <API key>::kArgCOffset)); return Smi::ToInt(argc_object); } intptr_t <API key>::GetSPToFPDelta() const { Address height_slot = fp() + <API key>::<API key>; intptr_t height = Smi::ToInt(Smi(Memory<Address>(height_slot))); return height; } Object <API key>::context() const { return Object(Memory<Address>( fp() + <API key>::<API key>)); } void <API key>::SetException( Object exception) { Address <API key> = fp() + <API key>::<API key> + kSystemPointerSize; // Skip over return value slot. // Only allow setting exception if previous value was the hole. CHECK_EQ(ReadOnlyRoots(isolate()).the_hole_value(), Object(Memory<Address>(<API key>))); Memory<Address>(<API key>) = exception.ptr(); } FrameSummary::<API key>::<API key>( Isolate* isolate, Object receiver, JSFunction function, AbstractCode abstract_code, int code_offset, bool is_constructor, FixedArray parameters) : FrameSummaryBase(isolate, FrameSummary::JAVA_SCRIPT), receiver_(receiver, isolate), function_(function, isolate), abstract_code_(abstract_code, isolate), code_offset_(code_offset), is_constructor_(is_constructor), parameters_(parameters, isolate) { DCHECK(abstract_code.IsBytecodeArray() || Code::cast(abstract_code).kind() != Code::OPTIMIZED_FUNCTION); } void FrameSummary::<API key>() { if (IsJavaScript()) { <API key>.<API key>(); } } bool FrameSummary::<API key>() const { if (IsJavaScript()) { return <API key>.<API key>(); } return true; } void FrameSummary::<API key>::<API key>() { Handle<SharedFunctionInfo> shared(function()->shared(), isolate()); SharedFunctionInfo::<API key>(isolate(), shared); } bool FrameSummary::<API key>::<API key>() const { return !<API key> || function()->shared().GetBytecodeArray().<API key>(); } bool FrameSummary::<API key>::<API key>() const { return function()->shared().<API key>(); } int FrameSummary::<API key>::SourcePosition() const { return abstract_code()->SourcePosition(code_offset()); } int FrameSummary::<API key>::<API key>() const { return abstract_code()-><API key>(code_offset()); } Handle<Object> FrameSummary::<API key>::script() const { return handle(function_->shared().script(), isolate()); } Handle<String> FrameSummary::<API key>::FunctionName() const { return JSFunction::GetDebugName(function_); } Handle<Context> FrameSummary::<API key>::native_context() const { return handle(function_->context().native_context(), isolate()); } FrameSummary::WasmFrameSummary::WasmFrameSummary( Isolate* isolate, FrameSummary::Kind kind, Handle<WasmInstanceObject> instance, bool <API key>) : FrameSummaryBase(isolate, kind), wasm_instance_(instance), <API key>(<API key>) {} Handle<Object> FrameSummary::WasmFrameSummary::receiver() const { return wasm_instance_->GetIsolate()->global_proxy(); } #define <API key>(type, name) \ type FrameSummary::WasmFrameSummary::name() const { \ DCHECK(kind() == Kind::WASM_COMPILED || kind() == Kind::WASM_INTERPRETED); \ return kind() == Kind::WASM_COMPILED \ ? static_cast<const <API key>*>(this)->name() \ : static_cast<const <API key>*>(this) \ ->name(); \ } <API key>(uint32_t, function_index) <API key>(int, byte_offset) #undef <API key> int FrameSummary::WasmFrameSummary::SourcePosition() const { Handle<WasmModuleObject> module_object(wasm_instance()->module_object(), isolate()); return WasmModuleObject::GetSourcePosition(module_object, function_index(), byte_offset(), <API key>()); } Handle<Script> FrameSummary::WasmFrameSummary::script() const { return handle(wasm_instance()->module_object().script(), wasm_instance()->GetIsolate()); } Handle<String> FrameSummary::WasmFrameSummary::FunctionName() const { Handle<WasmModuleObject> module_object(wasm_instance()->module_object(), isolate()); return WasmModuleObject::GetFunctionName(isolate(), module_object, function_index()); } Handle<Context> FrameSummary::WasmFrameSummary::native_context() const { return handle(wasm_instance()->native_context(), isolate()); } FrameSummary::<API key>::<API key>( Isolate* isolate, Handle<WasmInstanceObject> instance, wasm::WasmCode* code, int code_offset, bool <API key>) : WasmFrameSummary(isolate, WASM_COMPILED, instance, <API key>), code_(code), code_offset_(code_offset) {} uint32_t FrameSummary::<API key>::function_index() const { return code()->index(); } int FrameSummary::<API key>::<API key>( const wasm::WasmCode* code, int offset) { int position = 0; // Subtract one because the current PC is one instruction after the call site. offset for (<API key> iterator(code->source_positions()); !iterator.done() && iterator.code_offset() <= offset; iterator.Advance()) { position = iterator.source_position().ScriptOffset(); } return position; } int FrameSummary::<API key>::byte_offset() const { return <API key>(code_, code_offset()); } FrameSummary::<API key>::<API key>( Isolate* isolate, Handle<WasmInstanceObject> instance, uint32_t function_index, int byte_offset) : WasmFrameSummary(isolate, WASM_INTERPRETED, instance, false), function_index_(function_index), byte_offset_(byte_offset) {} FrameSummary::~FrameSummary() { #define FRAME_SUMMARY_DESTR(kind, type, field, desc) \ case kind: \ field.~type(); \ break; switch (base_.kind()) { <API key>(FRAME_SUMMARY_DESTR) default: UNREACHABLE(); } #undef FRAME_SUMMARY_DESTR } FrameSummary FrameSummary::GetTop(const StandardFrame* frame) { std::vector<FrameSummary> frames; frame->Summarize(&frames); DCHECK_LT(0, frames.size()); return frames.back(); } FrameSummary FrameSummary::GetBottom(const StandardFrame* frame) { return Get(frame, 0); } FrameSummary FrameSummary::GetSingle(const StandardFrame* frame) { std::vector<FrameSummary> frames; frame->Summarize(&frames); DCHECK_EQ(1, frames.size()); return frames.front(); } FrameSummary FrameSummary::Get(const StandardFrame* frame, int index) { DCHECK_LE(0, index); std::vector<FrameSummary> frames; frame->Summarize(&frames); DCHECK_GT(frames.size(), index); return frames[index]; } #define <API key>(ret, name) \ ret FrameSummary::name() const { \ switch (base_.kind()) { \ case JAVA_SCRIPT: \ return <API key>.name(); \ case WASM_COMPILED: \ return <API key>.name(); \ case WASM_INTERPRETED: \ return <API key>.name(); \ default: \ UNREACHABLE(); \ return ret{}; \ } \ } <API key>(Handle<Object>, receiver) <API key>(int, code_offset) <API key>(bool, is_constructor) <API key>(bool, <API key>) <API key>(Handle<Object>, script) <API key>(int, SourcePosition) <API key>(int, <API key>) <API key>(Handle<String>, FunctionName) <API key>(Handle<Context>, native_context) #undef <API key> void OptimizedFrame::Summarize(std::vector<FrameSummary>* frames) const { DCHECK(frames->empty()); DCHECK(is_optimized()); // Delegate to JS frame in absence of turbofan deoptimization. // TODO(turbofan): Revisit once we support deoptimization across the board. Code code = LookupCode(); if (code.kind() == Code::BUILTIN) { return JavaScriptFrame::Summarize(frames); } int deopt_index = Safepoint::<API key>; DeoptimizationData const data = <API key>(&deopt_index); if (deopt_index == Safepoint::<API key>) { CHECK(data.is_null()); FATAL("Missing deoptimization information for OptimizedFrame::Summarize."); } // Prepare iteration over translation. Note that the below iteration might // materialize objects without storing them back to the Isolate, this will // lead to objects being re-materialized again for each summary. TranslatedState translated(this); translated.Prepare(fp()); // We create the summary in reverse order because the frames // in the deoptimization translation are ordered bottom-to-top. bool is_constructor = IsConstructor(); for (auto it = translated.begin(); it != translated.end(); it++) { if (it->kind() == TranslatedFrame::<API key> || it->kind() == TranslatedFrame::<API key> || it->kind() == TranslatedFrame::<API key>) { Handle<SharedFunctionInfo> shared_info = it->shared_info(); // The translation commands are ordered and the function is always // at the first position, and the receiver is next. TranslatedFrame::iterator translated_values = it->begin(); // Get or materialize the correct function in the optimized frame. Handle<JSFunction> function = Handle<JSFunction>::cast(translated_values->GetValue()); translated_values++; // Get or materialize the correct receiver in the optimized frame. Handle<Object> receiver = translated_values->GetValue(); translated_values++; // Determine the underlying code object and the position within it from // the translation corresponding to the frame type in question. Handle<AbstractCode> abstract_code; unsigned code_offset; if (it->kind() == TranslatedFrame::<API key> || it->kind() == TranslatedFrame::<API key>) { code_offset = 0; abstract_code = handle(AbstractCode::cast(isolate()->builtins()->builtin( Builtins::<API key>(it->node_id()))), isolate()); } else { DCHECK_EQ(it->kind(), TranslatedFrame::<API key>); code_offset = it->node_id().ToInt(); // Points to current bytecode. abstract_code = handle(shared_info->abstract_code(), isolate()); } // Append full summary of the encountered JS frame. Handle<FixedArray> params = GetParameters(); FrameSummary::<API key> summary( isolate(), *receiver, *function, *abstract_code, code_offset, is_constructor, *params); frames->push_back(summary); is_constructor = false; } else if (it->kind() == TranslatedFrame::kConstructStub) { // The next encountered JS frame will be marked as a constructor call. DCHECK(!is_constructor); is_constructor = true; } } } int OptimizedFrame::<API key>( int* stack_slots, HandlerTable::CatchPrediction* prediction) { // We cannot perform exception prediction on optimized code. Instead, we need // to use FrameSummary to find the corresponding code offset in unoptimized // code to perform prediction there. DCHECK_NULL(prediction); Code code = LookupCode(); HandlerTable table(code); int pc_offset = static_cast<int>(pc() - code.InstructionStart()); if (stack_slots) *stack_slots = code.stack_slots(); // When the return pc has been replaced by a trampoline there won't be // a handler for this trampoline. Thus we need to use the return pc that // _used to be_ on the stack to get the right ExceptionHandler. if (code.kind() == Code::OPTIMIZED_FUNCTION && code.<API key>()) { SafepointTable safepoints(code); pc_offset = safepoints.find_return_pc(pc_offset); } return table.LookupReturn(pc_offset); } DeoptimizationData OptimizedFrame::<API key>( int* deopt_index) const { DCHECK(is_optimized()); JSFunction opt_function = function(); Code code = opt_function.code(); // The code object may have been replaced by lazy deoptimization. Fall // back to a slow search in this case to find the original optimized // code object. if (!code.contains(pc())) { code = isolate()->heap()-><API key>(pc()); } DCHECK(!code.is_null()); DCHECK(code.kind() == Code::OPTIMIZED_FUNCTION); SafepointEntry safepoint_entry = code.GetSafepointEntry(pc()); if (safepoint_entry.<API key>()) { *deopt_index = safepoint_entry.<API key>(); return DeoptimizationData::cast(code.deoptimization_data()); } *deopt_index = Safepoint::<API key>; return DeoptimizationData(); } Object OptimizedFrame::receiver() const { Code code = LookupCode(); if (code.kind() == Code::BUILTIN) { Address argc_ptr = fp() + <API key>::kArgCOffset; intptr_t argc = *reinterpret_cast<intptr_t*>(argc_ptr); intptr_t args_size = (<API key>::<API key> + argc) * kSystemPointerSize; Address receiver_ptr = fp() + args_size; return *FullObjectSlot(receiver_ptr); } else { return JavaScriptFrame::receiver(); } } void OptimizedFrame::GetFunctions( std::vector<SharedFunctionInfo>* functions) const { DCHECK(functions->empty()); DCHECK(is_optimized()); // Delegate to JS frame in absence of turbofan deoptimization. // TODO(turbofan): Revisit once we support deoptimization across the board. Code code = LookupCode(); if (code.kind() == Code::BUILTIN) { return JavaScriptFrame::GetFunctions(functions); } <API key> no_gc; int deopt_index = Safepoint::<API key>; DeoptimizationData const data = <API key>(&deopt_index); DCHECK(!data.is_null()); DCHECK_NE(Safepoint::<API key>, deopt_index); FixedArray const literal_array = data.LiteralArray(); TranslationIterator it(data.<API key>(), data.TranslationIndex(deopt_index).value()); Translation::Opcode opcode = static_cast<Translation::Opcode>(it.Next()); DCHECK_EQ(Translation::BEGIN, opcode); it.Next(); // Skip frame count. int jsframe_count = it.Next(); it.Next(); // Skip update feedback count. // We insert the frames in reverse order because the frames // in the deoptimization translation are ordered bottom-to-top. while (jsframe_count != 0) { opcode = static_cast<Translation::Opcode>(it.Next()); if (opcode == Translation::INTERPRETED_FRAME || opcode == Translation::<API key> || opcode == Translation::<API key>) { it.Next(); // Skip bailout id. jsframe_count // The second operand of the frame points to the function. Object shared = literal_array.get(it.Next()); functions->push_back(SharedFunctionInfo::cast(shared)); // Skip over remaining operands to advance to the next opcode. it.Skip(Translation::NumberOfOperandsFor(opcode) - 2); } else { // Skip over operands to advance to the next opcode. it.Skip(Translation::NumberOfOperandsFor(opcode)); } } } int OptimizedFrame::<API key>(int slot_index) { return <API key>::kCallerSPOffset - ((slot_index + 1) * kSystemPointerSize); } Object OptimizedFrame::StackSlotAt(int index) const { return Object(Memory<Address>(fp() + <API key>(index))); } int InterpretedFrame::position() const { AbstractCode code = AbstractCode::cast(GetBytecodeArray()); int code_offset = GetBytecodeOffset(); return code.SourcePosition(code_offset); } int InterpretedFrame::<API key>( int* context_register, HandlerTable::CatchPrediction* prediction) { HandlerTable table(GetBytecodeArray()); return table.LookupRange(GetBytecodeOffset(), context_register, prediction); } int InterpretedFrame::GetBytecodeOffset() const { const int index = <API key>::<API key>; DCHECK_EQ(<API key>::<API key>, <API key>::kExpressionsOffset - index * kSystemPointerSize); int raw_offset = Smi::ToInt(GetExpression(index)); return raw_offset - BytecodeArray::kHeaderSize + kHeapObjectTag; } int InterpretedFrame::GetBytecodeOffset(Address fp) { const int offset = <API key>::kExpressionsOffset; const int index = <API key>::<API key>; DCHECK_EQ(<API key>::<API key>, <API key>::kExpressionsOffset - index * kSystemPointerSize); Address expression_offset = fp + offset - index * kSystemPointerSize; int raw_offset = Smi::ToInt(Object(Memory<Address>(expression_offset))); return raw_offset - BytecodeArray::kHeaderSize + kHeapObjectTag; } void InterpretedFrame::PatchBytecodeOffset(int new_offset) { const int index = <API key>::<API key>; DCHECK_EQ(<API key>::<API key>, <API key>::kExpressionsOffset - index * kSystemPointerSize); int raw_offset = new_offset + BytecodeArray::kHeaderSize - kHeapObjectTag; SetExpression(index, Smi::FromInt(raw_offset)); } BytecodeArray InterpretedFrame::GetBytecodeArray() const { const int index = <API key>::<API key>; DCHECK_EQ(<API key>::<API key>, <API key>::kExpressionsOffset - index * kSystemPointerSize); return BytecodeArray::cast(GetExpression(index)); } void InterpretedFrame::PatchBytecodeArray(BytecodeArray bytecode_array) { const int index = <API key>::<API key>; DCHECK_EQ(<API key>::<API key>, <API key>::kExpressionsOffset - index * kSystemPointerSize); SetExpression(index, bytecode_array); } Object InterpretedFrame::<API key>(int register_index) const { const int index = <API key>::<API key>; DCHECK_EQ(<API key>::kRegisterFileFromFp, <API key>::kExpressionsOffset - index * kSystemPointerSize); return GetExpression(index + register_index); } void InterpretedFrame::<API key>(int register_index, Object value) { const int index = <API key>::<API key>; DCHECK_EQ(<API key>::kRegisterFileFromFp, <API key>::kExpressionsOffset - index * kSystemPointerSize); return SetExpression(index + register_index, value); } void InterpretedFrame::Summarize(std::vector<FrameSummary>* functions) const { DCHECK(functions->empty()); Handle<AbstractCode> abstract_code(AbstractCode::cast(GetBytecodeArray()), isolate()); Handle<FixedArray> params = GetParameters(); FrameSummary::<API key> summary( isolate(), receiver(), function(), *abstract_code, GetBytecodeOffset(), IsConstructor(), *params); functions->push_back(summary); } int <API key>::<API key>() const { return Smi::ToInt(GetExpression(0)); } Code <API key>::unchecked_code() const { return isolate()->builtins()->builtin(Builtins::<API key>); } int BuiltinFrame::<API key>() const { return Smi::ToInt(GetExpression(0)); } void BuiltinFrame::PrintFrameKind(StringStream* accumulator) const { accumulator->Add("builtin frame: "); } Address InternalFrame::<API key>() const { // Internal frames have no arguments. The stack pointer of the // caller is at a fixed offset from the frame pointer. return fp() + <API key>::kCallerSPOffset; } Code InternalFrame::unchecked_code() const { return Code(); } void WasmCompiledFrame::Print(StringStream* accumulator, PrintMode mode, int index) const { PrintIndex(accumulator, mode, index); accumulator->Add("WASM ["); accumulator->PrintName(script().name()); Address instruction_start = isolate() ->wasm_engine() ->code_manager() ->LookupCode(pc()) ->instruction_start(); Vector<const uint8_t> raw_func_name = module_object().GetRawFunctionName(function_index()); const int <API key> = 64; char func_name[<API key> + 1]; int func_name_len = std::min(<API key>, raw_func_name.length()); memcpy(func_name, raw_func_name.begin(), func_name_len); func_name[func_name_len] = '\0'; int pos = position(); const wasm::WasmModule* module = wasm_instance().module_object().module(); int func_index = function_index(); int func_code_offset = module->functions[func_index].code.offset(); accumulator->Add("], function #%u ('%s'), pc=%p (+0x%x), pos=%d (+%d)\n", func_index, func_name, reinterpret_cast<void*>(pc()), static_cast<int>(pc() - instruction_start), pos, pos - func_code_offset); if (mode != OVERVIEW) accumulator->Add("\n"); } Code WasmCompiledFrame::unchecked_code() const { return isolate()->FindCodeObject(pc()); } void WasmCompiledFrame::Iterate(RootVisitor* v) const { <API key>(v); } Address WasmCompiledFrame::<API key>() const { return fp() + ExitFrameConstants::kCallerSPOffset; } wasm::WasmCode* WasmCompiledFrame::wasm_code() const { return isolate()->wasm_engine()->code_manager()->LookupCode(pc()); } WasmInstanceObject WasmCompiledFrame::wasm_instance() const { const int offset = <API key>::kWasmInstanceOffset; Object instance(Memory<Address>(fp() + offset)); return WasmInstanceObject::cast(instance); } WasmModuleObject WasmCompiledFrame::module_object() const { return wasm_instance().module_object(); } uint32_t WasmCompiledFrame::function_index() const { return FrameSummary::GetSingle(this).AsWasmCompiled().function_index(); } Script WasmCompiledFrame::script() const { return module_object().script(); } int WasmCompiledFrame::position() const { return FrameSummary::GetSingle(this).SourcePosition(); } void WasmCompiledFrame::Summarize(std::vector<FrameSummary>* functions) const { DCHECK(functions->empty()); // The {WasmCode*} escapes this scope via the {FrameSummary}, which is fine, // since this code object is part of our stack. wasm::WasmCodeRefScope code_ref_scope; wasm::WasmCode* code = wasm_code(); int offset = static_cast<int>(pc() - code->instruction_start()); Handle<WasmInstanceObject> instance(wasm_instance(), isolate()); FrameSummary::<API key> summary( isolate(), instance, code, offset, <API key>()); functions->push_back(summary); } bool WasmCompiledFrame::<API key>() const { // Check whether our callee is a WASM_TO_JS frame, and this frame is at the // ToNumber conversion call. wasm::WasmCode* code = callee_pc() != kNullAddress ? isolate()->wasm_engine()->code_manager()->LookupCode(callee_pc()) : nullptr; if (!code || code->kind() != wasm::WasmCode::kWasmToJsWrapper) return false; int offset = static_cast<int>(callee_pc() - code->instruction_start()); int pos = FrameSummary::<API key>::<API key>( code, offset); DCHECK(pos == 0 || pos == 1); // The imported call has position 0, ToNumber has position 1. return !!pos; } int WasmCompiledFrame::<API key>(int* stack_slots) { DCHECK_NOT_NULL(stack_slots); wasm::WasmCode* code = isolate()->wasm_engine()->code_manager()->LookupCode(pc()); if (!code->IsAnonymous() && code->handler_table_size() > 0) { HandlerTable table(code->handler_table(), code->handler_table_size(), HandlerTable::<API key>); int pc_offset = static_cast<int>(pc() - code->instruction_start()); *stack_slots = static_cast<int>(code->stack_slots()); return table.LookupReturn(pc_offset); } return -1; } void <API key>::Iterate(RootVisitor* v) const { <API key>(v); } void <API key>::Print(StringStream* accumulator, PrintMode mode, int index) const { PrintIndex(accumulator, mode, index); accumulator->Add("WASM INTERPRETER ENTRY ["); Script script = this->script(); accumulator->PrintName(script.name()); accumulator->Add("]"); if (mode != OVERVIEW) accumulator->Add("\n"); } void <API key>::Summarize( std::vector<FrameSummary>* functions) const { Handle<WasmInstanceObject> instance(wasm_instance(), isolate()); std::vector<std::pair<uint32_t, int>> interpreted_stack = instance->debug_info().GetInterpretedStack(fp()); for (auto& e : interpreted_stack) { FrameSummary::<API key> summary(isolate(), instance, e.first, e.second); functions->push_back(summary); } } Code <API key>::unchecked_code() const { return Code(); } WasmInstanceObject <API key>::wasm_instance() const { const int offset = <API key>::kWasmInstanceOffset; Object instance(Memory<Address>(fp() + offset)); return WasmInstanceObject::cast(instance); } WasmDebugInfo <API key>::debug_info() const { return wasm_instance().debug_info(); } WasmModuleObject <API key>::module_object() const { return wasm_instance().module_object(); } Script <API key>::script() const { return module_object().script(); } int <API key>::position() const { return FrameSummary::GetBottom(this).AsWasmInterpreted().SourcePosition(); } Object <API key>::context() const { return wasm_instance().native_context(); } Address <API key>::<API key>() const { return fp() + ExitFrameConstants::kCallerSPOffset; } Code <API key>::unchecked_code() const { return Code(); } WasmInstanceObject <API key>::wasm_instance() const { return WasmInstanceObject::cast(*wasm_instance_slot()); } FullObjectSlot <API key>::wasm_instance_slot() const { const int offset = <API key>::kWasmInstanceOffset; return FullObjectSlot(&Memory<Address>(fp() + offset)); } void <API key>::Iterate(RootVisitor* v) const { const int header_size = <API key>::<API key>; FullObjectSlot base(&Memory<Address>(sp())); FullObjectSlot limit(&Memory<Address>(fp() - header_size)); v->VisitRootPointers(Root::kTop, nullptr, base, limit); v->VisitRootPointer(Root::kTop, nullptr, wasm_instance_slot()); } Address <API key>::<API key>() const { return fp() + <API key>::kCallerSPOffset; } namespace { void PrintFunctionSource(StringStream* accumulator, SharedFunctionInfo shared, Code code) { if (<API key> != 0 && !code.is_null()) { std::ostringstream os; os << " << SourceCodeOf(shared, <API key>) << "\n accumulator->Add(os.str().c_str()); } } } // namespace void JavaScriptFrame::Print(StringStream* accumulator, PrintMode mode, int index) const { Handle<SharedFunctionInfo> shared = handle(function().shared(), isolate()); SharedFunctionInfo::<API key>(isolate(), shared); <API key> no_gc; Object receiver = this->receiver(); JSFunction function = this->function(); accumulator-><API key>(function); PrintIndex(accumulator, mode, index); PrintFrameKind(accumulator); Code code; if (IsConstructor()) accumulator->Add("new "); accumulator->PrintFunction(function, receiver, &code); accumulator->Add(" [%p]", function); // Get scope information for nicer output, if possible. If code is nullptr, or // doesn't contain scope info, scope_info will return 0 for the number of // parameters, stack local variables, context local variables, stack slots, // or context slots. ScopeInfo scope_info = shared->scope_info(); Object script_obj = shared->script(); if (script_obj.IsScript()) { Script script = Script::cast(script_obj); accumulator->Add(" ["); accumulator->PrintName(script.name()); if (is_interpreted()) { const InterpretedFrame* iframe = reinterpret_cast<const InterpretedFrame*>(this); BytecodeArray bytecodes = iframe->GetBytecodeArray(); int offset = iframe->GetBytecodeOffset(); int source_pos = AbstractCode::cast(bytecodes).SourcePosition(offset); int line = script.GetLineNumber(source_pos) + 1; accumulator->Add(":%d] [bytecode=%p offset=%d]", line, reinterpret_cast<void*>(bytecodes.ptr()), offset); } else { int function_start_pos = shared->StartPosition(); int line = script.GetLineNumber(function_start_pos) + 1; accumulator->Add(":~%d] [pc=%p]", line, reinterpret_cast<void*>(pc())); } } accumulator->Add("(this=%o", receiver); // Print the parameters. int parameters_count = <API key>(); for (int i = 0; i < parameters_count; i++) { accumulator->Add(","); accumulator->Add("%o", GetParameter(i)); } accumulator->Add(")"); if (mode == OVERVIEW) { accumulator->Add("\n"); return; } if (is_optimized()) { accumulator->Add(" {\n// optimized frame\n"); PrintFunctionSource(accumulator, *shared, code); accumulator->Add("}\n"); return; } accumulator->Add(" {\n"); // Compute the number of locals and expression stack elements. int heap_locals_count = scope_info.ContextLocalCount(); int expressions_count = <API key>(); // Try to get hold of the context of this frame. Context context; if (this->context().IsContext()) { context = Context::cast(this->context()); while (context.IsWithContext()) { context = context.previous(); DCHECK(!context.is_null()); } } // Print heap-allocated local variables. if (heap_locals_count > 0) { accumulator->Add(" // heap-allocated locals\n"); } for (int i = 0; i < heap_locals_count; i++) { accumulator->Add(" var "); accumulator->PrintName(scope_info.ContextLocalName(i)); accumulator->Add(" = "); if (!context.is_null()) { int index = Context::MIN_CONTEXT_SLOTS + i; if (index < context.length()) { accumulator->Add("%o", context.get(index)); } else { accumulator->Add( "// warning: missing context slot - inconsistent frame?"); } } else { accumulator->Add("// warning: no context found - inconsistent frame?"); } accumulator->Add("\n"); } // Print the expression stack. if (0 < expressions_count) { accumulator->Add(" // expression stack (top to bottom)\n"); } for (int i = expressions_count - 1; i >= 0; i accumulator->Add(" [%02d] : %o\n", i, GetExpression(i)); } PrintFunctionSource(accumulator, *shared, code); accumulator->Add("}\n\n"); } void <API key>::Print(StringStream* accumulator, PrintMode mode, int index) const { int actual = <API key>(); int expected = -1; JSFunction function = this->function(); expected = function.shared().<API key>(); PrintIndex(accumulator, mode, index); accumulator->Add("arguments adaptor frame: %d->%d", actual, expected); if (mode == OVERVIEW) { accumulator->Add("\n"); return; } accumulator->Add(" {\n"); // Print actual arguments. if (actual > 0) accumulator->Add(" // actual arguments\n"); for (int i = 0; i < actual; i++) { accumulator->Add(" [%02d] : %o", i, GetParameter(i)); if (expected != -1 && i >= expected) { accumulator->Add(" // not passed to callee"); } accumulator->Add("\n"); } accumulator->Add("}\n\n"); } void EntryFrame::Iterate(RootVisitor* v) const { IteratePc(v, pc_address(), <API key>(), LookupCode()); } void StandardFrame::IterateExpressions(RootVisitor* v) const { const int offset = <API key>::kLastObjectOffset; FullObjectSlot base(&Memory<Address>(sp())); FullObjectSlot limit(&Memory<Address>(fp() + offset) + 1); v->VisitRootPointers(Root::kTop, nullptr, base, limit); } void JavaScriptFrame::Iterate(RootVisitor* v) const { IterateExpressions(v); IteratePc(v, pc_address(), <API key>(), LookupCode()); } void InternalFrame::Iterate(RootVisitor* v) const { Code code = LookupCode(); IteratePc(v, pc_address(), <API key>(), code); // Internal frames typically do not receive any arguments, hence their stack // only contains tagged pointers. // We are misusing the has_tagged_params flag here to tell us whether // the full stack frame contains only tagged pointers or only raw values. // This is used for the WasmCompileLazy builtin, where we actually pass // untagged arguments and also store untagged values on the stack. if (code.has_tagged_params()) IterateExpressions(v); } namespace { uint32_t PcAddressForHashing(Isolate* isolate, Address address) { if (InstructionStream::PcIsOffHeap(isolate, address)) { // Ensure that we get predictable hashes for addresses in embedded code. return EmbeddedData::FromBlob(isolate).AddressForHashing(address); } return <API key>(address); } } // namespace <API key>::<API key>* <API key>::GetCacheEntry(Address inner_pointer) { isolate_->counters()->pc_to_code()->Increment(); DCHECK(base::bits::IsPowerOfTwo(<API key>)); uint32_t hash = ComputeUnseededHash(PcAddressForHashing(isolate_, inner_pointer)); uint32_t index = hash & (<API key> - 1); <API key>* entry = cache(index); if (entry->inner_pointer == inner_pointer) { isolate_->counters()->pc_to_code_cached()->Increment(); DCHECK(entry->code == isolate_->heap()-><API key>(inner_pointer)); } else { // Because this code may be interrupted by a profiling signal that // also queries the cache, we cannot update inner_pointer before the code // has been set. Otherwise, we risk trying to use a cache entry before // the code has been computed. entry->code = isolate_->heap()-><API key>(inner_pointer); entry->safepoint_entry.Reset(); entry->inner_pointer = inner_pointer; } return entry; } // Frame layout helper class implementation. namespace { int <API key>(int arg_count) { return ShouldPadArguments(arg_count) ? 1 : 0; } // Some architectures need to push padding together with the TOS register // in order to maintain stack alignment. constexpr int <API key>() { return kPadArguments ? 1 : 0; } bool <API key>(<API key> mode) { switch (mode) { case <API key>::STUB: case <API key>::JAVASCRIPT: return false; case <API key>::<API key>: case <API key>::<API key>: return true; } UNREACHABLE(); } } // namespace <API key>::<API key>(int <API key>, int translation_height, bool is_topmost, FrameInfoKind frame_info_kind) { const int locals_count = translation_height; <API key> = <API key>::<API key>(locals_count); static constexpr int kTheAccumulator = 1; static constexpr int kTopOfStackPadding = <API key>(); int <API key> = (is_topmost || frame_info_kind == FrameInfoKind::kConservative) ? (kTheAccumulator + kTopOfStackPadding) : 0; <API key> = (<API key> + <API key>) * kSystemPointerSize; // The 'fixed' part of the frame consists of the incoming parameters and // the part described by <API key>. This will include // argument padding, when needed. const int <API key> = <API key>(<API key>); const int fixed_frame_size = <API key>::kFixedFrameSize + (<API key> + <API key>) * kSystemPointerSize; <API key> = <API key> + fixed_frame_size; } <API key>::<API key>(int translation_height) { // Note: This is according to the Translation's notion of 'parameters' which // differs to that of the SharedFunctionInfo, e.g. by including the receiver. const int parameters_count = translation_height; <API key> = (parameters_count + <API key>(parameters_count)) * kSystemPointerSize; <API key> = <API key> + <API key>::kFixedFrameSize; } <API key>::<API key>(int translation_height, bool is_topmost, FrameInfoKind frame_info_kind) { // Note: This is according to the Translation's notion of 'parameters' which // differs to that of the SharedFunctionInfo, e.g. by including the receiver. const int parameters_count = translation_height; // If the construct frame appears to be topmost we should ensure that the // value of result register is preserved during continuation execution. // We do this here by "pushing" the result of the constructor function to // the top of the reconstructed stack and popping it in // {Builtins::kNotifyDeoptimized}. static constexpr int kTopOfStackPadding = <API key>(); static constexpr int kTheResult = 1; const int argument_padding = <API key>(parameters_count); const int adjusted_height = (is_topmost || frame_info_kind == FrameInfoKind::kConservative) ? parameters_count + argument_padding + kTheResult + kTopOfStackPadding : parameters_count + argument_padding; <API key> = adjusted_height * kSystemPointerSize; <API key> = <API key> + <API key>::kFixedFrameSize; } <API key>::<API key>( int translation_height, const <API key>& <API key>, const <API key>* register_config, bool is_topmost, DeoptimizeKind deopt_kind, <API key> continuation_mode, FrameInfoKind frame_info_kind) { const bool is_conservative = frame_info_kind == FrameInfoKind::kConservative; // Note: This is according to the Translation's notion of 'parameters' which // differs to that of the SharedFunctionInfo, e.g. by including the receiver. const int parameters_count = translation_height; <API key> = !is_topmost || deopt_kind == DeoptimizeKind::kLazy; const int result_slot_count = (<API key> || is_conservative) ? 1 : 0; const int <API key> = (<API key>(continuation_mode) || is_conservative) ? 1 : 0; const int <API key> = register_config-><API key>(); const int padding_slot_count = <API key>::PaddingSlotCount( <API key>); const int <API key> = <API key>.<API key>(); <API key> = parameters_count - <API key>; <API key> = <API key> + result_slot_count + <API key>; const int <API key> = <API key>(<API key>); // If the builtins frame appears to be topmost we should ensure that the // value of result register is preserved during continuation execution. // We do this here by "pushing" the result of callback function to the // top of the reconstructed stack and popping it in // {Builtins::kNotifyDeoptimized}. static constexpr int kTopOfStackPadding = <API key>(); static constexpr int kTheResult = 1; const int push_result_count = (is_topmost || is_conservative) ? kTheResult + kTopOfStackPadding : 0; <API key> = kSystemPointerSize * (<API key> + <API key> + <API key> + padding_slot_count + push_result_count) + <API key>::kFixedFrameSize; <API key> = kSystemPointerSize * (<API key> + padding_slot_count + push_result_count) + (<API key>::kFixedFrameSize - <API key>::<API key>); } } // namespace internal } // namespace v8
body.page-register2 { padding-top:10px; padding-left:10px; } .page-register2 .rnr-c-register, .rnr-pagewrapper .page-register2 .rnr-c-register, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-c-register { margin-bottom:5px; } .page-register2 .rnr-c-register, .rnr-pagewrapper .page-register2 .rnr-c-register, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-c-register { min-width:400px; display:inline-block } .page-register2 .rnr-cw-register, .rnr-pagewrapper .page-register2 .rnr-cw-register, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-cw-register { text-align: center; } .page-register2 .rnr-b-regheader, .rnr-pagewrapper .page-register2 .rnr-b-regheader, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regheader { white-space: nowrap; } .page-register2 .rnr-b-regheader, .rnr-pagewrapper .page-register2 .rnr-b-regheader, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regheader { text-align: right; } .page-register2 .rnr-b-regheader > *, .rnr-pagewrapper .page-register2 .rnr-b-regheader > *, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regheader > * { font-size: 120%; } .page-register2 .rnr-b-message, .rnr-pagewrapper .page-register2 .rnr-b-message, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-message { white-space: nowrap; } .page-register2 .rnr-b-message, .rnr-pagewrapper .page-register2 .rnr-b-message, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-message { text-align: right; } .page-register2 .rnr-b-message > *, .rnr-pagewrapper .page-register2 .rnr-b-message > *, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-message > * { } .page-register2 .rnr-c-fields, .rnr-pagewrapper .page-register2 .rnr-c-fields, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-c-fields { margin-bottom:5px; } .page-register2 .rnr-b-regfields, .rnr-pagewrapper .page-register2 .rnr-b-regfields, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regfields { white-space: nowrap; } .page-register2 .rnr-b-regfields, .rnr-pagewrapper .page-register2 .rnr-b-regfields, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regfields { text-align: right; } .page-register2 .rnr-b-regfields > *, .rnr-pagewrapper .page-register2 .rnr-b-regfields > *, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regfields > * { } .page-register2 .rnr-b-regbuttons, .rnr-pagewrapper .page-register2 .rnr-b-regbuttons, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regbuttons { white-space: nowrap; } .page-register2 .rnr-b-regbuttons, .rnr-pagewrapper .page-register2 .rnr-b-regbuttons, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regbuttons { text-align: center; } .page-register2 .rnr-b-regbuttons > *, .rnr-pagewrapper .page-register2 .rnr-b-regbuttons > *, .rnr-pagewrapper .rnr-pagewrapper .page-register2 .rnr-b-regbuttons > * { } body.page-register2 .rnr-top { padding-right: 5px; }
[&#8249; Bee7 Doc Home](./) <h1>Bee7 Integration Guide</h1> <<[../../shared/-VERSION-/version.md] ##Intro 1.Before you start integrating the SDKBOX Bee7 plugin, you need to register with Bee7: a) [Create an account on Bee7's dashboard](https://dashboard.bee7.com/#/signup) ![](../../imgs/<API key>.png) b) [Register your apps in Bee7](http://bee7.com/integrate/<API key>/) using the dashboard account ![](../../imgs/<API key>.png) 2.The API key and Scheme name values that you will bee needing in the code can be found in the dashboard, under your app's details. ![](../../imgs/bee7_<TwitterConsumerkey>.png) 3.Once the integration of the SDKBOX Bee7 plugin is complete, <a href="mailto:support@bee7.com">contact Bee7 Support</a> to activate your app for production. ##Prerequisites * __For Android, Bee7 requires a minimum version of 4.0.3. This version is newer than what the other SDKBOX plugins require.__ * __For iOS, Bee7's game wall currently supports only portrait orientation.__ ##Integration Open a terminal and use the following command to install the SDKBOX Bee7 plugin. Make sure you setup the SDKBOX installer correctly. bash $ sdkbox import bee7 <<[../../shared/notice.md] <!--## Configuration <<[../../shared/sdkbox_cloud.md] <<[../../shared/<API key>.md] JSON Configuration SDKBOX Installer will automatically create a sample configuration `sdkbox_config.json` for you Here is an example of the Bee7 configuration you can enable/disable debug mode for Bee7 here json "Bee7": { "debug":true, "key":"<API key>" } <!--<<[<API key>.md]--> ##Usage ##Extra steps The following step assumes you already registered at [Bee7](https://dashboard.bee7.com/#/signup), created a new APP, and activated TEST state. Setup iOS * Modify `Info.plist`, add URL Schemes: __Target -> Info -> URL Types__: 1. click "+" 2. fill "URL Schemes" with "your bee7 scheme". For testing, you can try "<API key>". Setup Android * Open `AndroidManifest.xml` and replace `<API key>` with your `bee7 scheme` * Open `project.properties` and change target to `target=android-21` <<[usage.md] <<[api-reference.md] <<[manual_integration.md] <<[manual_ios.md] <<[../../shared/<API key>.md] <<[manual_android.md] <<[extra-step.md] <<[../../shared/<API key>.md] <<[proguard.md]
# Pyaisa v0.8.5 # Python Yet Another International Standard Atmosphere Python 3 - ISA Model computed in parallel C++ [![Coverage Status](https: [![Binstar Badge](https: [![Binstar Badge](https: [![Binstar Badge](https: ***Pysapp*** *has changed its name due to name collision with another Open Source project. Say hello to* ***Pyaisa****!* Current continuous integration tests and automated builds available through `conda` for `Python 3.5`: | Platform | Site | Status | | | Linux-x64 | Anaconda | [![Binstar Badge](https: | OS X-x64 | Travis CI | [![Build Status](https: | Windows-x64 | Appveyor | [![Build status](https: ## A simple Standard Atmosphere Model This project it's only a simple standard atmosphere model that I've made for learning purposes, and to introduce myself to the Open Source world and its tools. Despite that, the **ISA model** is fully functional, fast, configurable and compliant with the [COESA](http://hdl.handle.net/2060/19770009539) stdandard. It is written in **Python 3** with a **C++ OpenMP** powered heart using SWIG for interfacing between those two languages. If you are running a multiple core machine, pyaisa will auto-adjust itself in each situation to perform the fastest as posible. **Pyaisa** is also fully configurable, so feel free to change every single parameter to adapt the model to whatever atmosphere you want (R, g, T0, p0, number of layers...). Although the model is finished, there're many more things to do yet: writing the documentation, improving inline comments in the code, adding more tests... so keep an eye on future commits! ## The roots **Pyaisa** was born in another project where the [AeroPython team](https: Our secondary goal was to adopt different aproaches to the problem of coding the **ISA (International Standard Atmosphere) model**, a set of equations to estimate the variation of the temperature, pressure and air density with height above sea level. **Pyaisa** is a fork of [the work I begun then](https://github.com/AeroPython/aeropy/tree/alberto-cpp), and I've focused in cpu performance as seen in the graph: ![benchmark](./static/i5-5250U.png) ***Pyaisa's*** *strength resides in it's ability to guess the best point to switch from single to multicore processing at import time.* ## Installation and testing Source code installation in a **Python 3** environment via `setup.py`: $ python setup.py install Conda packages for Linux, OS X and Windows 64 bit plattforms are provided. $ conda install pyaisa --channel newlawrence To test the library: python -c "from pyaisa.testing import test_library;test_library()" ## Brief usage instructions The library interface is composed of: `ISA` object, and `build_atm` functions. All magnitudes are expressed in the International System of Units. The main object is `ISA` and its main method is `atm`: python import pyaisa isa = pyaisa.ISA() # Creates an ISA object with default (standard) params isa.atm(0) # Returns temperature, pressure and density at sea level (288.15, 101325.0, 1.225000018124288) isa.atm([0, 11000]) # Can be used with vectorial arguments (array([288.15, 216.65]), # Temperatures array array([101325., 22632.04009501]), # Pressures array array([1.22500002, 0.36391765])) # Densities array Custom parameters can be defined after or in the constructor: python new_isa = pyaisa.ISA(R=300) # New ISA object with custom Gas Constant new_isa.atm(0) # Check new density at sea level (288.15, 101325.0, 1.1721325698420961) new_isa.params['R'] 300. new_isa.params['R'] = 287.05287 # Restore default value new_isa.atm(0) (288.15, 101325.0, 1.225000018124288) new_isa.params # Check all the params {'R': 287.05287, 'p0': 101325.0, 'g': 9.80665, 'T0': 288.15, 'psize': 900, # Size of the array to turn on parallel calculations 'layers': {'h': array([ 0., 11000., 20000., 32000.]), 'a': array([-0.0065, 0. , 0.001 ])}} As the `ISA` object is a little ackward to use, the `build_atm` function is provided. That function returns `atm` functions built with the desired parameters. By default, `atm` function built with default parameters is provided. python pyaisa.atm(11000) (216.64999999999998, 22632.040095007793, 0.3639176481016034) new_atm = pyaisa.build_atm(R=300, g=10) new_atm(11000) (216.64999999999998, 23471.318210945108, 0.36112498209008553) Functions created using `build_atm` can be used with temperature offsets as their second argument (a functionality not present in `ISA.atm` method): python pyaisa.atm(0, 15) # Offsets are added to the temperature at sea level (303.15, 101325.0, 1.1643864595827595) pyaisa.atm(11000, 15) (231.64999999999998, 24643.196756515972, 0.3705978083423891) ## Borrowed code Integration with **Travis CI** and **Appveyor** would be nearly impossible to achieve without the marvellous efforts of: * Olivier Grisel, Jonathan Helmus, Kyle Kastner and Robert McGibbon, from whom I took the code (licensed under [Creative Commons Universal v1.0](https: * Robert McGibbon, whom magnific [<API key>](https: ## Acknowledgements Thanks to my friend [Juan Luis Cano](https:
class CreateCastVotes < ActiveRecord::Migration def change create_table :cast_votes do |t| t.references :appearance t.references :play end end end
SHELL = /bin/sh # V=0 quiet, V=1 verbose. other values don't work. V = 0 Q1 = $(V:1=) Q = $(Q1:0=@) ECHO1 = $(V:1=@:) ECHO = $(ECHO1:0=@echo) NULLCMD = : srcdir = . topdir = /usr/local/rvm/rubies/ruby-2.3.0/include/ruby-2.3.0 hdrdir = $(topdir) arch_hdrdir = /usr/local/rvm/rubies/ruby-2.3.0/include/ruby-2.3.0/x86_64-linux PATH_SEPARATOR = : VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby prefix = $(DESTDIR)/usr/local/rvm/rubies/ruby-2.3.0 rubysitearchprefix = $(rubylibprefix)/$(sitearch) rubyarchprefix = $(rubylibprefix)/$(arch) rubylibprefix = $(libdir)/$(RUBY_BASE_NAME) exec_prefix = $(prefix) vendorarchhdrdir = $(vendorhdrdir)/$(sitearch) sitearchhdrdir = $(sitehdrdir)/$(sitearch) rubyarchhdrdir = $(rubyhdrdir)/$(arch) vendorhdrdir = $(rubyhdrdir)/vendor_ruby sitehdrdir = $(rubyhdrdir)/site_ruby rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME) vendorarchdir = $(vendorlibdir)/$(sitearch) vendorlibdir = $(vendordir)/$(ruby_version) vendordir = $(rubylibprefix)/vendor_ruby sitearchdir = $(DESTDIR)./.gem.<API key> sitelibdir = $(DESTDIR)./.gem.<API key> sitedir = $(rubylibprefix)/site_ruby rubyarchdir = $(rubylibdir)/$(arch) rubylibdir = $(rubylibprefix)/$(ruby_version) sitearchincludedir = $(includedir)/$(sitearch) archincludedir = $(includedir)/$(arch) sitearchlibdir = $(libdir)/$(sitearch) archlibdir = $(libdir)/$(arch) ridir = $(datarootdir)/$(RI_BASE_NAME) mandir = $(datarootdir)/man localedir = $(datarootdir)/locale libdir = $(exec_prefix)/lib psdir = $(docdir) pdfdir = $(docdir) dvidir = $(docdir) htmldir = $(docdir) infodir = $(datarootdir)/info docdir = $(datarootdir)/doc/$(PACKAGE) oldincludedir = $(DESTDIR)/usr/include includedir = $(prefix)/include localstatedir = $(prefix)/var sharedstatedir = $(prefix)/com sysconfdir = $(DESTDIR)/etc datadir = $(datarootdir) datarootdir = $(prefix)/share libexecdir = $(exec_prefix)/libexec sbindir = $(exec_prefix)/sbin bindir = $(exec_prefix)/bin archdir = $(rubyarchdir) CC = gcc CXX = g++ LIBRUBY = $(LIBRUBY_SO) LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a LIBRUBYARG_SHARED = -Wl,-rpath,'$${ORIGIN}/../lib' -Wl,-R'$${ORIGIN}/../lib' -l$(RUBY_SO_NAME) LIBRUBYARG_STATIC = -Wl,-rpath,'$${ORIGIN}/../lib' -Wl,-R'$${ORIGIN}/../lib' -l$(RUBY_SO_NAME)-static empty = OUTFLAG = -o $(empty) COUTFLAG = -o $(empty) RUBY_EXTCONF_H = cflags = $(optflags) $(debugflags) $(warnflags) cxxflags = $(optflags) $(debugflags) $(warnflags) optflags = -O3 -fno-fast-math -fno-strict-aliasing debugflags = -ggdb3 warnflags = -Wall -Wextra -<API key> -Wno-parentheses -Wno-long-long -<API key> -Wunused-variable -Wpointer-arith -Wwrite-strings -<API key> -<API key> -<API key> -<API key> CCDLFLAGS = -fPIC CFLAGS = $(CCDLFLAGS) $(cflags) -fPIC $(ARCH_FLAG) INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) DEFS = CPPFLAGS = -DHAVE_UNISTD_H -DHAVE_SYS_SELECT_H -DEV_USE_SELECT -DHAVE_POLL_H -DEV_USE_POLL -DHAVE_SYS_EPOLL_H -DEV_USE_EPOLL -<API key> -<API key> $(DEFS) $(cppflags) CXXFLAGS = $(CCDLFLAGS) $(cxxflags) $(ARCH_FLAG) ldflags = -L. -fstack-protector -rdynamic -Wl,-export-dynamic dldflags = ARCH_FLAG = DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG) LDSHARED = $(CC) -shared LDSHAREDXX = $(CXX) -shared AR = ar EXEEXT = RUBY_INSTALL_NAME = $(RUBY_BASE_NAME) RUBY_SO_NAME = ruby RUBYW_INSTALL_NAME = RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version) RUBYW_BASE_NAME = rubyw RUBY_BASE_NAME = ruby arch = x86_64-linux sitearch = $(arch) ruby_version = 2.3.0 ruby = $(bindir)/$(RUBY_BASE_NAME) RUBY = $(ruby) ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h RM = rm -f RM_RF = $(RUBY) -run -e rm RMDIRS = rmdir --<API key> -p MAKEDIRS = /bin/mkdir -p INSTALL = /usr/bin/install INSTALL_PROG = $(INSTALL) -m 0755 INSTALL_DATA = $(INSTALL) -m 644 COPY = cp TOUCH = exit > preload = libpath = . $(libdir) LIBPATH = -L. -L$(libdir) -Wl,-R$(libdir) DEFFILE = CLEANFILES = mkmf.log DISTCLEANFILES = DISTCLEANDIRS = extout = extout_prefix = target_prefix = LOCAL_LIBS = LIBS = $(LIBRUBYARG_SHARED) -lpthread -lgmp -ldl -lcrypt -lm -lc ORIG_SRCS = nio4r_ext.c monitor.c bytebuffer.c selector.c SRCS = $(ORIG_SRCS) OBJS = nio4r_ext.o monitor.o bytebuffer.o selector.o HDRS = $(srcdir)/nio4r.h $(srcdir)/libev.h TARGET = nio4r_ext TARGET_NAME = nio4r_ext TARGET_ENTRY = Init_$(TARGET_NAME) DLLIB = $(TARGET).so EXTSTATIC = STATIC_LIB = TIMESTAMP_DIR = . BINDIR = $(bindir) RUBYCOMMONDIR = $(sitedir)$(target_prefix) RUBYLIBDIR = $(sitelibdir)$(target_prefix) RUBYARCHDIR = $(sitearchdir)$(target_prefix) HDRDIR = $(rubyhdrdir)/ruby$(target_prefix) ARCHHDRDIR = $(rubyhdrdir)/$(arch)/ruby$(target_prefix) TARGET_SO = $(DLLIB) CLEANLIBS = $(TARGET).so CLEANOBJS = *.o *.bak all: $(DLLIB) static: $(STATIC_LIB) install-rb .PHONY: all install static install-so install-rb .PHONY: clean clean-so clean-static clean-rb clean-static:: clean-rb-default:: clean-rb:: clean-so:: clean: clean-so clean-static clean-rb-default clean-rb -$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time <API key>:: distclean-rb:: distclean-so:: distclean-static:: distclean: clean distclean-so distclean-static <API key> distclean-rb -$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log -$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) -$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true realclean: distclean install: install-so install-rb install-so: $(DLLIB) $(TIMESTAMP_DIR)/.RUBYARCHDIR.time $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) clean-static:: -$(Q)$(RM) $(STATIC_LIB) install-rb: pre-install-rb install-rb-default install-rb-default: <API key> pre-install-rb: Makefile <API key>: Makefile <API key>: @$(NULLCMD) $(TIMESTAMP_DIR)/.RUBYARCHDIR.time: $(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR) $(Q) $(TOUCH) $@ site-install: site-install-so site-install-rb site-install-so: install-so site-install-rb: install-rb .SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S .cc.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< .cc.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $< .mm.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< .mm.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $< .cxx.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< .cxx.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $< .cpp.o: $(ECHO) compiling $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< .cpp.S: $(ECHO) translating $(<) $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $< .c.o: $(ECHO) compiling $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $< .c.S: $(ECHO) translating $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $< .m.o: $(ECHO) compiling $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $< .m.S: $(ECHO) translating $(<) $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $< $(DLLIB): $(OBJS) Makefile $(ECHO) linking shared-object $(DLLIB) -$(Q)$(RM) $(@) $(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) $(OBJS): $(HDRS) $(ruby_headers)
var CPC = { // Internal data and variables data: { script_full_url: document.<API key>('script')[document.<API key>('script').length-1].src, script_name: null, script_url_params: null, script_locales: null, css: null }, // Available options options: { auto_init: false, cookie_name: '<API key>', cookie_warning_id: '<API key>', load_external_files: true, show_only_once: false, click_anywhere: false, before_element_ID: null, expire_days: 999, lang: null, msg: null // Custom text not in locale }, host: window.location.hostname, hID: document.<API key>('head')[0], init: function(user_options) { // Si ya hay cookie if (CPC.check(CPC.options.cookie_name)) { return; } // Merge params if passed on init if (typeof user_options !== 'undefined') { for (var attrname in user_options) { CPC.options[attrname] = user_options[attrname]; } } // Set default CSS path // We only request CSS file if its enabled if (CPC.options.load_external_files) { // Set default locales path if not set by user if (CPC.data.script_locales === null) { CPC.data.script_locales = CPC.data.script_name.replace('.js','-locales.js'); } // Set default CSS if not set by user if (CPC.data.css === null) { CPC.data.css = CPC.data.script_name.replace('.js','.css'); } CPC.appendCSS(); } // If a custom msg was set dont insert locales if (CPC.options.msg !== null) { CPC.appendWarning(); } else { // First load locales then append cookie advice if (CPC.options.load_external_files) { CPC.loadScript(CPC.data.script_locales, function(){ CPC.appendWarning(); }); } else { CPC.appendWarning(); } } }, // // Cookies handlers // // GET returns the value of the cookie // CPC.get("cookie_name_here"); get: function(c_name) { if (document.cookie.length > 0) { var c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; var c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ''; }, // CHECK returns only true or false if the cookie exists // CPC.check("cookie_name_here"); check: function(c_name) { c_name = CPC.get(c_name); if (c_name !== null && c_name !== '') { return true; } else { return false; } }, // SET name, val and # of days til expiration // CPC.set("cookie_name", "cookie_value", 5 ); set: function(c_name, value, expiredays) { var dstr, exd = new Date(); if (expiredays === 0) { sdtr = 'Thu, 01 Jan 1970 00:00:01 GMT'; } else { exd.setDate(exd.getDate() + expiredays); sdtr = exd.toUTCString(); } document.cookie = c_name + "=" + escape(value) + ";expires=" + sdtr + ';path=/;domain=.' + CPC.host + ';'; }, // DELETE cookie // Simple set expiring to 0 :-) del: function(c_name) { if (typeof c_name === 'undefined') { c_name = CPC.options.cookie_name; } CPC.set(c_name, '', 0); }, loadScript: function (url, callback){ var script = document.createElement('script'); script.type = 'text/javascript'; if (script.readyState){ script.onreadystatechange = function(){ if (script.readyState == 'loaded' || script.readyState == 'complete'){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } script.src = url; CPC.hID.appendChild(script); }, appendWarning: function() { var t = '', h = '', d = document.createElement('div'), body = document.<API key>('body')[0]; // If NOT passing custom message if (CPC.options.msg === null) { // If locale undefined assign first one if (CPC.options.lang === null) { CPC.options.msg = CPC.locales[Object.keys(CPC.locales)[0]]; } else { // Use lang set by user CPC.options.msg = CPC.locales[CPC.options.lang]; } } // Create MSG d.setAttribute('id', CPC.options.cookie_warning_id); d.setAttribute('style', 'display:none;'); d.innerHTML = CPC.options.msg; // Append before or after // If undefined OR null if (CPC.options.before_element_ID !== null) { // Append before elemint_ID var bID = document.getElementById(CPC.options.before_element_ID); bID.parentNode.insertBefore(d, bID); } else { // Append at end of body body.appendChild(d); } // Show cookie-warning only first time if (CPC.options.show_only_once) { CPC.set(CPC.options.cookie_name, true, CPC.options.expire_days); } // Hide when clicked // Set cookie to true // If there is close button var cb = document.getElementById('<API key>'); if (cb !== null && !CPC.options.click_anywhere) { cb.onclick = function(){ CPC.removeWarning(); }; } else { // Close clicking anywhere d.onclick = function(){ CPC.removeWarning(); }; } }, // Appends default CSS stylesheet appendCSS: function () { if (CPC.data.css !== null) { var lnk = document.createElement('link'); lnk.type = 'text/css'; lnk.rel = 'stylesheet'; lnk.media = 'screen'; lnk.href = CPC.data.css; CPC.hID.appendChild(lnk); } }, // Hides warning removeWarning: function() { CPC.set(CPC.options.cookie_name, true, CPC.options.expire_days); var el = document.getElementById(CPC.options.cookie_warning_id); el.outerHTML = ''; }, // Auto-initializes the CW script if has param '?auto_init' autoInit: function () { // Current script params var p = CPC.data.script_url_params; if (typeof p !== 'undefined' && p !== null) { // If has autoinit parameter if (p.match(/auto_init/)) { // If set lang parameter var L = p.match(/lang=(.*)$/); if (L) CPC.params.lang = l[1]; CPC.init(); } } } }; // Script auto init CPC.data.script_name = CPC.data.script_full_url.split('?')[0]; CPC.data.script_url_params = CPC.data.script_full_url.split('?')[1]; CPC.autoInit();
from grow.pods.preprocessors import closure_compiler from grow.pods.preprocessors import google_sheets from grow.pods.preprocessors import sass_preprocessor from protorpc import protojson import json <API key> = {} _builtins = ( sass_preprocessor.SassPreprocessor, google_sheets.<API key>, closure_compiler.<API key>, ) def <API key>(class_obj): <API key>[class_obj.KIND] = class_obj def config_from_json(preprocessor_class, content): config_class = preprocessor_class.Config return protojson.decode_message(config_class, content) def make_preprocessor(name, config, pod): class_obj = <API key>.get(name) if class_obj is None: raise ValueError('No preprocessor named "{}".'.format(name)) if isinstance(config, dict): config = json.dumps(config) config = config_from_json(class_obj, config) return class_obj(pod, config) def register_builtins(): for builtin in _builtins: <API key>(builtin) register_builtins()
using System; using System.Linq; namespace _05.Fibonacci { class Program { static void Main() { int input = int.Parse(Console.ReadLine()); Console.WriteLine(Fib(input)); } static ulong Fib(int n) { double sqrt5 = Math.Sqrt(5); double p1 = (1 + sqrt5) / 2; double p2 = -1 * (p1 - 1); double n1 = Math.Pow(p1, n + 1); double n2 = Math.Pow(p2, n + 1); return (ulong)((n1 - n2) / sqrt5); } } }
package cocagne.paxos.essential; import java.util.HashSet; public class <API key> implements EssentialProposer { protected EssentialMessenger messenger; protected String proposerUID; protected final int quorumSize; protected ProposalID proposalID; protected Object proposedValue = null; protected ProposalID lastAcceptedID = null; protected HashSet<String> promisesReceived = new HashSet<String>(); public <API key>(EssentialMessenger messenger, String proposerUID, int quorumSize) { this.messenger = messenger; this.proposerUID = proposerUID; this.quorumSize = quorumSize; this.proposalID = new ProposalID(0, proposerUID); } @Override public void setProposal(Object value) { if ( proposedValue == null ) proposedValue = value; } @Override public void prepare() { promisesReceived.clear(); proposalID.incrementNumber(); messenger.sendPrepare(proposalID); } @Override public void receivePromise(String fromUID, ProposalID proposalID, ProposalID prevAcceptedID, Object prevAcceptedValue) { if ( !proposalID.equals(this.proposalID) || promisesReceived.contains(fromUID) ) return; promisesReceived.add( fromUID ); if (lastAcceptedID == null || prevAcceptedID.isGreaterThan(lastAcceptedID)) { lastAcceptedID = prevAcceptedID; if (prevAcceptedValue != null) proposedValue = prevAcceptedValue; } if (promisesReceived.size() == quorumSize) if (proposedValue != null) messenger.sendAccept(this.proposalID, proposedValue); } public EssentialMessenger getMessenger() { return messenger; } public String getProposerUID() { return proposerUID; } public int getQuorumSize() { return quorumSize; } public ProposalID getProposalID() { return proposalID; } public Object getProposedValue() { return proposedValue; } public ProposalID getLastAcceptedID() { return lastAcceptedID; } public int numPromises() { return promisesReceived.size(); } }
package de.geeksfactory.opacclient.storage; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; public class AccountDatabase extends SQLiteOpenHelper { private static AccountDatabase instance; public static final String[] COLUMNS = {"id", "bib", "label", "name", "password", "cached", "pendingFees", "validUntil", "warning", "passwordValid", "<API key>"}; public static final String[] COLUMNS_ALARMS = {"id", "deadline", "media", "alarm", "notified", "finished"}; // CHANGE THIS public static final String[] COLUMNS_LENT = {"id", "account", "title", "author", "format", "itemid", "status", "barcode", "deadline", "homebranch", "lending_branch", "prolong_data", "renewable", "download_data", "ebook", "mediatype", "cover"}; public static final String[] <API key> = {"id", "account", "title", "author", "format", "itemid", "status", "ready", "expiration", "branch", "cancel_data", "booking_data", "mediatype", "cover"}; public static final String TABLENAME_ACCOUNTS = "accounts"; public static final String TABLENAME_LENT = "accountdata_lent"; public static final String <API key> = "<API key>"; public static final String TABLENAME_ALARMS = "alarms"; private static final String DATABASE_NAME = "accounts.db"; private static final int DATABASE_VERSION = 28; // REPLACE ONUPGRADE IF YOU private AccountDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public static synchronized AccountDatabase getInstance(Context context) { if (instance == null) instance = new AccountDatabase(context); return instance; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + "accounts ( id integer primary key autoincrement," + " bib text," + " label text," + " name text," + " password text," + " cached integer," + " pendingFees text," + " validUntil text," + " warning text," + " passwordValid integer," + " <API key> integer" + ");"); db.execSQL( "create table " + "accountdata_lent (" + "id integer primary key autoincrement," + "account integer," + "title text," + "author text," + "format text," + "itemid text," + "status text," + "barcode text," + "deadline text," + "homebranch text," + "lending_branch text," + "prolong_data text," + "renewable integer," + "download_data text," + "ebook integer," + "mediatype text," + "cover text" + ");"); db.execSQL("create table " + "<API key> (" + "id integer primary key autoincrement," + "account integer," + "title text," + "author text," + "format text," + "itemid text," + "status text," + "ready text," + "expiration text," + "branch text," + "cancel_data text," + "booking_data text," + "mediatype text," + "cover text" + ");"); db.execSQL("create table " + "alarms (" + "id integer primary key autoincrement," + "deadline text," + "media text," + "alarm text," + "notified integer," + "finished integer" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Provide something here if you change the database version if (oldVersion < 2) { // App version 2.0.0-alpha to 2.0.0, adding tables for account data db.execSQL("create table " + "accountdata_lent ( account integer, " + "title text," + "barcode text," + "author text," + "deadline text," + "deadline_ts integer," + "status text," + "branch text," + "lending_branch text," + "link text" + ");"); db.execSQL("create table " + "<API key> ( account integer, " + "title text," + "author text," + "ready text," + "branch text," + "cancel text" + ");"); } if (oldVersion < 3) { // App version 2.0.0-alpha3 to 2.0.0-alpha4, adding tables for // account data db.execSQL("alter table accounts add column cached integer"); } if (oldVersion == 3) { // App version 2.0.0-alpha4 to 2.0.0-alpha5, adding tables for // account data db.execSQL("alter table accountdata_lent add column deadline_ts integer"); } if (oldVersion < 7) { // App version 2.0.5-1 to 2.0.6, adding "expire" to reservations try { db.execSQL("alter table <API key> add column expire text"); } catch (SQLiteException sqle) { sqle.printStackTrace(); } } if (oldVersion < 8) { // App version 2.0.6 to 2.0.7 db.execSQL("create table " + "notified ( id integer primary key autoincrement, " + "account integer, " + "timestamp integer);"); } if (oldVersion < 9) { // App version 2.0.14 to 2.0.15 db.execSQL("alter table accountdata_lent add column download text"); } if (oldVersion < 11) { // App version 2.0.15 to 2.0.16 db.execSQL("alter table <API key> add column bookingurl text"); } if (oldVersion < 12) { // App version 2.0.17 to 2.0.18 db.execSQL("alter table accounts add column pendingFees text"); } if (oldVersion < 13) { // App version 2.0.23 to 2.0.24 db.execSQL("alter table accounts add column validUntil text"); } if (oldVersion < 15) { // App version 2.0.23 to 2.0.24 db.execSQL("alter table accountdata_lent add column format text"); } if (oldVersion < 16) { // App version 2.1.1 to 3.0.0beta db.execSQL("alter table accountdata_lent add column renewable text"); } if (oldVersion < 17) { // App version 2.1.1 to 3.0.0beta db.execSQL("alter table accountdata_lent add column itemid text"); } if (oldVersion < 18) { // App version 2.1.1 to 3.0.0beta db.execSQL("alter table <API key> add column itemid text"); } if (oldVersion < 20) { // App version 3.0.1 to 3.0.2 db.execSQL("alter table accounts add column warning text"); } if (oldVersion < 21) { // App version 4.1.11 to 4.2.0 // <API key> existed before but was missing in the DB db.execSQL("alter table <API key> add column format text"); } if (oldVersion < 22) { // App version 4.2.0 to 4.2.1 // We added <API key> to onUpgrade but didn't in onCreate, // so we need to fix this by adding it again if it does not exist try { db.execSQL("alter table <API key> add column format text"); } catch (Exception e) { // it already exists, do nothing } } if (oldVersion < 23) { // Upgrade to new Notifications implementation using the "alarms" table db.execSQL("drop table notified"); db.execSQL("create table " + "alarms (" + " id integer primary key autoincrement," + " deadline_ts integer," + " media text," + " alarm_ts integer," + " notified integer," + " finished " + "integer" + ");"); } if (oldVersion < 24) { // Upgrade to new AccountItem implementaion db.execSQL("drop table accountdata_lent"); db.execSQL("drop table <API key>"); db.execSQL("create table " + "accountdata_lent (" + "id integer primary key autoincrement," + "account integer," + "title text," + "author text," + "format text," + "itemid text," + "status text," + "barcode text," + "deadline text," + "homebranch text," + "lending_branch text," + "prolong_data text," + "renewable integer," + "download_data text," + "ebook integer" + ");"); db.execSQL("create table " + "<API key> (" + "id integer primary key autoincrement," + "account integer," + "title text," + "author text," + "format text," + "itemid text," + "status text," + "ready text," + "expiration text," + "branch text," + "cancel_data text," + "booking_data text" + ");"); db.execSQL("drop table alarms"); db.execSQL("create table " + "alarms (" + "id integer primary key autoincrement," + "deadline text," + "media text," + "alarm text," + "notified integer," + "finished integer" + ");"); } if (oldVersion < 26) { // App version 4.4.x to 4.5.0 // We incremented by one, because I am stupid. try { db.execSQL("alter table accounts add column passwordValid integer"); } catch (Exception e) { // it already exists, do nothing } } if (oldVersion < 27) { db.execSQL("alter table accountdata_lent add column mediatype text"); db.execSQL("alter table accountdata_lent add column cover text"); db.execSQL("alter table <API key> add column mediatype text"); db.execSQL("alter table <API key> add column cover text"); } if (oldVersion < 28) { db.execSQL("alter table accounts add column <API key> integer"); } } }
<?php declare(strict_types=1); namespace App\View\Helper; use Zend\View\Helper\AbstractHelper; final class SpeakerHeadshot extends AbstractHelper { /** * @var string */ private $region; /** * @var string */ private $bucket; public function __construct(string $region, string $bucket) { $this->region = $region; $this->bucket = $bucket; } public function __invoke(string $filename): string { return sprintf('https://s3.%s.amazonaws.com/%s/%s', $this->region, $this->bucket, $filename); } }
'use strict'; import { Promise, TPromise } from 'vs/base/common/winjs.base'; import extfs = require('vs/base/node/extfs'); import paths = require('vs/base/common/paths'); import { dirname, join } from 'path'; import { nfcall } from 'vs/base/common/async'; import fs = require('fs'); export function isRoot(path: string): boolean { return path === dirname(path); } export function readdir(path: string): TPromise<string[]> { return nfcall(extfs.readdir, path); } export function exists(path: string): TPromise<boolean> { return new Promise(c => fs.exists(path, c)); } export function chmod(path: string, mode: number): TPromise<boolean> { return nfcall(fs.chmod, path, mode); } export function mkdirp(path: string, mode?: number): TPromise<boolean> { const mkdir = () => nfcall(fs.mkdir, path, mode) .then(null, (err: NodeJS.ErrnoException) => { if (err.code === 'EEXIST') { return nfcall(fs.stat, path) .then((stat: fs.Stats) => stat.isDirectory ? null : Promise.wrapError(new Error(`'${ path }' exists and is not a directory.`))); } return TPromise.wrapError<boolean>(err); }); if (isRoot(path)) { return TPromise.as(true); } return mkdir().then(null, (err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') { return mkdirp(dirname(path), mode).then(mkdir); } return TPromise.wrapError<boolean>(err); }); } export function rimraf(path: string): TPromise<void> { return stat(path).then(stat => { if (stat.isDirectory()) { return readdir(path) .then(children => TPromise.join(children.map(child => rimraf(join(path, child))))) .then(() => rmdir(path)); } else { return unlink(path); } }, (err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') { return; } return TPromise.wrapError<void>(err); }); } export function realpath(path: string): TPromise<string> { return nfcall(fs.realpath, path, null); } export function stat(path: string): TPromise<fs.Stats> { return nfcall(fs.stat, path); } export function mstat(paths: string[]): TPromise<{ path: string; stats: fs.Stats; }> { return doStatMultiple(paths.slice(0)); } export function rename(oldPath: string, newPath: string): Promise { return nfcall(fs.rename, oldPath, newPath); } export function rmdir(path: string): Promise { return nfcall(fs.rmdir, path); } export function unlink(path: string): Promise { return nfcall(fs.unlink, path); } function doStatMultiple(paths: string[]): TPromise<{ path: string; stats: fs.Stats; }> { var path = paths.shift(); return stat(path).then((value) => { return { path: path, stats: value }; }, (err) => { if (paths.length === 0) { return err; } return mstat(paths); }); } export function readFile(path: string): TPromise<Buffer>; export function readFile(path: string, encoding: string): TPromise<string>; export function readFile(path: string, encoding?: string): TPromise<Buffer | string> { return nfcall(fs.readFile, path, encoding); } export function writeFile(path: string, data: string, encoding?: string): Promise; export function writeFile(path: string, data: NodeBuffer, encoding?: string): Promise; export function writeFile(path: string, data: any, encoding: string = 'utf8'): Promise { return nfcall(fs.writeFile, path, data, encoding); } /** * Read a dir and return only subfolders */ export function readDirsInDir(dirPath: string): TPromise<string[]> { return readdir(dirPath).then((children) => { return TPromise.join( children.map((child) => dirExistsWithResult(paths.join(dirPath, child), child)) ).then((subdirs) => { return removeNull(subdirs); }); }); } function dirExistsWithResult<T>(path: string, successResult: T): TPromise<T> { return dirExists(path).then((exists) => { return exists ? successResult : null; }); } /** * `path` exists and is a directory */ export function dirExists(path: string): TPromise<boolean> { return stat(path).then(stat => stat.isDirectory(), () => false); } /** * `path` exists and is a file. */ export function fileExists(path: string): TPromise<boolean> { return stat(path).then(stat => stat.isFile(), () => false); } /** * Read dir at `path` and return only files matching `pattern` */ export function readFiles(path: string, pattern: RegExp): TPromise<string[]> { return readdir(path).then((children) => { children = children.filter((child) => { return pattern.test(child); }); let fileChildren = children.map((child) => { return <API key>(paths.join(path, child), child); }); return TPromise.join(fileChildren).then((subdirs) => { return removeNull(subdirs); }); }); } export function <API key><T>(path: string, successResult: T): TPromise<T> { return fileExists(path).then((exists) => { return exists ? successResult : null; }, (err) => { return TPromise.wrapError(err); }); } function removeNull<T>(arr: T[]): T[] { return arr.filter(item => (item !== null)); }
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using EarTrumpet.Services; namespace EarTrumpet.Extensions { static class DoubleExtensions { public static double Bound(this double val, double min, double max) { return Math.Max(min, Math.Min(max, val)); } } }
<?php declare(strict_types=1); namespace Humbug\PhpScoper\Patcher; use PHPUnit\Framework\TestCase; /** * @covers \Humbug\PhpScoper\Patcher\SymfonyPatcher */ class SymfonyPatcherTest extends TestCase { /** * @dataProvider provideFiles */ public function <API key>(string $filePath, string $contents, string $expected): void { $actual = (new SymfonyPatcher())->__invoke($filePath, 'Humbug', $contents); self::assertSame($expected, $actual); } public static function provideFiles(): iterable { $validPaths = [ 'src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php', 'symfony/<API key>/Dumper/PhpDumper.php', 'vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php', 'vendor/symfony/<API key>/Dumper/PhpDumper.php', ]; $invalidPaths = [ 'DependencyInjection/Dumper/PhpDumper.php', '<API key>/Dumper/PhpDumper.php', 'Dumper/PhpDumper.php', ]; foreach (self::provideCodeSamples() as [$input, $scopedOutput]) { foreach ($validPaths as $path) { yield [$path, $input, $scopedOutput]; } foreach ($invalidPaths as $path) { yield [$path, $input, $input]; } } } private static function provideCodeSamples(): iterable { yield [ 'PHP' private function startClass(string $class, string $baseClass, string $<API key>): string { $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; $code = <<<EOF <?php $namespaceLine use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\Exception\<API key>; use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; /*{$this->docStar} * This class has been auto-generated * by the Symfony Dependency Injection Component. * * @final since Symfony 3.3 */ class $class extends $baseClass { private \$parameters; private \$targetDirs = array(); /*{$this->docStar} * @internal but protected for BC on cache:clear */ protected \$privates = array(); public function __construct() { EOF; PHP , 'PHP' private function startClass(string $class, string $baseClass, string $<API key>): string { $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; $code = <<<EOF <?php $namespaceLine use Humbug\Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Humbug\Symfony\Component\DependencyInjection\ContainerInterface; use Humbug\Symfony\Component\DependencyInjection\Container; use Humbug\Symfony\Component\DependencyInjection\Exception\<API key>; use Humbug\Symfony\Component\DependencyInjection\Exception\LogicException; use Humbug\Symfony\Component\DependencyInjection\Exception\RuntimeException; use Humbug\Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; /*{$this->docStar} * This class has been auto-generated * by the Symfony Dependency Injection Component. * * @final since Symfony 3.3 */ class $class extends $baseClass { private \$parameters; private \$targetDirs = array(); /*{$this->docStar} * @internal but protected for BC on cache:clear */ protected \$privates = array(); public function __construct() { EOF; PHP ]; yield [ 'PHP' private function startClass(string $class, string $baseClass, string $<API key>): string { $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; $code = <<<EOF <?php $namespaceLine use Symfony\\Component\\DependencyInjection\\Argument\\RewindableGenerator; use Symfony\\Component\\DependencyInjection\\ContainerInterface; use Symfony\\Component\\DependencyInjection\\Container; use Symfony\\Component\\DependencyInjection\\Exception\\<API key>; use Symfony\\Component\\DependencyInjection\\Exception\\LogicException; use Symfony\\Component\\DependencyInjection\\Exception\\RuntimeException; use Symfony\\Component\\DependencyInjection\\ParameterBag\\FrozenParameterBag; /*{$this->docStar} * This class has been auto-generated * by the Symfony Dependency Injection Component. * * @final since Symfony 3.3 */ class $class extends $baseClass { private \$parameters; private \$targetDirs = array(); /*{$this->docStar} * @internal but protected for BC on cache:clear */ protected \$privates = array(); public function __construct() { EOF; PHP , 'PHP' private function startClass(string $class, string $baseClass, string $<API key>): string { $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; $code = <<<EOF <?php $namespaceLine use Humbug\\Symfony\\Component\\DependencyInjection\\Argument\\RewindableGenerator; use Humbug\\Symfony\\Component\\DependencyInjection\\ContainerInterface; use Humbug\\Symfony\\Component\\DependencyInjection\\Container; use Humbug\\Symfony\\Component\\DependencyInjection\\Exception\\<API key>; use Humbug\\Symfony\\Component\\DependencyInjection\\Exception\\LogicException; use Humbug\\Symfony\\Component\\DependencyInjection\\Exception\\RuntimeException; use Humbug\\Symfony\\Component\\DependencyInjection\\ParameterBag\\FrozenParameterBag; /*{$this->docStar} * This class has been auto-generated * by the Symfony Dependency Injection Component. * * @final since Symfony 3.3 */ class $class extends $baseClass { private \$parameters; private \$targetDirs = array(); /*{$this->docStar} * @internal but protected for BC on cache:clear */ protected \$privates = array(); public function __construct() { EOF; PHP ]; yield [ 'PHP' private function startClass(string $class, string $baseClass, string $<API key>): string { $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; $code = <<<EOF <?php $namespaceLine use Humbug\Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Humbug\Symfony\Component\DependencyInjection\ContainerInterface; use Humbug\Symfony\Component\DependencyInjection\Container; use Humbug\Symfony\Component\DependencyInjection\Exception\<API key>; use Humbug\Symfony\Component\DependencyInjection\Exception\LogicException; use Humbug\Symfony\Component\DependencyInjection\Exception\RuntimeException; use Humbug\Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; /*{$this->docStar} * This class has been auto-generated * by the Symfony Dependency Injection Component. * * @final since Symfony 3.3 */ class $class extends $baseClass { private \$parameters; private \$targetDirs = array(); /*{$this->docStar} * @internal but protected for BC on cache:clear */ protected \$privates = array(); public function __construct() { EOF; PHP , 'PHP' private function startClass(string $class, string $baseClass, string $<API key>): string { $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; $code = <<<EOF <?php $namespaceLine use Humbug\Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Humbug\Symfony\Component\DependencyInjection\ContainerInterface; use Humbug\Symfony\Component\DependencyInjection\Container; use Humbug\Symfony\Component\DependencyInjection\Exception\<API key>; use Humbug\Symfony\Component\DependencyInjection\Exception\LogicException; use Humbug\Symfony\Component\DependencyInjection\Exception\RuntimeException; use Humbug\Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; /*{$this->docStar} * This class has been auto-generated * by the Symfony Dependency Injection Component. * * @final since Symfony 3.3 */ class $class extends $baseClass { private \$parameters; private \$targetDirs = array(); /*{$this->docStar} * @internal but protected for BC on cache:clear */ protected \$privates = array(); public function __construct() { EOF; PHP ]; } }
/* eslint-disable */ 'use strict'; if (typeof Peeracle === 'undefined') { var Peeracle = require('..'); } describe('Peer', function() { });
MIT License Copyright (c) 2017 Baeldung 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.
namespace JK.Common.Patterns.Specification { <summary> Abstraction on ISpecification that supplies And, Or and Not. </summary> <typeparam name="TEntity">The type of entity.</typeparam> public abstract class Specification<TEntity> : ISpecification<TEntity> { <summary> Determines whether the specified candidate is satisfied by TEntity. </summary> <param name="candidate">The candidate.</param> <returns>True if is satisfied by the specified candidate; otherwise false.</returns> public abstract bool IsSatisfiedBy(TEntity candidate); <summary> Ands the specified specification. </summary> <param name="specification">The specification</param> <returns>Returns a new specification of type And.</returns> public ISpecification<TEntity> And(ISpecification<TEntity> specification) { return new AndSpecification<TEntity>(this, specification); } <summary> Performs the 'not' operators on this instance. </summary> <returns>Returns a new specification of type Not.</returns> public ISpecification<TEntity> Not() { return new NotSpecification<TEntity>(this); } <summary> Performs the 'or' operator on the specified specification. </summary> <param name="specification">The specification.</param> <returns>Returns a new specification of type Or.</returns> public ISpecification<TEntity> Or(ISpecification<TEntity> specification) { return new OrSpecification<TEntity>(this, specification); } } }
package org.lwjgl.opengl; import org.lwjgl.LWJGLException; import java.nio.ByteBuffer; import java.nio.IntBuffer; /** * @author elias_naur <elias_naur@users.sourceforge.net> * @version $Revision$ * $Id$ */ final class <API key> implements <API key> { public ByteBuffer create(PeerInfo peer_info, IntBuffer attribs, ByteBuffer <API key>) throws LWJGLException { LinuxDisplay.lockAWT(); try { ByteBuffer peer_handle = peer_info.lockAndGetHandle(); try { return nCreate(peer_handle, attribs, <API key>); } finally { peer_info.unlock(); } } finally { LinuxDisplay.unlockAWT(); } } private static native ByteBuffer nCreate(ByteBuffer peer_handle, IntBuffer attribs, ByteBuffer <API key>) throws LWJGLException; native long getGLXContext(ByteBuffer context_handle); native long getDisplay(ByteBuffer peer_info_handle); public void releaseDrawable(ByteBuffer context_handle) throws LWJGLException { } public void swapBuffers() throws LWJGLException { ContextGL current_context = ContextGL.getCurrentContext(); if ( current_context == null ) throw new <API key>("No context is current"); synchronized ( current_context ) { PeerInfo current_peer_info = current_context.getPeerInfo(); LinuxDisplay.lockAWT(); try { ByteBuffer peer_handle = current_peer_info.lockAndGetHandle(); try { nSwapBuffers(peer_handle); } finally { current_peer_info.unlock(); } } finally { LinuxDisplay.unlockAWT(); } } } private static native void nSwapBuffers(ByteBuffer peer_info_handle) throws LWJGLException; public void <API key>() throws LWJGLException { ContextGL current_context = ContextGL.getCurrentContext(); if ( current_context == null ) throw new <API key>("No context is current"); synchronized ( current_context ) { PeerInfo current_peer_info = current_context.getPeerInfo(); LinuxDisplay.lockAWT(); try { ByteBuffer peer_handle = current_peer_info.lockAndGetHandle(); try { <API key>(peer_handle); } finally { current_peer_info.unlock(); } } finally { LinuxDisplay.unlockAWT(); } } } private static native void <API key>(ByteBuffer peer_info_handle) throws LWJGLException; public void update(ByteBuffer context_handle) { } public void makeCurrent(PeerInfo peer_info, ByteBuffer handle) throws LWJGLException { LinuxDisplay.lockAWT(); try { ByteBuffer peer_handle = peer_info.lockAndGetHandle(); try { nMakeCurrent(peer_handle, handle); } finally { peer_info.unlock(); } } finally { LinuxDisplay.unlockAWT(); } } private static native void nMakeCurrent(ByteBuffer peer_handle, ByteBuffer context_handle) throws LWJGLException; public boolean isCurrent(ByteBuffer handle) throws LWJGLException { LinuxDisplay.lockAWT(); try { boolean result = nIsCurrent(handle); return result; } finally { LinuxDisplay.unlockAWT(); } } private static native boolean nIsCurrent(ByteBuffer context_handle) throws LWJGLException; public void setSwapInterval(int value) { ContextGL current_context = ContextGL.getCurrentContext(); PeerInfo peer_info = current_context.getPeerInfo(); if ( current_context == null ) throw new <API key>("No context is current"); synchronized ( current_context ) { LinuxDisplay.lockAWT(); try { ByteBuffer peer_handle = peer_info.lockAndGetHandle(); try { nSetSwapInterval(peer_handle, current_context.getHandle(), value); } finally { peer_info.unlock(); } } catch (LWJGLException e) { // API CHANGE - this methods should throw LWJGLException e.printStackTrace(); } finally { LinuxDisplay.unlockAWT(); } } } private static native void nSetSwapInterval(ByteBuffer peer_handle, ByteBuffer context_handle, int value); public void destroy(PeerInfo peer_info, ByteBuffer handle) throws LWJGLException { LinuxDisplay.lockAWT(); try { ByteBuffer peer_handle = peer_info.lockAndGetHandle(); try { nDestroy(peer_handle, handle); } finally { peer_info.unlock(); } } finally { LinuxDisplay.unlockAWT(); } } private static native void nDestroy(ByteBuffer peer_handle, ByteBuffer context_handle) throws LWJGLException; }
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <fcntl.h> #ifdef _WIN32 #include "winconfig.h" #elif defined(HAVE_EXPAT_CONFIG_H) #include <expat_config.h> #endif /* ndef _WIN32 */ #include "expat.h" #include "internal.h" /* for UNUSED_P only */ #include "xmlfile.h" #include "xmltchar.h" #include "filemap.h" #if defined(_MSC_VER) #include <io.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifndef O_BINARY #ifdef _O_BINARY #define O_BINARY _O_BINARY #else #define O_BINARY 0 #endif #endif #ifdef _DEBUG #define READ_SIZE 16 #else #define READ_SIZE (1024*8) #endif typedef struct { XML_Parser parser; int *retPtr; } PROCESS_ARGS; static int processStream(const XML_Char *filename, XML_Parser parser); static void reportError(XML_Parser parser, const XML_Char *filename) { enum XML_Error code = XML_GetErrorCode(parser); const XML_Char *message = XML_ErrorString(code); if (message) ftprintf(stdout, T("%s:%" XML_FMT_INT_MOD "u:%" XML_FMT_INT_MOD "u: %s\n"), filename, <API key>(parser), <API key>(parser), message); else ftprintf(stderr, T("%s: (unknown message %d)\n"), filename, code); } /* This implementation will give problems on files larger than INT_MAX. */ static void processFile(const void *data, size_t size, const XML_Char *filename, void *args) { XML_Parser parser = ((PROCESS_ARGS *)args)->parser; int *retPtr = ((PROCESS_ARGS *)args)->retPtr; if (XML_Parse(parser, (const char *)data, (int)size, 1) == XML_STATUS_ERROR) { reportError(parser, filename); *retPtr = 0; } else *retPtr = 1; } #if defined(_WIN32) static int isAsciiLetter(XML_Char c) { return (T('a') <= c && c <= T('z')) || (T('A') <= c && c <= T('Z')); } #endif /* _WIN32 */ static const XML_Char * resolveSystemId(const XML_Char *base, const XML_Char *systemId, XML_Char **toFree) { XML_Char *s; *toFree = 0; if (!base || *systemId == T('/') #if defined(_WIN32) || *systemId == T('\\') || (isAsciiLetter(systemId[0]) && systemId[1] == T(':')) #endif ) return systemId; *toFree = (XML_Char *)malloc((tcslen(base) + tcslen(systemId) + 2) * sizeof(XML_Char)); if (!*toFree) return systemId; tcscpy(*toFree, base); s = *toFree; if (tcsrchr(s, T('/'))) s = tcsrchr(s, T('/')) + 1; #if defined(_WIN32) if (tcsrchr(s, T('\\'))) s = tcsrchr(s, T('\\')) + 1; #endif tcscpy(s, systemId); return *toFree; } static int <API key>(XML_Parser parser, const XML_Char *context, const XML_Char *base, const XML_Char *systemId, const XML_Char *UNUSED_P(publicId)) { int result; XML_Char *s; const XML_Char *filename; XML_Parser entParser = <API key>(parser, context, 0); int filemapRes; PROCESS_ARGS args; args.retPtr = &result; args.parser = entParser; filename = resolveSystemId(base, systemId, &s); XML_SetBase(entParser, filename); filemapRes = filemap(filename, processFile, &args); switch (filemapRes) { case 0: result = 0; break; case 2: ftprintf(stderr, T("%s: file too large for memory-mapping") T(", switching to streaming\n"), filename); result = processStream(filename, entParser); break; } free(s); XML_ParserFree(entParser); return result; } static int processStream(const XML_Char *filename, XML_Parser parser) { /* passing NULL for filename means read intput from stdin */ int fd = 0; /* 0 is the fileno for stdin */ if (filename != NULL) { fd = topen(filename, O_BINARY|O_RDONLY); if (fd < 0) { tperror(filename); return 0; } } for (;;) { int nread; char *buf = (char *)XML_GetBuffer(parser, READ_SIZE); if (!buf) { if (filename != NULL) close(fd); ftprintf(stderr, T("%s: out of memory\n"), filename != NULL ? filename : "xmlwf"); return 0; } nread = read(fd, buf, READ_SIZE); if (nread < 0) { tperror(filename != NULL ? filename : "STDIN"); if (filename != NULL) close(fd); return 0; } if (XML_ParseBuffer(parser, nread, nread == 0) == XML_STATUS_ERROR) { reportError(parser, filename != NULL ? filename : "STDIN"); if (filename != NULL) close(fd); return 0; } if (nread == 0) { if (filename != NULL) close(fd); break;; } } return 1; } static int <API key>(XML_Parser parser, const XML_Char *context, const XML_Char *base, const XML_Char *systemId, const XML_Char *UNUSED_P(publicId)) { XML_Char *s; const XML_Char *filename; int ret; XML_Parser entParser = <API key>(parser, context, 0); filename = resolveSystemId(base, systemId, &s); XML_SetBase(entParser, filename); ret = processStream(filename, entParser); free(s); XML_ParserFree(entParser); return ret; } int XML_ProcessFile(XML_Parser parser, const XML_Char *filename, unsigned flags) { int result; if (!XML_SetBase(parser, filename)) { ftprintf(stderr, T("%s: out of memory"), filename); exit(1); } if (flags & <API key>) <API key>(parser, (flags & XML_MAP_FILE) ? <API key> : <API key>); if (flags & XML_MAP_FILE) { int filemapRes; PROCESS_ARGS args; args.retPtr = &result; args.parser = parser; filemapRes = filemap(filename, processFile, &args); switch (filemapRes) { case 0: result = 0; break; case 2: ftprintf(stderr, T("%s: file too large for memory-mapping") T(", switching to streaming\n"), filename); result = processStream(filename, parser); break; } } else result = processStream(filename, parser); return result; }
//! moment.js locale configuration //! locale : siSwati [ss] import moment from '../moment'; export default moment.defineLocale('ss', { months : "<API key>'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split('_'), monthsShort : '<API key>'.split('_'), weekdays : '<API key>'.split('_'), weekdaysShort : '<API key>'.split('_'), weekdaysMin : '<API key>'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { sameDay : '[Namuhla nga] LT', nextDay : '[Kusasa nga] LT', nextWeek : 'dddd [nga] LT', lastDay : '[Itolo nga] LT', lastWeek : 'dddd [leliphelile] [nga] LT', sameElse : 'L' }, relativeTime : { future : 'nga %s', past : 'wenteka nga %s', s : 'emizuzwana lomcane', ss : '%d mzuzwana', m : 'umzuzu', mm : '%d emizuzu', h : 'lihora', hh : '%d emahora', d : 'lilanga', dd : '%d emalanga', M : 'inyanga', MM : '%d tinyanga', y : 'umnyaka', yy : '%d iminyaka' }, meridiemParse: /ekuseni|emini|entsambama|ebusuku/, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'ekuseni'; } else if (hours < 15) { return 'emini'; } else if (hours < 19) { return 'entsambama'; } else { return 'ebusuku'; } }, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ekuseni') { return hour; } else if (meridiem === 'emini') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') { if (hour === 0) { return 0; } return hour + 12; } }, <API key>: /\d{1,2}/, ordinal : '%d', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } });
title: Downloads aliases: - /enterprise/v1.1/introduction/download/ menu: <API key>: weight: 0 parent: Introduction Please visit [InfluxPortal](https: Also see the [Installation](/enterprise_influxdb/v1.1/introduction/<API key>/) documentation to access the downloads. You must have a valid license to run a cluster. InfluxPortal offers 14-day Demo licenses on sign-up.
# encoding: UTF-8 require 'test_helper' class NumericInputTest < ActionView::TestCase test 'input generates an integer text field for integer attributes ' do with_input_for @user, :age, :integer assert_select 'input[type=number].integer#user_age' end test 'input generates a float text field for float attributes ' do with_input_for @user, :age, :float assert_select 'input[type=number].float#user_age' end test 'input generates a decimal text field for decimal attributes ' do with_input_for @user, :age, :decimal assert_select 'input[type=number].decimal#user_age' end test 'input does not generate min attribute by default' do with_input_for @user, :age, :integer assert_no_select 'input[min]' end test 'input does not generate max attribute by default' do with_input_for @user, :age, :integer assert_no_select 'input[max]' end test 'input infers min value from integer attributes with greater than validation' do with_input_for @<API key>, :age, :float assert_no_select 'input[min]' with_input_for @<API key>, :age, :integer assert_select 'input[min="18"]' end test 'input infers min value from integer attributes with greater than validation using symbol' do with_input_for @validating_user, :amount, :float assert_no_select 'input[min]' with_input_for @validating_user, :amount, :integer assert_select 'input[min="11"]' end test 'input infers min value from integer attributes with greater than or equal to validation using symbol' do with_input_for @validating_user, :attempts, :float assert_select 'input[min="1"]' with_input_for @validating_user, :attempts, :integer assert_select 'input[min="1"]' end test 'input infers min value from integer attributes with greater than validation using proc' do with_input_for @<API key>, :amount, :float assert_no_select 'input[min]' with_input_for @<API key>, :amount, :integer assert_select 'input[min="20"]' end test 'input infers min value from integer attributes with greater than or equal to validation using proc' do with_input_for @<API key>, :attempts, :float assert_select 'input[min="19"]' with_input_for @<API key>, :attempts, :integer assert_select 'input[min="19"]' end test 'input infers max value from attributes with less than validation' do with_input_for @<API key>, :age, :float assert_no_select 'input[max]' with_input_for @<API key>, :age, :integer assert_select 'input[max="99"]' end test 'input infers max value from attributes with less than validation using symbol' do with_input_for @validating_user, :amount, :float assert_no_select 'input[max]' with_input_for @validating_user, :amount, :integer assert_select 'input[max="99"]' end test 'input infers max value from attributes with less than or equal to validation using symbol' do with_input_for @validating_user, :attempts, :float assert_select 'input[max="100"]' with_input_for @validating_user, :attempts, :integer assert_select 'input[max="100"]' end test 'input infers max value from attributes with less than validation using proc' do with_input_for @<API key>, :amount, :float assert_no_select 'input[max]' with_input_for @<API key>, :amount, :integer assert_select 'input[max="118"]' end test 'input infers max value from attributes with less than or equal to validation using proc' do with_input_for @<API key>, :attempts, :float assert_select 'input[max="119"]' with_input_for @<API key>, :attempts, :integer assert_select 'input[max="119"]' end test 'input has step value of any except for integer attribute' do with_input_for @validating_user, :age, :float assert_select 'input[step="any"]' with_input_for @validating_user, :age, :integer assert_select 'input[step="1"]' with_input_for @validating_user, :age, :integer, as: :decimal, input_html: { step: 0.5 } assert_select 'input[step="0.5"]' end test 'numeric input does not generate placeholder by default' do with_input_for @user, :age, :integer assert_no_select 'input[placeholder]' end test 'numeric input accepts the placeholder option' do with_input_for @user, :age, :integer, placeholder: 'Put in your age' assert_select 'input.integer[placeholder="Put in your age"]' end test 'numeric input uses i18n to translate placeholder text' do store_translations(:en, simple_form: { placeholders: { user: { age: 'Age goes here' } } }) do with_input_for @user, :age, :integer assert_select 'input.integer[placeholder="Age goes here"]' end end # Numeric input but HTML5 disabled test 'when not using HTML5 input does not generate field with type number and use text instead' do swap_wrapper do with_input_for @user, :age, :integer assert_no_select "input[type=number]" assert_no_select "input#user_age[text]" end end test 'when not using HTML5 input does not use min or max or step attributes' do swap_wrapper do with_input_for @validating_user, :age, :integer assert_no_select "input[type=number]" assert_no_select "input[min]" assert_no_select "input[max]" assert_no_select "input[step]" end end [:integer, :float, :decimal].each do |type| test "#{type} input infers min value from attributes with greater than or equal validation" do with_input_for @validating_user, :age, type assert_select 'input[min="18"]' end test "#{type} input infers the max value from attributes with less than or equal to validation" do with_input_for @validating_user, :age, type assert_select 'input[max="99"]' end end test 'min_max does not emit max value as bare string' do with_input_for @<API key>, :age, :integer assert_select 'input[max]' assert_no_select 'div', %r{^99} end end
#if !defined(<API key>) #define <API key> #include <mitsuba/hw/session.h> MTS_NAMESPACE_BEGIN /** \brief A MacOS X (NSGL) windowing environment session * \ingroup libhw */ class MTS_EXPORT_HW NSGLSession : public Session { public: Create a new session NSGLSession(); Initialize the session void init(); Shut the session down void shutdown(); Process all events and call event callbacks void processEvents(); /** * \brief Process all events and call event callbacks. * * This function will run until the \c stop parameter is set * to \c true from within an event callback. */ void <API key>(bool &stop); MTS_DECLARE_CLASS() protected: Virtual destructor virtual ~NSGLSession(); }; MTS_NAMESPACE_END #endif /* <API key> */
#include "stdneb.h" #include "particles/affectors/<API key>.h" namespace Particles { using namespace Serialization; const static char* s_Gravity = "Movement"; const static char* s_GravityPosition = "MovementPosition"; extern const char* s_KeyFrameCount; extern const char* s_CurveKey; extern const char* s_CurveValue; class <API key> { public: void Load( MovementAffector* obj, SVersion ver, SerializeReader* pReader ) { if ( 1 == ver ) { Load_1(obj, pReader); return; } else if(2 == ver) { Load_2(obj,pReader); return; } n_error(" %s Load unknown version.\n", obj->GetClassName().AsCharPtr() ); } void Load_1(MovementAffector* obj, SerializeReader* pReader) { <API key>(pReader,*obj->getMinMaxCurve(<API key>),"Movement",s_CurveKey); <API key>(pReader,*obj->getMinMaxCurve(Affector_MovementX),"MovementX",s_CurveKey); <API key>(pReader,*obj->getMinMaxCurve(Affector_MovementY),"MovementY",s_CurveKey); <API key>(pReader,*obj->getMinMaxCurve(Affector_MovementZ),"MovementZ",s_CurveKey); } void Load_2(MovementAffector* obj, SerializeReader* pReader) { <API key>(pReader,*obj->getMinMaxCurve(<API key>),"Movement",s_CurveKey); <API key>(pReader,*obj->getMinMaxCurve(Affector_MovementX),"MovementX",s_CurveKey); <API key>(pReader,*obj->getMinMaxCurve(Affector_MovementY),"MovementY",s_CurveKey); <API key>(pReader,*obj->getMinMaxCurve(Affector_MovementZ),"MovementZ",s_CurveKey); } void Save( const MovementAffector* obj, SerializeWriter* pWriter ) { <API key>(pWriter,*((MovementAffector* )obj)->getMinMaxCurve(<API key>),"Movement",s_CurveKey); <API key>(pWriter,*((MovementAffector* )obj)->getMinMaxCurve(Affector_MovementX),"MovementX",s_CurveKey); <API key>(pWriter,*((MovementAffector* )obj)->getMinMaxCurve(Affector_MovementY),"MovementY",s_CurveKey); <API key>(pWriter,*((MovementAffector* )obj)->getMinMaxCurve(Affector_MovementZ),"MovementZ",s_CurveKey); } }; // @ISerialization::GetVersion. when change storage, must add SerializeVersion count SVersion MovementAffector::GetVersion() const { return 2; } // @ISerialization::Load void MovementAffector::Load( SVersion ver, SerializeReader* pReader, const Serialization::SerializationArgs* args ) { pReader->SerializeSuper<Super>(this, args); <API key> Serialize; Serialize.Load( this, ver, pReader ); } // @ISerialization::Save void MovementAffector::Save( SerializeWriter* pWriter ) const { pWriter->SerializeSuper<Super>(this); <API key> Serialize; Serialize.Save( this, pWriter ); } void MovementAffector::CopyFrom( const ParticleAffectorPtr& target ) { Super::CopyFrom( target ); n_assert( target->GetRtti() == this->GetRtti() ); GPtr<MovementAffector> source = target.downcast<MovementAffector>(); <API key>(source->mMinMaxSpeed,this->mMinMaxSpeed); <API key>(source->mMinMaxPosX,this->mMinMaxPosX); <API key>(source->mMinMaxPosY,this->mMinMaxPosY); <API key>(source->mMinMaxPosZ,this->mMinMaxPosZ); } }
from alembic import op # revision identifiers, used by Alembic. revision = "2979a1322381" down_revision = "2b478162b2b7" def upgrade(): op.drop_index("<API key>", table_name="notification") op.drop_table("notification") op.drop_column("diagram", "data") op.drop_constraint("<API key>", "document", type_="foreignkey") # op.alter_column('role', 'is_muted', # existing_type=sa.BOOLEAN(), # nullable=False) op.drop_column("role", "notified_at") def downgrade(): pass
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "m9.31 17 2.44-2.44L14.19 17l1.06-1.06-2.44-2.44 2.44-2.44L14.19 10l-2.44 2.44L9.31 10l-1.06 1.06 2.44 2.44-2.44 2.44L9.31 17zM19 <API key>.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z" }), 'EventBusy');
<?php namespace CurrencyCloud\Model; use ArrayIterator; class Contacts extends PaginatedData { /** * @var Contact[] */ private $contacts; /** * @param Contact[] $contacts * @param Pagination $pagination */ public function __construct(array $contacts, Pagination $pagination) { parent::__construct($pagination); $this->contacts = $contacts; } /** * @return Contact[] */ public function getContacts() { return $this->contacts; } /** * @inheritdoc */ public function getIterator() { return new ArrayIterator($this->contacts); } /** * @inheritdoc */ public function count() { return count($this->contacts); } }
// For further details and documentation: (function(root){ // Module loading var Monitor = root.Monitor || require('monitor-dashboard'), UI = Monitor.UI, core = UI.app.core = UI.app.core || {}, Chart = core.Chart, Backbone = Monitor.Backbone, _ = Monitor._; /** * A line chart view * * @class LineChart * @extends Backbone.View * @constructor * @param options {Object} View initialization options (See others in Backbone.View) * @param options.label='Chart' {String} The component label * @param options.icon='icon-bar-chart' {String} The icon class name * @param options.highcharts = {} {Object} Highcharts chart configuration object */ var LineChart = core.LineChart = Chart.extend({ // Define the view name: 'LineChart', tags: ['Chart', 'Time Series', 'Real Time'], icon: 'image/LineChart.png', description: 'A line chart', defaultOptions: { title: 'Line Chart', highcharts: { chart: { type: 'line', margin: null }, legend: { enabled: false }, xAxis: { title: { text: 'Values' }, labels: { enabled:true } }, yAxis: { title: { text: '' }, labels: { enabled:true } }, plotOptions: { line: { } }, series: [{ name: 'value', data: [1,0,4,10,3,8,7,7,3,0,5] }] } }, initialize: function(options) { var t = this; Chart.prototype.initialize.apply(t, arguments); } }); // This settings form is inherited by all charts. LineChart.SettingsView = Chart.SettingsView.extend({ // Extend for local events events: _.extend({}, Chart.SettingsView.prototype.events, { "change *" : "onChange" }), render: function() { var t = this; // Call parent render to set up dom Chart.SettingsView.prototype.render.apply(t, arguments); // Set my title & HTML $('.core-chart-settings').append('' + '<div class="core-gauge-label">' + '<label>X Axis Label</label>' + '<input class="xlabel" type="text"/>' + '</div>' + '<div class="<API key>">' + '<label>Y Axis Label</label>' + '<input class="ylabel" type="text"/>' + '</div>' ); // Set initial field values t.xlabel = t.$('.xlabel').val(t.hc.xAxis.title.text); t.ylabel = t.$('.ylabel').val(t.hc.yAxis.title.text); }, onChange: function() { var t = this; t.hc.xAxis.title.text = t.xlabel.val(); t.hc.yAxis.title.text = t.ylabel.val(); } }); }(this));
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Sql { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; <summary> <API key> operations. </summary> internal partial class <API key> : IServiceOperations<SqlManagementClient>, <API key> { <summary> Initializes a new instance of the <API key> class. </summary> <param name='client'> Reference to the service client. </param> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> internal <API key>(SqlManagementClient client) { if (client == null) { throw new System.<API key>("client"); } Client = client; } <summary> Gets a reference to the SqlManagementClient </summary> public SqlManagementClient Client { get; private set; } <summary> Completes the restore operation on a managed database. </summary> <param name='locationName'> The name of the region where the resource is located. </param> <param name='operationId'> Management operation id that this request tries to complete. </param> <param name='parameters'> The definition for completing the restore of this managed database. </param> <param name='customHeaders'> The headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> public async Task<<API key>> <API key>(string locationName, System.Guid operationId, <API key> parameters, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { // Send request <API key> _response = await <API key>(locationName, operationId, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.<API key>(_response, customHeaders, cancellationToken).ConfigureAwait(false); } <summary> Gets a list of managed databases. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='customHeaders'> Headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> <exception cref="CloudException"> Thrown when the operation returned an invalid status code </exception> <exception cref="<API key>"> Thrown when unable to deserialize the response </exception> <exception cref="ValidationException"> Thrown when a required parameter is null </exception> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> <return> A response object containing the response body and response headers. </return> public async Task<<API key><IPage<ManagedDatabase>>> <API key>(string resourceGroupName, string managedInstanceName, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (managedInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "managedInstanceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = <API key>.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = <API key>.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("managedInstanceName", managedInstanceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); <API key>.Enter(_invocationId, this, "ListByInstance", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{managedInstanceName}", System.Uri.EscapeDataString(managedInstanceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.<API key> != null && Client.<API key>.Value) { _httpRequest.Headers.<API key>("<API key>", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.<API key>("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.<API key>(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.<API key>(); await Client.Credentials.<API key>(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { <API key>.SendRequest(_invocationId, _httpRequest); } cancellationToken.<API key>(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { <API key>.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.<API key>(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.<API key>); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new <API key>(_httpRequest, _requestContent); ex.Response = new <API key>(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new <API key><IPage<ManagedDatabase>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<ManagedDatabase>>(_responseContent, Client.<API key>); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new <API key>("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { <API key>.Exit(_invocationId, _result); } return _result; } <summary> Gets a managed database. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='databaseName'> The name of the database. </param> <param name='customHeaders'> Headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> <exception cref="CloudException"> Thrown when the operation returned an invalid status code </exception> <exception cref="<API key>"> Thrown when unable to deserialize the response </exception> <exception cref="ValidationException"> Thrown when a required parameter is null </exception> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> <return> A response object containing the response body and response headers. </return> public async Task<<API key><ManagedDatabase>> <API key>(string resourceGroupName, string managedInstanceName, string databaseName, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (managedInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "managedInstanceName"); } if (databaseName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "databaseName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = <API key>.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = <API key>.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("managedInstanceName", managedInstanceName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); <API key>.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{managedInstanceName}", System.Uri.EscapeDataString(managedInstanceName)); _url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.<API key> != null && Client.<API key>.Value) { _httpRequest.Headers.<API key>("<API key>", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.<API key>("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.<API key>(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.<API key>(); await Client.Credentials.<API key>(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { <API key>.SendRequest(_invocationId, _httpRequest); } cancellationToken.<API key>(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { <API key>.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.<API key>(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.<API key>); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new <API key>(_httpRequest, _requestContent); ex.Response = new <API key>(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new <API key><ManagedDatabase>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ManagedDatabase>(_responseContent, Client.<API key>); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new <API key>("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { <API key>.Exit(_invocationId, _result); } return _result; } <summary> Creates a new database or updates an existing database. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='databaseName'> The name of the database. </param> <param name='parameters'> The requested database resource state. </param> <param name='customHeaders'> The headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> public async Task<<API key><ManagedDatabase>> <API key>(string resourceGroupName, string managedInstanceName, string databaseName, ManagedDatabase parameters, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { // Send Request <API key><ManagedDatabase> _response = await <API key>(resourceGroupName, managedInstanceName, databaseName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.<API key>(_response, customHeaders, cancellationToken).ConfigureAwait(false); } <summary> Deletes a managed database. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='databaseName'> The name of the database. </param> <param name='customHeaders'> The headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> public async Task<<API key>> <API key>(string resourceGroupName, string managedInstanceName, string databaseName, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { // Send request <API key> _response = await <API key>(resourceGroupName, managedInstanceName, databaseName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.<API key>(_response, customHeaders, cancellationToken).ConfigureAwait(false); } <summary> Updates an existing database. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='databaseName'> The name of the database. </param> <param name='parameters'> The requested database resource state. </param> <param name='customHeaders'> The headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> public async Task<<API key><ManagedDatabase>> <API key>(string resourceGroupName, string managedInstanceName, string databaseName, <API key> parameters, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { // Send Request <API key><ManagedDatabase> _response = await <API key>(resourceGroupName, managedInstanceName, databaseName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.<API key>(_response, customHeaders, cancellationToken).ConfigureAwait(false); } <summary> Completes the restore operation on a managed database. </summary> <param name='locationName'> The name of the region where the resource is located. </param> <param name='operationId'> Management operation id that this request tries to complete. </param> <param name='parameters'> The definition for completing the restore of this managed database. </param> <param name='customHeaders'> Headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> <exception cref="CloudException"> Thrown when the operation returned an invalid status code </exception> <exception cref="ValidationException"> Thrown when a required parameter is null </exception> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> <return> A response object containing the response body and response headers. </return> public async Task<<API key>> <API key>(string locationName, System.Guid operationId, <API key> parameters, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { if (locationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "locationName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = <API key>.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = <API key>.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("locationName", locationName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); <API key>.Enter(_invocationId, this, "<API key>", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/<API key>/{operationId}/completeRestore").ToString(); _url = _url.Replace("{locationName}", System.Uri.EscapeDataString(locationName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(operationId, Client.<API key>).Trim('"'))); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.<API key> != null && Client.<API key>.Value) { _httpRequest.Headers.<API key>("<API key>", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.<API key>("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.<API key>(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.<API key>); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.<API key>.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.<API key>(); await Client.Credentials.<API key>(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { <API key>.SendRequest(_invocationId, _httpRequest); } cancellationToken.<API key>(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { <API key>.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.<API key>(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.<API key>); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new <API key>(_httpRequest, _requestContent); ex.Response = new <API key>(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new <API key>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Exit(_invocationId, _result); } return _result; } <summary> Creates a new database or updates an existing database. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='databaseName'> The name of the database. </param> <param name='parameters'> The requested database resource state. </param> <param name='customHeaders'> Headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> <exception cref="CloudException"> Thrown when the operation returned an invalid status code </exception> <exception cref="<API key>"> Thrown when unable to deserialize the response </exception> <exception cref="ValidationException"> Thrown when a required parameter is null </exception> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> <return> A response object containing the response body and response headers. </return> public async Task<<API key><ManagedDatabase>> <API key>(string resourceGroupName, string managedInstanceName, string databaseName, ManagedDatabase parameters, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (managedInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "managedInstanceName"); } if (databaseName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "databaseName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = <API key>.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = <API key>.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("managedInstanceName", managedInstanceName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); <API key>.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{managedInstanceName}", System.Uri.EscapeDataString(managedInstanceName)); _url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.<API key> != null && Client.<API key>.Value) { _httpRequest.Headers.<API key>("<API key>", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.<API key>("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.<API key>(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.<API key>); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.<API key>.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.<API key>(); await Client.Credentials.<API key>(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { <API key>.SendRequest(_invocationId, _httpRequest); } cancellationToken.<API key>(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { <API key>.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.<API key>(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.<API key>); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new <API key>(_httpRequest, _requestContent); ex.Response = new <API key>(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new <API key><ManagedDatabase>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ManagedDatabase>(_responseContent, Client.<API key>); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new <API key>("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ManagedDatabase>(_responseContent, Client.<API key>); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new <API key>("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { <API key>.Exit(_invocationId, _result); } return _result; } <summary> Deletes a managed database. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='databaseName'> The name of the database. </param> <param name='customHeaders'> Headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> <exception cref="CloudException"> Thrown when the operation returned an invalid status code </exception> <exception cref="ValidationException"> Thrown when a required parameter is null </exception> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> <return> A response object containing the response body and response headers. </return> public async Task<<API key>> <API key>(string resourceGroupName, string managedInstanceName, string databaseName, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (managedInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "managedInstanceName"); } if (databaseName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "databaseName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = <API key>.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = <API key>.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("managedInstanceName", managedInstanceName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); <API key>.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{managedInstanceName}", System.Uri.EscapeDataString(managedInstanceName)); _url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.<API key> != null && Client.<API key>.Value) { _httpRequest.Headers.<API key>("<API key>", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.<API key>("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.<API key>(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.<API key>(); await Client.Credentials.<API key>(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { <API key>.SendRequest(_invocationId, _httpRequest); } cancellationToken.<API key>(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { <API key>.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.<API key>(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.<API key>); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new <API key>(_httpRequest, _requestContent); ex.Response = new <API key>(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new <API key>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Exit(_invocationId, _result); } return _result; } <summary> Updates an existing database. </summary> <param name='resourceGroupName'> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> <param name='managedInstanceName'> The name of the managed instance. </param> <param name='databaseName'> The name of the database. </param> <param name='parameters'> The requested database resource state. </param> <param name='customHeaders'> Headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> <exception cref="CloudException"> Thrown when the operation returned an invalid status code </exception> <exception cref="<API key>"> Thrown when unable to deserialize the response </exception> <exception cref="ValidationException"> Thrown when a required parameter is null </exception> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> <return> A response object containing the response body and response headers. </return> public async Task<<API key><ManagedDatabase>> <API key>(string resourceGroupName, string managedInstanceName, string databaseName, <API key> parameters, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (managedInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "managedInstanceName"); } if (databaseName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "databaseName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = <API key>.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = <API key>.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("managedInstanceName", managedInstanceName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); <API key>.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{managedInstanceName}", System.Uri.EscapeDataString(managedInstanceName)); _url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.<API key> != null && Client.<API key>.Value) { _httpRequest.Headers.<API key>("<API key>", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.<API key>("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.<API key>(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.<API key>); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.<API key>.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.<API key>(); await Client.Credentials.<API key>(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { <API key>.SendRequest(_invocationId, _httpRequest); } cancellationToken.<API key>(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { <API key>.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.<API key>(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.<API key>); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new <API key>(_httpRequest, _requestContent); ex.Response = new <API key>(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new <API key><ManagedDatabase>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ManagedDatabase>(_responseContent, Client.<API key>); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new <API key>("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { <API key>.Exit(_invocationId, _result); } return _result; } <summary> Gets a list of managed databases. </summary> <param name='nextPageLink'> The NextLink from the previous successful call to List operation. </param> <param name='customHeaders'> Headers that will be added to request. </param> <param name='cancellationToken'> The cancellation token. </param> <exception cref="CloudException"> Thrown when the operation returned an invalid status code </exception> <exception cref="<API key>"> Thrown when unable to deserialize the response </exception> <exception cref="ValidationException"> Thrown when a required parameter is null </exception> <exception cref="System.<API key>"> Thrown when a required parameter is null </exception> <return> A response object containing the response body and response headers. </return> public async Task<<API key><IPage<ManagedDatabase>>> <API key>(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, Cancellation<API key> = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = <API key>.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = <API key>.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); <API key>.Enter(_invocationId, this, "ListByInstanceNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.<API key> != null && Client.<API key>.Value) { _httpRequest.Headers.<API key>("<API key>", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.<API key>("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.<API key>(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.<API key>(); await Client.Credentials.<API key>(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { <API key>.SendRequest(_invocationId, _httpRequest); } cancellationToken.<API key>(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { <API key>.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.<API key>(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.<API key>); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new <API key>(_httpRequest, _requestContent); ex.Response = new <API key>(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { <API key>.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new <API key><IPage<ManagedDatabase>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<ManagedDatabase>>(_responseContent, Client.<API key>); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new <API key>("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { <API key>.Exit(_invocationId, _result); } return _result; } } }
{% extends path+"/scenario_03k/_layout.html" %} {% block assess_content %} <main id="content" role="main" class="main-content-inner"> <div class="container"> <div class="grid-row main-row"> <div class="column-one-quarter left-area"> <div class="left-panel"> <p style="font-weight:bold;">Review complete</p> <hr> <! <ul class="secondary-actions"> <li><a href="/{{path}}/scenario/not-testing">Observations</a></li> <li><a href="/{{path}}/scenario/not-testing" class="">Additional attendee</a></li> <li><a href="/{{path}}/scenario/not-testing">Abandon assessment</a></li> <li><a href="/{{path}}/<API key>/<API key>">Curtail assessment</a></li> </ul> {% block actioncolumn %}{% endblock %} </div> </div> <div class="<API key> main-area"> <div class="staff__heading"> <div class="grid-row"> <div class="column-half <API key>"> <!--<div class="badges"> <ul> <li class="badge">UC</li> {% if customer.name.first == 'Lowery' %} <li class="badge support-item">Unacceptable customer behaviour</li> {% endif %} </ul> </div> <h1 class="heading-xlarge"><span>Customer details</span>{% block citizen_detail %}Aaron Murray{% endblock %}</h1> <p class="mb20"><span class="visually-hidden">National insurance number</span>KK 12 34 56 L</p> </div><!-- column --> <div class="column-half <API key>"> <div class="header-left-col mt20"> <h2>Date of birth</h2> <p>12 September 1973 <!--{{customer.dateOfBirth |formatDate('D MMMM YYYY') }}--></p> </div> <div class="header-right-col mt20"> <h2>Benefit</h2> <p>Universal credit</p> </div> <!-- / column half --> </div><!-- / grid row --> </div> </div> <div nunj-block="citizen_content"> {% block citizen_content %}{% endblock %} </div><!-- column --> </div><!-- row --> </div><!-- container --> </main> {% endblock %} {% block page_scripts %} {{ super }} <script type="text/javascript"> $( document ).ready(function() { $( ".panel-switch" ).click(function() { $( ".inner-panel" ).toggleClass( "panel-open" ); }); }); </script> {% endblock %} {% block footer_top %} {{ super() }} {% endblock %}
# NOTICE: THIS FILE IS AUTOGENERATED # MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY # PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/space/capacitor/<API key>.iff" result.<API key> = -1 result.stfName("string_id_table","") return result
import { LoggerageObject } from '../loggerage-object'; import { Storage } from '../storage-interface'; import { Query } from './query'; export declare class WrapLocalStorage implements Storage { private _storage; constructor(localStorage: any); getItem(app: string, query?: Query): LoggerageObject[]; setItem(app: string, value: LoggerageObject): void; clear(): void; }
// <auto-generated> // This code was generated by Codezu. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> using System; using System.Collections.Generic; namespace Mozu.Api.Contracts.ProductAdmin { Mozu.ProductAdmin.Contracts.<API key> ApiType DOCUMENT_HERE public class <API key> { Collection list of items. All returned data is provided in an items array. For a failed request, the returned response may be success with an empty item collection. Items are used throughout APIs for carts, wish lists, documents, payments, returns, properties, and more. public List<PublishSet> Items { get; set; } Total number of objects in am item collection. Total counts are calculated for numerous objects in Mozu, including location inventory, products, options, product types, product reservations, categories, addresses, carriers, tax rates, time zones, and much more. public int TotalCount { get; set; } } }
import React from 'react'; const style = { marginTop: '30%' }; export default () => ( <div className="center spinner" style={style}> <div className="preloader-wrapper big active"> <div className="spinner-layer spinner-blue-only"> <div className="circle-clipper left"> <div className="circle"></div> </div><div className="gap-patch"> <div className="circle"></div> </div><div className="circle-clipper right"> <div className="circle"></div> </div> </div> </div> </div> );
/*global Reply*/ /** A Gambit is a Trigger + Reply or Reply Set - We define a Reply as a subDocument in Mongo. **/ // var regexreply = require("../parse/regexreply"); module.exports = function (mongoose, facts) { var Utils = require("../utils"); var regexreply = require("../parse/regexreply"); var debug = require("debug")("Gambit"); var norm = require("node-normalizer"); var findOrCreate = require("<API key>"); var gNormalizer; norm.loadData(function () { gNormalizer = norm; debug("Normaizer Loaded."); }); /** I trigger is the matching rule behind a piece of input. It lives in a topic or several topics. A trigger also contains one or more replies. **/ var gambitSchema = new mongoose.Schema({ id: {type: String, index: true, default: Utils.genId()}, // This is the input string that generates a rule, // In the event we want to export this, we will use this value. // Make this filed conditionally required if trigger is supplied input: {type: String}, // The Trigger is a partly baked regex. trigger: {type: String, index: true}, // If the trigger is a Question Match isQuestion: {type: Boolean, default: false}, // If the trigger is a Answer Type Match qType: {type: String, default: ""}, qSubType: {type: String, default: ""}, // The filter function for the the expression filter: {type: String, default: ""}, // An array of replies. replies: [{ type: String, ref: "Reply"}], // replies: [Reply.schema], // This will redirect anything that matches elsewhere. // If you want to have a conditional rediect use reply redirects // TODO, change the type to a ID and reference another gambit directly // this will save us a lookup down the road (and improve performace.) redirect: {type: String, default: ""} }); gambitSchema.pre("save", function (next) { var self = this; // FIXME: This only works when the replies are populated which is not always the case. // self.replies = _.uniq(self.replies, function(item, key, id) { // return item.id; // If input was supplied, we want to use it to generate the trigger if (self.input) { var input = gNormalizer.clean(self.input); // We want to convert the input into a trigger. regexreply.parse(Utils.quotemeta(input, true), facts, function (trigger) { self.trigger = trigger; next(); }); } else { // Otherwise we populate the trigger normally next(); } }); gambitSchema.methods.addReply = function (replyData, callback) { var self = this; if (!replyData) { return callback("No data"); } var reply = new Reply(replyData); reply.save(function (err) { if (err) { return callback(err); } self.replies.addToSet(reply._id); self.save(function (err2) { callback(err2, reply); }); }); }; // TODO - Test against Qtypes too. gambitSchema.methods.doesMatch = function (message, cb) { var self = this; var match = false; regexreply.postParse(this.trigger, message, null, function (regexp) { var compiledRE = new RegExp("^" + regexp + "$", "i"); debug("clean'" + message.clean + "' against " + self.trigger + " (" + regexp + ")"); debug("lemma'" + message.lemString + "' against " + self.trigger + " (" + regexp + ")"); match = message.clean.match(compiledRE); if (!match) { match = message.lemString.match(compiledRE); } cb(null, match); }); }; gambitSchema.plugin(findOrCreate); try { return mongoose.model("Gambit", gambitSchema); } catch(e) { return mongoose.model("Gambit"); } };
title: order: 3 Facet G2 View View View G2 typescript const chart = new Chart({ container: '#container', }); chart.facet(facatType, { facetConfig, }); G2 - rect - list - matrix - circle - tree [](../../api/general/facet) > G2 1. View 1. 1. ## View View view G2 View view View region typescript type Point = { readonly x: number; readonly y: number; }; type Region = { readonly start: Point; readonly end: Point; }; startend x y 0 ~ 1 view view typescript const region = { start: { x: 0, y: 0 }, end: { x: 1, y: 0.5 }, }; view region view G2 typescript import { registerFacet, Facet } from '@antv/g2'; class MyFacet extends Facet { // TODO } registerFacet('my-facet', Facet); const chart = new Chart({ }); chart.facet('my-facet', { /* facetConfig */ }); > `MyFacet` typescript import { Datum, Facet, FacetCfg, FacetData, View } from '@antv/g2'; interface MyFacetCfg extends FacetCfg { // TODO } interface MyFacetData extends FacetData { // TODO } class MyFacet extends Facet<MyFacetCfg, MyFacetData> { protected afterEachView(view: View, facet: MyFacetCfg) {} protected beforeEachView(view: View, facet: MyFacetCfg) {} protected generateFacets(data: Datum[]): MyFacetCfg[] { return []; } protected getXAxisOption(x: string, axes: any, option: object, facet: MyFacetCfg): object { return undefined; } protected getYAxisOption(y: string, axes: any, option: object, facet: MyFacetCfg): object { return undefined; } } 1. Facet MyFacetCfg MyFacetData 2. G2 FacetFacet 5 - beforeEachView - afterEachView - generateFacets - getXAxisOption - getYAxisOption 1. **beforeEachViewafterEachView** view G2 annotation 2. **generateFacets** generateFacets - data view - region View - rect index - rect field 3. **getXAxisOptiongetYAxisOption** view 3. G2 typescript import { registerFacet } from '@antv/g2'; registerFacet('my-facet', MyFacet); chart.facet('my-facet', MyFacetCfg); G2 [rect ](https://github.com/antvis/G2/blob/master/src/facet/rect.ts)
<API key> ===================== ##Description The <API key> allows you to integrate a sliding panel mechanism in your projects ![ScreenShot](https://raw.github.com/PlayAdz/<API key>/master/Assets/<API key>.gif) ##Screenshots ![ScreenShot](https: ##Installation There are two ways to use the library in your project: 1) Manually add the library files to your project - <API key>.h - <API key>.m - PZSideMenuProtocol.h 2) Using CocoaPods Ruby pod '<API key>' ##Usage Create a side menu view controller and give it at least the center view controller // Prepare side menu view controller <API key> = [[<API key> alloc] <API key>:[[HomeViewController alloc] init]]; You can, at any moment give the side menu view controller a left and/or a right side view controller: <API key>.leftViewController = [[<API key> alloc] init]; <API key>.rightViewController = [[<API key> alloc] init]; Left and right pan gestures are automatically added to your view controllers, but you can open / close the side menu view controller programatically with the three following methods: // Open / Close side view controllers - (void)<API key>:(BOOL)animated completion:(void(^)(void))completionBlock; - (void)<API key>:(BOOL)animated completion:(void(^)(void))completionBlock; - (void)<API key>:(BOOL)animated completion:(void(^)(void))completionBlock; ##Options // Animation variables @property (nonatomic, assign) CGFloat zoomScale; @property (nonatomic, assign) UIOffset edgeOffset; @property (nonatomic, assign) CGFloat duration; // Shadow variables @property (nonatomic, strong) UIColor *shadowColor; @property (nonatomic, assign) CGFloat shadowOpacity; @property (nonatomic, assign) CGFloat shadowRadius; ##Tests - Works fine with iOS7 on iPhone 3.5" and 4" - Not tested on iPad ##Contribute The component has been developed for a single project, feel free to contribute to improve it.
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = <API key>(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = <API key>(_reactIconBase); function <API key>(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TiSocialFacebook = function TiSocialFacebook(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm21.7 16.7h5v5h-5v11.6h-5v-11.6h-5v-5h5v-2.1c0-2 0.6-4.5 1.8-5.9 1.3-1.3 2.8-2 4.7-2h3.5v5h-3.5c-0.9 0-1.5 0.6-1.5 1.5v3.5z' }) ) ); }; exports.default = TiSocialFacebook; module.exports = exports['default'];
import json import numpy as np import matplotlib.pyplot as plt file = raw_input('File to read: ') sn = file.split('.')[0] f = open(file,'r') data=json.load(f) f.close() lc = [] for i in data[sn]['photometry']: try: time = i['time'] mag = i['magnitude'] try: err = i['e_magnitude'] except: err = 'nan' band = i['band'] lc.append(np.array([time,mag,err,band])) except: pass lc = np.array(lc) filters = np.unique(lc[:,3]) filters = filters.tolist() filtNames = '' for i in filters: filtNames += '\t'+i+'\terr' dates = np.unique(lc[:,0]) tab = np.empty((len(dates),2*len(filters)+1)) tab.fill(np.nan) tab[:,0] = dates for i in tab: for j in range(len(lc[:,0])): if float(lc[j,0])==i[0]: i[2*(filters.index(lc[j,3]))+1] = lc[j,1] i[2*(filters.index(lc[j,3]))+2] = lc[j,2] lc_file = open(sn+'_lc.txt','w') lc_file.write('#Time'+filtNames+'\n') np.savetxt(lc_file,tab,fmt='%.2f',delimiter='\t') lc_file.close() plt.figure(1) plt.clf() for i in range(len(filters)): plt.errorbar(tab[:,0],tab[:,2*i+1],fmt='o',label=filters[i]) plt.legend() plt.gca().invert_yaxis() plt.show()
local diff = require('<API key>') describe('<API key>', function() describe('square_of_sums', function() it('should square the sum of the numbers up to the given number', function() assert.equal(225, diff.square_of_sums(5)) assert.equal(3025, diff.square_of_sums(10)) assert.equal(25502500, diff.square_of_sums(100)) end) end) describe('sum_of_squares', function() it('should sum the squares of the numbers up to the given number', function() assert.equal(55, diff.sum_of_squares(5)) assert.equal(385, diff.sum_of_squares(10)) assert.equal(338350, diff.sum_of_squares(100)) end) end) describe('<API key>', function() it('should subtract sum of squares from square of sums', function() assert.equal(0, diff.<API key>(0)) assert.equal(170, diff.<API key>(5)) assert.equal(2640, diff.<API key>(10)) assert.equal(25164150, diff.<API key>(100)) end) end) end)
require("./core"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; var builtin = types.builtInTypes; var isBoolean = builtin.boolean; var isObject = builtin.object; var isString = builtin.string; var defaults = require("../lib/shared").defaults; def("Function").field("generator", isBoolean, defaults["false"]).field("expression", isBoolean, defaults["false"]).field("defaults", [or(def("Expression"), null)], defaults.emptyArray).field("rest", or(def("Identifier"), null), defaults["null"]); def("FunctionDeclaration").build("id", "params", "body", "generator", "expression"); def("FunctionExpression").build("id", "params", "body", "generator", "expression"); def("<API key>").bases("Function", "Expression").build("params", "body", "expression").field("id", null, defaults["null"]).field("generator", false, defaults["false"]); def("YieldExpression").bases("Expression").build("argument", "delegate").field("argument", or(def("Expression"), null)).field("delegate", isBoolean, defaults["false"]); def("GeneratorExpression").bases("Expression").build("body", "blocks", "filter").field("body", def("Expression")).field("blocks", [def("ComprehensionBlock")]).field("filter", or(def("Expression"), null)); def("<API key>").bases("Expression").build("body", "blocks", "filter").field("body", def("Expression")).field("blocks", [def("ComprehensionBlock")]).field("filter", or(def("Expression"), null)); def("ComprehensionBlock").bases("Node").build("left", "right", "each").field("left", def("Pattern")).field("right", def("Expression")).field("each", isBoolean); def("ModuleSpecifier").bases("Literal").build("value").field("value", isString); def("Property").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("method", isBoolean, defaults["false"]).field("shorthand", isBoolean, defaults["false"]).field("computed", isBoolean, defaults["false"]); def("PropertyPattern").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("computed", isBoolean, defaults["false"]); def("MethodDefinition").bases("Declaration").build("kind", "key", "value").field("kind", or("init", "get", "set", "")).field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("value", def("Function")).field("computed", isBoolean, defaults["false"]); def("SpreadElement").bases("Node").build("argument").field("argument", def("Expression")); def("ArrayExpression").field("elements", [or(def("Expression"), def("SpreadElement"), null)]); def("NewExpression").field("arguments", [or(def("Expression"), def("SpreadElement"))]); def("CallExpression").field("arguments", [or(def("Expression"), def("SpreadElement"))]); def("<API key>").bases("Pattern").build("argument").field("argument", def("Pattern")); def("ArrayPattern").field("elements", [or(def("Pattern"), null, def("SpreadElement"))]); var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("<API key>"), def("ClassProperty")); def("ClassProperty").bases("Declaration").build("key").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("computed", isBoolean, defaults["false"]); def("<API key>").bases("Declaration").build("definition").field("definition", ClassBodyElement); def("ClassBody").bases("Declaration").build("body").field("body", [ClassBodyElement]); def("ClassDeclaration").bases("Declaration").build("id", "body", "superClass").field("id", def("Identifier")).field("body", def("ClassBody")).field("superClass", or(def("Expression"), null), defaults["null"]); def("ClassExpression").bases("Expression").build("id", "body", "superClass").field("id", or(def("Identifier"), null), defaults["null"]).field("body", def("ClassBody")).field("superClass", or(def("Expression"), null), defaults["null"]).field("implements", [def("ClassImplements")], defaults.emptyArray); def("ClassImplements").bases("Node").build("id").field("id", def("Identifier")).field("superClass", or(def("Expression"), null), defaults["null"]); def("Specifier").bases("Node"); def("NamedSpecifier").bases("Specifier").field("id", def("Identifier")).field("name", or(def("Identifier"), null), defaults["null"]); def("ExportSpecifier").bases("NamedSpecifier").build("id", "name"); def("<API key>").bases("Specifier").build(); def("ImportSpecifier").bases("NamedSpecifier").build("id", "name"); def("<API key>").bases("Specifier").build("id").field("id", def("Identifier")); def("<API key>").bases("Specifier").build("id").field("id", def("Identifier")); def("ExportDeclaration").bases("Declaration").build("default", "declaration", "specifiers", "source").field("default", isBoolean).field("declaration", or(def("Declaration"), def("Expression"), null)).field("specifiers", [or(def("ExportSpecifier"), def("<API key>"))], defaults.emptyArray).field("source", or(def("ModuleSpecifier"), null), defaults["null"]); def("ImportDeclaration").bases("Declaration").build("specifiers", "source").field("specifiers", [or(def("ImportSpecifier"), def("<API key>"), def("<API key>"))], defaults.emptyArray).field("source", def("ModuleSpecifier")); def("<API key>").bases("Expression").field("tag", def("Expression")).field("quasi", def("TemplateLiteral")); def("TemplateLiteral").bases("Expression").build("quasis", "expressions").field("quasis", [def("TemplateElement")]).field("expressions", [def("Expression")]); def("TemplateElement").bases("Node").build("value", "tail").field("value", { "cooked": isString, "raw": isString }).field("tail", isBoolean);
(function() { // The Fork Class // We'll have lots of forks. // Each fork will be on object of this // constructor. mit.Fork = function() { // Handle x/y this.x = 0; this.y = 0; this.w = 0; this.h = 0; // Head x/y this.head_x = 0; this.head_y = 0; // Head W/H this.head_w = 0; this.head_h = 0; // Edge on which the fork will stand on this.edge = 'btm'; // Get Handle Bounds this.getHandleBounds = function() { var b = {}; b.start_x = this.x; b.start_y = this.y; b.end_x = this.x + this.w; b.end_y = this.y + this.h; //console.log(bounds); return b; }; // Get Head Bounds this.getHeadBounds = function() { var b = {}; b.start_x = this.head_x; b.start_y = this.head_y; b.end_x = this.head_x + this.head_w; b.end_y = this.head_y + this.head_h; return b; }; }; // A ForkUtils class to help save the world mit.ForkUtils = { // Master array of all existing forks in memory forks: [], // Forks can be placed on top/bottom edges edges: ['top', 'btm'], // Images for fork handle, fork head and the digged part fork_img: {}, fork_head_img: {}, dig_img: {}, // How many forks to have in memory ? count: 6, init: function() { // Loading Images // Fork handle // this.fork_img = new Image(); // this.fork_img.src = 'img/fork_handle.png'; this.fork_img = mit.image.fork_handle; // Fork Head // this.fork_head_img = new Image(); // this.fork_head_img.src = 'img/fork_head.png'; this.fork_head_img = mit.image.fork_head; // Dig Image // this.dig_img = new Image(); // this.dig_img.src = 'img/dig.png'; }, /* How do we go about positioning forks exactly ? - Forks can appear on top or bottom edge. - Forks should vary in sizes, but should be mostly long to produce a harder gameplay. - Forks should appear at random distance. But there needs to be a range (or capping). - Every fork object should know what edge it is put on. This will help us calculate the exact height based on entire canvas height/width. This means, we only need the x/y position along with the edge, to put on the fork. */ /* This method will generate a random x/y position for the forks to start at. Based on the `fork.edge` we can draw the fork easily on the canvas edges. */ getRandomForkPos: function() { // We have access to `forks` here var pos = {}; if (this.forks[this.forks.length-1]) { pos.x = this.forks[this.forks.length-1].x; if (mit.score > 2500) pos.x += utils.randomNumber(300,600); else pos.x += utils.randomNumber(500,800); } else { pos.x = mit.W/1000 * 1050; } var branches = mit.BranchUtils.branches; /*var last_branch = [branches.length-1]; if (last_branch) { if (Math.abs(pos.x - last_branch.x) < 300) pos.x = last_branch.x + 300; }*/ if (branches.length) { branches.forEach(function(branch) { if (Math.abs(pos.x - branch.x) < 500) pos.x = branch.x + 500; }); } return pos; }, create: function() { var fork_img = this.fork_img, dig_img = this.dig_img, fork_head_img = this.fork_head_img, forks = this.forks, count = this.count; if (forks.length < count) { for (var i = 0; i < count - forks.length; i++) { var fork = new mit.Fork(); // Setting a Random Edge fork.edge = this.edges[utils.randomNumber(0,1)]; // Setting the Dig Position if (fork.edge === 'btm') { var dig_rand = utils.randomNumber(3,5); fork.dig_x = dig_img.width / dig_rand; fork.dig_y = mit.H - dig_img.height; // console.log(this.dig_img.width); fork.y = 200 + utils.randomNumber(0,100); fork.y += fork_head_img.height; } if (fork.edge === 'top') { fork.y = 0 - utils.randomNumber(0,100); fork.y -= fork_head_img.height; } var pos = this.getRandomForkPos(); fork.x = pos.x; // Height and Width fork.w = fork_img.width; fork.h = fork_img.height; forks.push(fork); } } }, draw: function(ctx) { var fork_img = this.fork_img, dig_img = this.dig_img, fork_head_img = this.fork_head_img, forks = this.forks, dead_forks = 0; this.create(); // Loop over forks and draw each of them forks.forEach(function(fork, index) { fork.x -= mit.Backgrounds.<API key>; if (fork.x + fork.w < 0) { ++dead_forks; return; } // Out of view port, no need to draw if (fork.x > mit.W) { // console.log('out of view port'); return; } if (fork.edge === 'top') { // ctx.lineTo(fork.x, 0); // Top forks need flippin ctx.save(); ctx.translate(fork.x, fork.y); ctx.translate(~~(fork_img.width/2), ~~(fork_img.height/2)); ctx.rotate( utils.toRadian(180) ); ctx.drawImage(fork_img, -~~(fork_img.width/2), -~~(fork_img.height/2)); ctx.restore(); fork.head_x = fork.x-~~(fork_head_img.width/8); fork.head_y = fork.y+fork_img.height; fork.head_w = fork_head_img.width; fork.head_h = fork_head_img.height; // Draw Fork Head ctx.save(); ctx.translate(fork.head_x, fork.head_y); ctx.translate(~~(fork_head_img.width/2), ~~(fork_head_img.height/2)); ctx.rotate( utils.toRadian(180) ); ctx.drawImage(fork_head_img, -~~(fork_head_img.width/2), -~~(fork_head_img.height/2)); ctx.restore(); } else if (fork.edge === 'btm') { ctx.drawImage(fork_img, fork.x, fork.y); fork.head_x = fork.x-~~(fork_head_img.width/5); fork.head_y = fork.y-fork_head_img.height; fork.head_w = fork_head_img.width; fork.head_h = fork_head_img.height; // Draw Fork Head ctx.save(); ctx.translate(fork.head_x, fork.head_y); ctx.translate(1* ~~(fork_head_img.width/2), 1* ~~(fork_head_img.height/2)); ctx.scale(-1,1); ctx.drawImage( fork_head_img, 1* -~~(fork_head_img.width/2), 1* -~~(fork_head_img.height/2) ); ctx.restore(); } }); if (dead_forks) { forks.splice(0, dead_forks); } return; }, // Forks have black digs in grounds // This function will draw those drawDigs: function(ctx) { // Loop over forks and draw digs for each of them var dig_img = this.dig_img; this.forks.forEach(function(fork, index) { if (fork.edge === 'btm') { ctx.drawImage(dig_img, fork.x - fork.dig_x, fork.dig_y); } }); }, // Check Fork Collision checkCollision: function() { var first_fork = this.forks[0]; // Useless optimization if (first_fork.x > mit.W/2) return; // Get Pappu Bounds var pappu_bounds = mit.Pappu.getBounds(), // Get Nearest Fork's Handle's Bounds fork_bounds = first_fork.getHandleBounds(); // Check whether pappu collided with the // fork handle or not. if (utils.intersect(pappu_bounds, fork_bounds)) { // console.log(pappu_bounds, fork_bounds); mit.gameOver(); } // We'll have to check for collision with fork heads. // If there's a collision pappu will be pushed! var fork_head_bounds = first_fork.getHeadBounds(); // Check whether pappu collided with the // fork head or not. With fork heads // collision detection checks would be // a little casual than super stern. // if (utils.intersect(pappu_bounds, fork_head_bounds)) { if ( pappu_bounds.end_x > fork_head_bounds.start_x+20 && fork_head_bounds.end_x-20 > pappu_bounds.start_x && pappu_bounds.end_y > fork_head_bounds.start_y+20 && fork_head_bounds.end_y-20 > pappu_bounds.start_y ) { mit.gameOver(); } } }; }());
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; class OptimizeCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'optimize'; /** * The console command description. * * @var string */ protected $description = 'Cache the framework bootstrap files'; /** * Execute the console command. * * @return void */ public function handle() { $this->call('config:cache'); $this->call('route:cache'); $this->call('view:cache'); $this->info('Files cached successfully!'); } }
import java.io.*; /** * Base64 implements Base64 encoding and Base 64 decoding. * */ public class Base64 implements Serializable { private static byte[] Base64EncMap, Base64DecMap; static { // rfc-2045: Base64 Alphabet byte[] map = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; Base64EncMap = map; Base64DecMap = new byte[128]; for (int idx = 0; idx < Base64EncMap.length; idx++) Base64DecMap[Base64EncMap[idx]] = (byte) idx; } /** * constructor * */ public Base64 () { } /** * This method decodes the given byte[] using the base64-encoding * specified in RFC-2045 (Section 6.8). * * @param data the base64-encoded data. * @return the decoded data. */ public final static byte[] base64Decode(byte[] data) { if (data == null) return null; int tail = data.length; while (data[tail-1] == '=') tail byte dest[] = new byte[tail - data.length/4]; // ascii printable to 0-63 conversion for (int idx = 0; idx <data.length; idx++) data[idx] = Base64DecMap[data[idx]]; // 4-byte to 3-byte conversion int sidx, didx; for (sidx = 0, didx=0; didx < dest.length-2; sidx += 4, didx += 3) { dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 003) ); dest[didx+1] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) ); dest[didx+2] = (byte) ( ((data[sidx+2] << 6) & 255) | (data[sidx+3] & 077) ); } if (didx < dest.length) dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 003) ); if (++didx < dest.length) dest[didx] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) ); return dest; } /** * This method decodes the given string using the base64-encoding * specified in RFC-2045 (Section 6.8). * * @param str the base64-encoded string. * @return the decoded str. */ public final static String base64Decode(String str) { if (str == null) return null; byte data[] = new byte[str.length()]; data = str.getBytes(); return new String(base64Decode(data)); } /** * This method encodes the given byte[] using the base64-encoding * specified in RFC-2045 (Section 6.8). * * @param data the data * @return the base64-encoded data */ public final static byte[] base64Encode(byte[] data) { if (data == null) return null; int sidx, didx; byte dest[] = new byte[((data.length+2)/3)*4]; // 3-byte to 4-byte conversion + 0-63 to ascii printable conversion for (sidx=0, didx=0; sidx < data.length-2; sidx += 3) { dest[didx++] = Base64EncMap[(data[sidx] >>> 2) & 077]; dest[didx++] = Base64EncMap[(data[sidx+1] >>> 4) & 017 | (data[sidx] << 4) & 077]; dest[didx++] = Base64EncMap[(data[sidx+2] >>> 6) & 003 | (data[sidx+1] << 2) & 077]; dest[didx++] = Base64EncMap[data[sidx+2] & 077]; } if (sidx < data.length) { dest[didx++] = Base64EncMap[(data[sidx] >>> 2) & 077]; if (sidx < data.length-1) { dest[didx++] = Base64EncMap[(data[sidx+1] >>> 4) & 017 | (data[sidx] << 4) & 077]; dest[didx++] = Base64EncMap[(data[sidx+1] << 2) & 077]; } else dest[didx++] = Base64EncMap[(data[sidx] << 4) & 077]; } // add padding for ( ; didx < dest.length; didx++) dest[didx] = (byte) '='; return dest; } /** * This method encodes the given string using the base64-encoding * specified in RFC-2045 (Section 6.8). * * @param str the string * @return the base64-encoded str */ public final static String base64Encode(String str) { if (str == null) return null; byte data[] = new byte[str.length()]; data = str.getBytes(); return new String(base64Encode(data)); } public static void main(String[] args) { System.out.println("This is not an executable application and is for reference only. Please view source code for Base64 encoding and decoding."); } }
; (function() { /** * Namespace for all Svidget library classes. * @namspace */ var Svidget = {}; Svidget.emptyArray = []; Svidget.root = window; // note: this may be different for node.js Svidget.version = "0.1.1"; Svidget.declaredHandlerName = "_declared"; /** @function Svidget.array Builds an array from any collection, be it another array, HTMLCollection, etc. */ Svidget.array = function(anyCollection) { // oops, we need a collection with a length property if (!anyCollection || !anyCollection.length) return null; try { // this may blow up for IE8 and below and other less than modern browsers return Svidget.emptyArray.slice.call(anyCollection, 0); } catch (e) { // iterate the old fashioned way and push items onto array var res = []; for (var i = 0; i < anyCollection.length; i++) { res.push(anyCollection[i]); } return res; } }; /** @function Svidget.isArray Determines if passed in object is actually an array. This is a more relaxed check and handles the case when array is a Svidget.Collection and/or across frame boundaries */ Svidget.isArray = function(array) { return array != null && (Array.isArray(array) || Array.prototype.isPrototypeOf(array) || array.length && array.push); }; Svidget.isFunction = function(func) { return typeof func === "function"; }; Svidget.isColor = function(color) { // todo return false; }; Svidget.extend = function(objtype, prototype, overwrite) { for (var methodName in prototype) { // do we check for hasOwnProperty here? if (overwrite || objtype.prototype[methodName] === undefined) { objtype.prototype[methodName] = prototype[methodName]; } } }; Svidget.wrap = function(func, context) { // todo: use function.bind() if available // ensure func is function, return undefined if not if (func == null || typeof func !== "function") return undefined; // return a wrapper function var p = function() { return func.apply(context, arguments); }; return p; }; // Find the function by name in the specified scope, or just return it if is already a function // By default scope == global scope Svidget.findFunction = function(funcNameOrInstance, scope) { if (typeof funcNameOrInstance === "function") { return funcNameOrInstance; } if (scope == null) scope = Svidget.root; // global scope if (funcNameOrInstance != null) { var bind = funcNameOrInstance + ""; //coerce to string var func = scope[bind]; if (func == null) return null; if (typeof func === "function") return func; // bind is an expression, so just wrap it in a function if (bind.substr(0, 7) != "return ") return new Function("return " + bind); else return new Function(bind); } return null; }; Svidget.log = function(msg) { if (!Svidget.Settings.enableLogging) return; console.log(msg); }; Svidget.readOnlyProperty = function(value) { return { enumerable: true, configurable: false, writable: false, value: value }; }; Svidget.fixedProperty = function(value) { return { enumerable: true, configurable: false, writable: true, value: value }; }; Svidget.getPrivateAccessor = function(privates) { return function(p) { return privates[p]; }; }; Svidget.setPrivateAccessor = function(privates) { return function(p, val) { if (!privates.writable.contains(p)) return false; privates[p] = val; return true; }; }; Svidget.returnFalse = function() { return false; }; Svidget.returnTrue = function() { return true; }; Svidget.Settings = {}; Svidget.Settings.showPrivates = true; //show private members of objects, useful for debugging Svidget.Settings.enableLogging = false; // whether console.logging is enabled, turn on for troubleshooting if (!Array.prototype.contains) { Array.prototype.contains = function(obj) { var i = this.length; while (i if (this[i] === obj) { return true; } } return false; }; } // a note about "bla instanceof Array" checks, they don't work across frame boundaries // so we use isArray if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === "[object Array]"; }; } /** * Encapsulates common functionality for all object types in the framework. * @class * @static * @memberof Svidget */ Svidget.ObjectPrototype = { // protected setup: function(privates) { this.getPrivate = Svidget.getPrivateAccessor(privates); this.setPrivate = Svidget.setPrivateAccessor(privates); if (Svidget.Settings.showPrivates) this.privates = privates; }, // protected getset: function(prop, val, validator) { // ** get mode var curProp = this.getPrivate(prop); if (val === undefined) return curProp; // ** set mode if (validator && !validator(val)) return false; // throw error? var oldProp = curProp; var success = this.setPrivate(prop, val); return success; }, // protected // should always return a collection select: function(col, selector) { if (typeof selector === "number") { selector = parseInt(selector); // coerce to integer return col.wrap(col.getByIndex(selector)); } if (selector !== undefined) return col.wrap(col.getByName(selector + "")); // todo: should we clone collection? return col; }, // protected // should always return a single item selectFirst: function(col, selector) { if (typeof selector === "number") { selector = parseInt(selector); // coerce to integer return col.getByIndex(selector); } if (selector !== undefined) return col.getByName(selector + ""); return col.first(); }, // protected <API key>: function(col, addFunc, removeFunc) { if (col == null) return; col.onAdded(Svidget.wrap(addFunc, this)); col.onRemoved(Svidget.wrap(removeFunc, this)); } }; /** * Encapsulates a set of prototype methods for managing events. * @class * @memberof Svidget * @param {array} typelist - A list of event types. */ Svidget.EventPrototype = function(typelist) { // todo: validate typelist // these are the event types that the base object supports, like "invoke" for action. this.eventTypes = new Svidget.Collection(typelist); }; Svidget.EventPrototype.prototype = { on: function(type, data, name, handler) { // resolve handler from whether name, data passed handler = handler || (Svidget.isFunction(name) ? name : Svidget.isFunction(data) ? data : null); data = arguments.length > 2 ? data : null; name = name !== undefined && handler !== name ? name : null; return this.addHandler(type, handler, name, data); }, off: function(type, handlerOrName) { // separate handlerOrName into handler, name var handler = Svidget.isFunction(handlerOrName) ? handlerOrName : null; var name = handler != null ? null : handlerOrName; return this.removeHandler(type, handler, name); }, trigger: function(type, value, originalTarget) { if (type == null) return; // nothing to do // get event object from handlers var e = this.triggerHandlers(type, value, originalTarget); Svidget.log("trigger: " + type); // if not stopPropagation call bubble if (!e.<API key>()) { this.bubble(type, e); } }, triggerHandlers: function(type, value, originalTarget) { // generate event object var e = new Svidget.Event(null, type, null, this.getTarget(), originalTarget, value); if (type == null || this.handlers == null || this.handlers[type] == null) return e; // nothing to do var handlers = this.handlers[type]; // loop through each handler (make sure it is a function) // h == { handler: handler, name: name, data: data } handlers.each(function(h) { if (e.<API key>()) return false; // if <API key>, then exit loop by returning false if (h == null || h.handler == null || typeof h.handler !== "function") return; // handler is not a function // set name/data e.name = h.name; e.data = h.data; // invoke handler h.handler.call(null, e); }); return e; }, bubble: function(type, sourceEvent) { // invoked from child this.ensureBubbleParents(); sourceEvent.name = null; sourceEvent.data = null; if (this.bubbleParents[type]) this.bubbleParents[type](type, sourceEvent, this.getTarget()); }, addHandler: function(type, handler, name, data) { this.<API key>(type); // todo: get handler function name, we will use to off() handlers by name //if (this.handlers[type].contains(handler)) return false; if (this.handlerExists(type, handler, name)) return false; var obj = this.toHandlerObject(handler, name, data); this.handlers[type].push(obj); return true; }, removeHandler: function(type, handler, name) { this.ensureHandlers(); if (!this.handlers[type]) return false; //return this.handlers[type].removeAll(handler); var that = this; return this.handlers[type].removeWhere(function(item) { return that.handlerMatch(item, handler, name); }); }, handlerExists: function(type, handler, name) { var that = this; var any = this.handlers[type].any(function(item) { return that.handlerMatch(item, handler, name); }); return any; }, handlerMatch: function(handlerObj, handler, name) { if (name != null && handlerObj.name === name) return true; if (handler === handlerObj.handler) return true; return false; }, setBubbleParent: function(type, callback) { this.ensureBubbleParents(); this.bubbleParents[type] = callback; }, // private, called by the object to register a single callback for all its event types // bubbleTarget: usually a parent object <API key>: function(types, bubbleTarget, callback) { if (bubbleTarget && callback) { for (var i = 0; i < types.length; i++) { this.setBubbleParent(types[i], Svidget.wrap(callback, bubbleTarget)); } } }, toHandlerObject: function(handler, name, data) { var handlerFunc = typeof handler !== "function" ? null : handlerFunc; var res = { handler: handler, name: name, data: data }; return res; }, bubbleFuncs: function(objectType) {}, ensureHandlers: function() { if (!this.handlers) this.handlers = {}; }, <API key>: function(type) { this.ensureHandlers(); if (!this.handlers[type]) { this.handlers[type] = new Svidget.Collection(); } }, ensureBubbleParents: function() { if (!this.bubbleParents) this.bubbleParents = {}; }, // internal // returns the target object to use for the event object // override in eventContainer getTarget: function() { return this; } }; /** * Encapsulates common functionality for a Param and ActionParam. * @class * @abstract * @memberof Svidget */ Svidget.ParamPrototype = { /** * Gets the param name. * @method * @returns {string} */ name: function() { var res = this.getPrivate("name"); return res; }, /** * Gets or sets the description. * @method * @param {string} [val] - Sets the value when specified. * @returns {string} - The value for a get, or true/false if succeeded or failed for a set. */ description: function(val) { var res = this.getset("description", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event if (this.trigger) this.trigger("change", { property: "description", value: val }); return true; }, /** * Gets or sets the param type. This can be "string", "number", etc. See the Svidget.ParamTypes enum. * @method * @param {string} [val] - Sets the value when specified. * @returns {string} - The value for a get, or true/false if succeeded or failed for a set. */ type: function(val) { var res = this.getset("type", val, this.validateType); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event if (this.trigger) this.trigger("change", { property: "type", value: val }); return true; }, /** * Gets or sets the param subtype. This can be on of the values from the Svidget.ParamSubTypes enum. * @method * @param {string} [val] - Sets the value when specified. * @returns {string} - The value for a get, or true/false if succeeded or failed for a set. */ subtype: function(val) { var res = this.getset("subtype", val, this.validateSubtype); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event if (this.trigger) this.trigger("change", { property: "subtype", value: val }); return true; }, /** * Gets or sets the param defvalue. This is the default value if nothing (or undefined) is set. * @method * @param {string} [val] - Sets the value when specified. * @returns {string} - The value for a get, or true/false if succeeded or failed for a set. */ defvalue: function(val) { var res = this.getset("defvalue", val, this.validateSubtype); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "change" event if (this.trigger) this.trigger("change", { property: "defvalue", value: val }); return true; }, validateType: function(t) { if (!typeof t === "string") return false; return Svidget.ParamTypes[t] != undefined; }, validateSubtype: function(t) { if (!typeof t === "string") return false; return Svidget.ParamSubTypes[t] != undefined; } }; /** * Represents a structured collection. Extends array by providing additional methods to select, tranverse, and modify an array.s * @constructor * @augments Array * @param {Array} array - The initial elements of the collection. */ Svidget.Collection = function(array) { this.__type = "Svidget.Collection"; this.source = array; //this.baseType = Svidget.Collection; // this.items = []; // append items from source to this instance if (array && (Svidget.isArray(array) || Array.prototype.isPrototypeOf(array))) { this.push.apply(this, array); } }; Svidget.Collection.prototype = new Array(); Svidget.extend(Svidget.Collection, { /** * Returns true if any of the items satisfies the specified predicate function. * @method * @param {Function} predicate - A function that accepts an item as input and returns true/false. * @returns {boolean} */ any: function(predicate) { if (predicate == null) return this.length > 0; for (var i = 0; i < this.length; i++) { if (predicate(this[i])) return true; } return false; }, /** * Returns true if all of the items satisfies the specified predicate function. * @method * @param {Function} predicate - A function that accepts an item as input and returns true/false. * @returns {boolean} */ all: function(predicate) { if (predicate == null) return false; for (var i = 0; i < this.length; i++) { if (!predicate(this[i])) return false; } return true; }, /** * Returns true if the item is contained in the collection. * @method * @param {object} obj - The object to look for. * @returns {boolean} */ contains: function(obj) { return this.indexOf(obj) >= 0; }, /** * Iterates on each item in the collection and performs the operation. * @method * @param {Function} operation - A function that accepts an item as input. */ each: function(operation) { for (var i = 0; i < this.length; i++) { var res = operation(this[i]); if (res === false) break; } }, /** * Returns the first item in the collection that satisfies the condition in the specified predicate function. * @method * @param {Function} predicate - A function that accepts an item as input and returns true/false. * @returns {object} - The item in the collection. */ first: function(predicate) { if (this.length == 0) return null; if (predicate == null || !typeof predicate === "function") return this[0]; for (var i = 0; i < this.length; i++) { if (predicate(this[i])) return this[i]; } return null; }, /** * Returns the last item in the collection that satisfies the condition in the specified predicate function. * @method * @param {Function} predicate - A function that accepts an item as input and returns true/false. * @returns {object} - The item in the collection. */ last: function(predicate) { if (this.length == 0) return null; if (predicate == null || !typeof predicate === "function") return this[0]; for (var i = this.length - 1; i >= 0; i if (predicate(this[i])) return this[i]; } return null; }, /** * Iterates on the collection calling the specified selector function and returns a new collection. Chainable. * @method * @param {Function} selector - A function that accepts an item as input and returns a value based on it. * @returns {Svidget.Collection} - The result collection. */ select: function(selector) { var result = []; for (var i = 0; i < this.length; i++) { result.push(selector(this[i])); } return new Svidget.Collection(result); }, /** * Iterates on the collection calling the specified predicate filter function and returns a new collection. Chainable. * @method * @param {Function} predicate - A function that accepts an item as input and returns true/false. * @returns {Svidget.Collection} - The result collection. */ where: function(predicate) { var result = []; for (var i = 0; i < this.length; i++) { if (predicate(this[i])) result.push(this[i]); } return new Svidget.Collection(result); }, // modifiers /** * Adds an item to the collection. * @method * @param {object} obj - The item to add. * @returns {boolean} - True if add succeeds. */ add: function(obj) { var pos = this.indexOf(obj); if (pos >= 0) return false; this.push(obj); return true; }, /** * Adds an array of items to the collection. * @method * @param {Array} array - The items to add. * @returns {boolean} - True if add succeeds. */ addRange: function(array) { if (!Svidget.isArray(array)) return false; this.push.apply(this, array); return true; }, /** * Inserts an item to the collection at the specified index. * @method * @param {object} obj - The item to add. * @param {number} index - The items to add. * @returns {boolean} - True if add succeeds. */ insert: function(obj, index) { index = parseInt(index); if (!isNaN(index) && (index < 0 || index > this.length)) return false; this.splice(index, 0, obj); return true; }, /** * Removes an item from the collection. Only removes the first instance of the item found. * @method * @param {object} obj - The item to remove. * @returns {boolean} - True if remove succeeds. */ remove: function(obj) { var pos = this.indexOf(obj); if (pos < 0) return false; this.splice(pos, 1); return true; }, /** * Removes an item from the collection. Removes all instances of the item. * @method * @param {object} obj - The item to remove. * @returns {boolean} - True if remove succeeds. */ removeAll: function(obj) { var removed = false; while (this.remove(obj)) { removed = true; } return removed; }, /** * Removes an item from the collection based on the specified predicate function. * @method * @param {Function} predicate - A function that accepts an item as input and returns true/false. * @returns {boolean} - True if remove succeeds. */ removeWhere: function(predicate) { var result = []; var removed = false; for (var i = 0; i < this.length; i++) { if (predicate(this[i])) result.push(this[i]); } for (var i = 0; i < result.length; i++) { removed = this.remove(result) || removed; } return removed; }, // misc /** * Returns a new array based on items in the collection. * @method * @returns {Array} */ toArray: function() { var arr = []; for (var i = 0; i < this.length; i++) { arr.push(this[i]); } //var check = arr instanceof Array; //Svidget.log('is it array: ' + check); return arr; } }); /** * Represents a specialized collection for framework objects. * @constructor * @mixes Svidget.ObjectPrototype * @augments Svidget.Collection * @param {Array} array - The initial elements of the collection. * @param {Function} type - The type of objects that the collection should hold. */ Svidget.ObjectCollection = function(array, type) { // todo: filter input array by type specified Svidget.Collection.apply(this, [ array ]); this.__type = "Svidget.ObjectCollection"; // private fields var privates = new function() { this.writable = [ "addedFunc", "removedFunc" ]; this.type = type; this.addedFunc = null; this.removedFunc = null; }(); // private accessors this.setup(privates); }; var base = new Svidget.Collection(); Svidget.ObjectCollection.prototype = base; Svidget.ObjectCollection.prototype.base_add = base.add; Svidget.ObjectCollection.prototype.base_remove = base.remove; Svidget.extend(Svidget.ObjectCollection, { /** * Gets an item in the collection by its index (if number passed) or id/name (if string passed). * @method * @param {(string|number)} selector - The selector. * @returns {object} - The object in the collection. */ get: function(selector) { if (typeof selector === "number") return col.getByIndex(selector); return col.getByName(selector); }, /** * Gets an item in the collection by its index. * @method * @param {number} selector - The index. * @returns {object} - The object in the collection. */ getByIndex: function(index) { if (index == null || isNaN(index)) return null; index = parseInt(index); return this[index]; }, /** * Gets an item in the collection by its name. * @method * @param {string} selector - The name. * @returns {object} - The object in the collection. */ getByName: function(name) { return this.first(function(p) { return p.name() == name; }); }, /** * Gets the object type that this collection holds. * @method * @returns {Function} - The type constructor that represents the type. */ type: function() { return this.getset("type"); }, /** * Adds an item to the collection. * @method * @param {object} obj - The item to add. * @returns {boolean} - The item that was added. */ add: function() { if (arguments.length == 0) return null; // call add overload var item; var arg0; var success; if (arguments.length >= 1) arg0 = arguments[0]; if (typeof arg0 === "string") { item = this.create.apply(this, arguments); } else { item = arg0; } if (item == null) return null; success = this.addObject(item); if (!success) return null; // if succeeded, notify widget this.triggerAdded(item); return item; }, addObject: function(obj) { // ensure obj is a valid Param if (obj == null || !obj instanceof this.type()) return false; // ensure no other parameter exists in the collection by that name if (obj.name !== undefined && this.getByName(obj.name()) != null) return false; // add to collection this.push(obj); return obj; }, /** * Creates an returns the item. * @abstract */ create: function() { // override me return null; }, // addCreate: function (name, value, options) { // // create param // // call addObject // // ensure no other parameter exists in the collection by that name // if (this.getByName(name) != null) return false; // // create obj // var obj = new Svidget.Param(name, value, options); // this.push(obj); // return true; /** * Removes an item from the collection. Only removes the first instance of the item found. * @method * @param {object} obj - The item to remove. * @returns {boolean} - True if remove succeeds. */ remove: function(name) { var item = this.getByName(name); if (item == null) return false; var success = this.base_remove(item); if (!success) return false; // if succeeded, notify widget this.triggerRemoved(item); return true; }, /** * Wraps the specified item in a new ObjectCollection. * @method * @param {object} item - The item to make a collection from. * @returns {Svidget.ObjectCollection} - The collection. */ wrap: function(item) { var items = [ item ]; if (item == null || !item instanceof this.type()) items = []; var col = new this.constructor(items, this.parent); return col; }, // internal // wires up an internal handler when an item is added to the collection onAdded: function(func) { this.getset("addedFunc", func); }, // internal // wires up an internal handler when an item is removed from the collection onRemoved: function(func) { this.getset("removedFunc", func); }, // private triggerAdded: function(item) { var func = this.getset("addedFunc"); if (func) func(item); }, // private triggerRemoved: function(item) { var func = this.getset("removedFunc"); if (func) func(item); } }, true); // overwrite base methods, copied above Svidget.extend(Svidget.Collection, Svidget.ObjectPrototype); /** * Provides communications functionality between a page and a widget. Internal class only. * @class */ Svidget.Communicator = function() { this.__type = "Svidget.Communicator"; this.sameDomain = null; this._init(); }; Svidget.Communicator.prototype = { _init: function() { this.addMessageEvent(); }, // REGION: Events addMessageEvent: function() { window.addEventListener("message", Svidget.wrap(this.receiveXSM, this), false); }, // REGION: Receive receiveFromParent: function(name, payload) { svidget.receiveFromParent(name, payload); }, receiveFromWidget: function(name, payload, widgetID) { svidget.receiveFromWidget(name, payload, widgetID); }, receiveXSM: function(message) { if (message == null) return; var msgData = message.data; if (msgData == null) return; // it's possible in future we'll have a nested widget scenario, so a widget can have both a parent and widgets. if (msgData.widget !== undefined) this.receiveFromWidget(msgData.name, msgData.payload, msgData.widget); else this.receiveFromParent(msgData.name, msgData.payload); }, // REGION: Signal Parent signalParent: function(name, payload, widgetID) { // todo: cache result of isParentSameDomain if (this.isParentSameDomain()) { this.signalParentDirect(name, payload, widgetID); } else { this.signalParentXSM(name, payload, widgetID); } }, signalParentDirect: function(name, payload, widgetID) { // note: if window.parent.svidget is null it means the widget DOM was ready before the page DOM, although unlikely it is possible // so we need to handle somehow if (window.parent != null && window !== window.parent && window.parent.svidget != null && window.parent.svidget) { var root = window.parent.svidget; setTimeout(function() { root.routeFromWidget(name, payload, widgetID); }, 0); } }, signalParentXSM: function(name, payload, widgetID) { if (window.parent != null) { //alert('postMessage'); var msg = this.<API key>(name, payload, widgetID); window.parent.postMessage(msg, "*"); } }, <API key>: function(name, payload, widgetID) { return { name: name, payload: payload, widget: widgetID }; }, // todo: move to widget // note: this returns true when widget is forced cross domain isParentSameDomain: function() { if (this.sameParentDomain == null) this.sameParentDomain = this.<API key>(); return this.sameParentDomain; }, // todo: move to Svidget.DOM <API key>: function() { try { var d = window.parent.document; return true; } catch (ex) { return false; } }, // REGION: Widgets signalWidget: function(widgetRef, name, payload) { Svidget.log("communicator: signalWidget {name: " + name + "}"); if (!widgetRef.isCrossDomain()) //this.isWidgetSameDomain(widgetProxy)) this.signalWidgetDirect(widgetRef, name, payload); else this.signalWidgetXSM(widgetRef, name, payload); }, signalWidgetDirect: function(widgetRef, name, payload) { if (widgetRef == null) return; var root = widgetRef.root(); if (root != null) { setTimeout(function() { root.receiveFromParent(name, payload); }, 0); } }, signalWidgetXSM: function(widgetRef, name, payload) { if (widgetRef != null && widgetRef.window() != null) { var msg = this.<API key>(name, payload); //widgetRef.window().postMessage(msg, '*'); setTimeout(function() { Svidget.log("communicator: postMessage"); widgetRef.window().postMessage(msg, "*"); }, 0); } }, <API key>: function(name, payload) { return { name: name, payload: payload }; } }; /** * A collection of methods for working with DOM elements. * @static * @memberof Svidget */ Svidget.DOM = { // REMARKS // Wrapper for getElementById get: function(sel) { return document.getElementById(sel); }, getByName: function(tagName, asCollection) { return this.getChildrenByName(document, tagName, asCollection); }, getByNameNS: function(namespace, tagName, asCollection) { var tags = document.<API key>(namespace, tagName); if (asCollection) { return new Svidget.Collection(Svidget.array(tags)); } return tags; }, // Gets elements by tag name belonging to the svidget namespace getByNameSvidget: function(tagName, asCollection) { return this.getByNameNS(Svidget.Namespaces.svidget, tagName, asCollection); }, getChildrenByName: function(source, tagName, asCollection) { var tags = source.<API key>(tagName); if (asCollection) { return new Svidget.Collection(Svidget.array(tags)); } return tags; }, // if sel is a string calls get() getElement: function(sel) { if (typeof sel == "string") return this.get(sel); else return sel; }, // gets an element by ID and returns a DomItem getItem: function(sel) { return this.wrap(this.get(sel)); }, // returns a DomQuery object select: function(sel) { // todo: support jQuery selector if querySelectorAll fails, it might be loaded on the page so we might as well use it if we can if (!document.querySelectorAll) return null; if (sel == null) return null; // new Svidget.DomQuery(); // use querySelectorAll var attrRX = /@[^= var hasAttr = attrRX.test(sel); var col = new Svidget.Collection(); var res; // if selector has an attribute in it, split it first by comma if (hasAttr) { var parts = sel.split(","); for (var i = 0; i < parts.length; i++) { res = selectSingle(parts[i]); if (res) col.addRange(res); } } else { res = selectSingle(sel); // its possible selector was bad, in which case we get null, so check if (res) col.addRange(res); } var query = new Svidget.DOMQuery(col, sel); return query; // given a selector string free from any commas, looks up the elements/attributes for it // and returns a collection. function selectSingle(s) { if (s == null) return null; var attrRXEnd = /@([^= var sel = s; var attrName; var match = attrRXEnd.exec(s); if (match) { attrName = match[1]; // match the subgroup sel = sel.replace(match[0], ""); } // query var eles; try { eles = document.querySelectorAll(sel); } catch (ex) { // seelctor was invalid, so just return null return null; } // build collection var col = []; for (var i = 0; i < eles.length; i++) { var ele = eles[i]; var item; if (attrName) { var attr = Svidget.DOM.attr(ele, attrName); if (attr != null) { item = new Svidget.DOMItem(attr); } } else { item = new Svidget.DOMItem(ele); } if (item) { col.push(item); } } return new Svidget.Collection(col); } }, // Returns the first DOM element in a query selectElement: function(sel) { if (typeof sel == "string") { var q = this.select(sel); if (q == null || q.length == 0) return null; return q.item(0).source(); } else if (this.isElement(sel)) return sel; else return null; }, // returns a DomItem if ele is a element or attribute object // else returns the original item wrap: function(ele) { return new Svidget.DOMItem(ele); }, // converts an HTML or SVG DOM node into a pure object literal used to transport transportize: function(ele) { return { name: ele.localName, namespace: ele.namespaceURI, value: ele.value, type: ele.nodeType == 1 ? Svidget.NodeType.element : ele.nodeType == 2 ? Svidget.NodeType.attribute : null }; }, // Elements root: function() { return document.documentElement; }, rootItem: function() { // should we cache? return this.wrap(this.root()); }, attr: function(ele, attrName) { return ele.attributes[attrName]; }, attrValue: function(ele, attrName) { var a = this.attr(ele, attrName); if (a) return a.value; return null; }, clone: function(item) {}, cloneDetached: function(item) {}, isDOMNode: function(source) { return source.namespaceURI && source.localName && source.nodeType && source.value && (source.nodeType == 1 || source.nodeType == 2); }, fromNodeType: function(type) { if (type == 1) return "element"; if (type == 2) return "attribute"; if (type == 3) return "text"; return null; }, // TEXT text: function(sel, text) { var obj = this.select(sel); if (text === undefined) return this.getText(obj); else this.setText(obj, text); }, getText: function(obj) { if (obj.textContent) return obj.textContent; else if (obj.innerHTML) return obj.innerHTML; else return null; }, setText: function(obj, text) { if (obj.textContent) obj.textContent = text + ""; else if (obj.innerHTML) obj.innerHTML = text + ""; }, // returns null - it means document hasn't loaded yet // returns undefined - it means document is loaded but not accessible due to security (cross domain) constraints getDocument: function(objOrWinEle) { try { var doc = objOrWinEle.contentDocument; // certain browsers (Chrome) returns a blank document instead of null if (doc != null && doc.URL == "about:blank") return null; return doc; } catch (ex) { return undefined; } }, // determines if document for <object> or <iframe> is loaded and ready <API key>: function(objOrWinEle) { return this.getDocument(objOrWinEle) !== null; }, isElement: function(ele) { return ele instanceof HTMLElement; }, // todo move to DomItem attach: function(containerEle, eles) {}, // detaches an element from the DOM // RETURNS // The elements that were detached detach: function(sel) {}, disable: function(ele) { ele.disabled = true; }, enable: function(ele) { ele.disabled = false; }, show: function(ele, val) { ele.style.display = "initial"; ele.style.visibility = "visible"; }, hide: function(ele, val) { ele.style.display = "none"; ele.style.visibility = "hidden"; }, // Note: todo: for on and off // wrap callback in compat layer with jQuery style event object // PARAMS // obj: object to attach listener to // name: type of event i.e. "click" // callback: function to call back // capture: whether in capture/bubble // RETURNS // true if successful // REMARKS // Note: this is for DOM events // todo: support for event delegation? on: function(obj, type, callback, capture) { capture = !!capture; // normalize to bool (default == false) var attached = false; if (obj.addEventListener) { // Supports DOM spec obj.addEventListener(type, callback, capture); attached = true; } else if (obj.attachEvent) { // IE8 and below obj.attachEvent("on" + type, callback); attached = true; } // obj doesn't support events return attached; }, off: function(obj, type, callback, capture) { capture = !!capture; // normalize to bool (default == false) var detached = false; if (obj.addEventListener) { obj.removeEventListener(type, callback, false); detached = true; } else if (document.attachEvent) { document.detachEvent("on" + type, callback); detached = true; } // obj doesn't support events return detached; } }; /** * Encapsulates a single DOM element or attribute. * @class * @param {object} source - A DOM element or attribute. Can be null */ Svidget.DOMItem = function(source) { this.__type = "Svidget.DOMItem"; source = source || {}; // default source to empty object // privates var privates = new function() { this.writable = [ "value" ]; this.type = null; this.name = null; this.value = null; this.namespace = null; this.source = source; this.sourceDOM = isSourceDOM(source); }(); // private accessors this.setup(privates); function isSourceDOM(source) { if (source == null) return false; return source.namespaceURI && source.localName && source.nodeType && (source.value || source.textContent) && (source.nodeType == 1 || source.nodeType == 2); } function getType(typeCode) { if (typeCode == Svidget.NodeType.element) return "element"; if (typeCode == Svidget.NodeType.attribute) return "attribute"; return null; } function getNamespaceType(namespace) { for (var n in Svidget.Namespaces) { if (namespace === Svidget.Namespaces[n]) return n; } } if (privates.sourceDOM) { privates.typeCode = source.nodeType == 1 ? Svidget.NodeType.element : source.nodeType == 2 ? Svidget.NodeType.attribute : null; privates.name = source.localName; privates.namespace = source.namespaceURI; } else { privates.typeCode = source.type; privates.name = source.name; privates.namespace = source.namespace; } privates.value = source.value || source.textContent; privates.type = getType(privates.typeCode); privates.namespaceType = getNamespaceType(privates.namespace); // build attributes this.cachedAttributes = null; // build child elements this.cachedElements = null; }; Svidget.DOMItem.prototype = { typeCode: function() { return this.getset("type"); }, // type: function () { // var type = this.typeCode(); // if (type == Svidget.NodeType.element) return "element"; // if (type == Svidget.NodeType.attribute) return "attribute"; // return null; /** * Gets the element or attribute name of the item. * @method * @returns {string} */ name: function() { return this.getset("name"); }, /** * Gets the element text content or the attribute value. * @method * @returns {string} */ value: function(val) { var source = this.source(); if (val === undefined) return source.value || source.textContent; var strval = val + ""; if (source.value) source.value = strval; else source.textContent = strval; }, /** * Gets the namespace URI for the element or attribute item. * @method * @returns {string} */ namespace: function() { return this.getset("namespace"); }, /** * Gets the namespace type i.e. html, svg, xlink, svidget, etc. * @method * @returns {string} */ namespaceType: function() { return this.getset("namespaceType"); }, // namespaceType: function () { // var ns = this.namespace(); // for (var n in Svidget.Namespaces) { /** * Gets whether the item has child elements. * @method * @returns {boolean} */ hasElements: function() { if (this.isAttribute()) return false; var source = this.source(); if (this.isAttached() || source.children && source.children.length) { return source.children.length > 0; } return false; }, /** * Gets whether the item has attributes. False when the item is an attribute. * @method * @returns {boolean} */ hasAttributes: function() { if (this.isAttribute()) return false; var source = this.source(); if (this.isAttached() || source.attributes && source.attributes.length) { return source.attributes.length > 0; } return false; }, /** * Gets whether the item is an attribute. * @method * @returns {boolean} */ isAttribute: function() { return this.type() == Svidget.NodeType.attribute; }, /** * Returns a collection of DOMItem objects representing child elements. Returns null if item is an attribute. * @method * @returns {Svidget.Collection} - the collection of DOMItems */ elements: function() { // lazy load if (this.cachedElements != null && Svidget.isArray(this.cachedElements)) return this.cachedElements; var isDOM = this.isAttached(); if (!isDOM && (!source.elements || !source.elements.length)) return null; var source = this.source(); var origcol = isDOM ? source.children : source.elements; var eles = new Svidget.Collection(Svidget.array(origcol)); eles = eles.select(function(e) { return new Svidget.DOMItem(e); }); this.cachedElements = eles; return this.cachedElements; }, /** * Returns a collection of DOMItem objects representing attributes. Returns null if item is an attribute. * @method * @returns {Svidget.Collection} - the collection of DOMItems */ attributes: function() { // lazy load if (this.cachedAttributes != null && Svidget.isArray(this.cachedAttributes)) return this.cachedAttributes; var isDOM = this.isAttached(); if (!isDOM && (!source.attributes || !source.attributes.length)) return null; var source = this.source(); var origcol = source.attributes; var attrs = new Svidget.Collection(Svidget.array(origcol)); attrs = attrs.select(function(a) { return new Svidget.DOMItem(a); }); this.cachedAttributes = attrs; return this.cachedAttributes; }, /** * Gets the underlying DOM object that this DOMItem instance wraps. * @method * @returns {(HTMLElement|HTMLAttribute)} - the underlying DOM object */ source: function() { return this.getset("source"); }, /** * Returns whether the DOMItem actually wraps an underlying DOM object. * @method * @returns {Svidget.Collection} - the collection of DOMItems */ isAttached: function() { return this.getset("sourceDOM"); } }; // future item: extend EventPrototype when adding events to DOMItem. Svidget.extend(Svidget.DOMItem, Svidget.ObjectPrototype); /** * Represents the result of a DOM query. Chainable. * @class * @param {Array} domItemCollection - An array or array-like collection of DOMItem objects. * @param {string} selector - The selector used to get the items for this query. */ Svidget.DOMQuery = function(domItemCollection, selector) { this.__type = "Svidget.DOMQuery"; var items = new Svidget.Collection(domItemCollection); // if domItemCollection not valid its ok, will just initialize an empty collection var privates = new function() { this.writable = []; this.items = items; this.selector = selector; }(); // private accessors this.getPrivate = Svidget.getPrivateAccessor(privates); this.setPrivate = Svidget.setPrivateAccessor(privates); // define length readonly property Object.defineProperty(this, "length", { enumerable: true, configurable: false, writable: false, value: items.length || 0 }); }; Svidget.DOMQuery.prototype = { /** * Gets the collection of items that are the result of the query. * @method * @returns {Svidget.Collection} */ items: function() { return this.getset("items"); }, /** * Gets the item in the collection at the specified index. * @method * @param {number} index - The index * @returns {Svidget.Collection} */ item: function(index) { var items = this.items(); if (items == null) return null; return items[index]; }, /** * Gets whether the collection has any items. * @method * @returns {boolean} */ hasItems: function() { //return this.items().length > 0; return this.length > 0; }, /** * Gets the selector string used for this query. * @method * @returns {string} */ selector: function() { return this.getset("selector"); }, /** * Sets the value of each item in the collection. * @method * @returns {string} */ setValue: function(val) { this.items().each(function(i) { i.value(val); }); }, /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.DOMQuery { selector: "' + this.selector() + '", items: ' + this.items().length + "}]"; } }; // note: down the road we may make this more like a jquery object Svidget.extend(Svidget.DOMQuery, Svidget.ObjectPrototype); // Enums /** * Represents the DOM document type. * @enum * @readonly */ Svidget.DocType = { html: 0, svg: 1 }; /** * Represents the ready state for a document. * @enum * @readonly */ Svidget.DocReadyState = { loading: 0, //'loading', interactive: 1, //'interactive', complete: 2 }; /** * Represents the ready state for an element. * @enum * @readonly */ Svidget.ElementReadyState = { uninitialized: 0, loading: 1, loaded: 2, interactive: 3, complete: 4 }; /** * Represents the core types for a Param object. * @enum * @readonly */ Svidget.ParamTypes = { object: 0, string: 1, number: 2, bool: 3 }; /** * Represents the core subtypes for a Param object. * @enum * @readonly */ Svidget.ParamSubTypes = { none: 0, color: 1, integer: 2, regex: 3 }; /** * Represents the item type for an xml node. * @enum * @readonly */ Svidget.NodeType = { element: 0, attribute: 1 }; /** * Represents xml namespaces used by this framework. * @enum * @readonly */ Svidget.Namespaces = { html: "http: // also used for HTML5 svidget: "http: svg: "http: xlink: "http: }; /** * Represents an event triggers by the framework. * @class * @param {string} name - The name of the event as specified when registering a handler. * @param {string} type - The type of the event, like "actioninvoke", "eventtrigger" etc. * @param {object} data - An arbitrary object passed in when registering a handler. * @param {object} target - The framework object that is the latest object to trigger the event, i.e. do to an event bubble. * @param {object} origTarget - The framework object that originally triggered the event. * @param {object} value - The value associated with the event. This is specific to the type of event that was triggered. */ Svidget.Event = function(name, type, data, target, origTarget, value) { /** * Gets the current object (param, action, etc) that currently triggered event (either original or current bubble target). */ Object.defineProperty(this, "currentTarget", Svidget.readOnlyProperty(target)); /** * Gets the data that was passed at bind time (writable). */ Object.defineProperty(this, "data", Svidget.fixedProperty(data)); /** * Gets the name of the handler specified at bind time (writable). */ Object.defineProperty(this, "name", Svidget.fixedProperty(name)); /** * Gets the date/time timestamp when the event was triggered. */ Object.defineProperty(this, "timeStamp", Svidget.readOnlyProperty(+new Date())); /** * Gets the object (param, action, etc) that triggered event. */ Object.defineProperty(this, "target", Svidget.readOnlyProperty(origTarget == null ? target : origTarget)); /** * Gets the event type i.e. "invoke", "change", "actioninvoke", "eventtrigger" etc */ Object.defineProperty(this, "type", Svidget.readOnlyProperty(type)); /** * Gets the value specified at trigger time. */ Object.defineProperty(this, "value", Svidget.readOnlyProperty(value)); }; Svidget.Event.prototype = { /** * Gets whether propagation was stopped on this event. When true this event will not bubble to parent. * @method * @returns {boolean} */ <API key>: Svidget.returnFalse, /** * Gets whether immediate propagation was stopped on this event. When true, no futher handlers will be invoked and this event will not bubble to parent. * @method * @returns {boolean} */ <API key>: Svidget.returnFalse, /** * Stops propagation for this event. * @method */ stopPropagation: function() { this.<API key> = Svidget.returnTrue; }, /** * Stops immediate propagation for this event. * @method */ <API key>: function() { this.<API key> = returnTrue; this.stopPropagation(); } }; /** * Implements EventPrototype as a standalone object. * @class * @param {Array} typelist - An array of types that this event container accepts. * @param {object} target - The object instantiating this object that will be specified as the target when triggered. */ Svidget.EventContainer = function(typelist, target) { this.__type = "Svidget.EventContainer"; Svidget.EventPrototype.apply(this, [ typelist ]); this.target = target; }; Svidget.EventContainer.prototype = new Svidget.EventPrototype(); Svidget.extend(Svidget.EventContainer, { /** * Gets the target object to use when triggering an event. * @method * @returns {object} */ getTarget: function() { return this.target; } }, true); /** * Represents the root object (access via global svidget var). * @constructor * @mixes ObjectPrototype * @memberof Svidget * @param {object} root - The root global object in scope (i.e. window). */ Svidget.Root = function(root) { this.__type = "Svidget.Root"; //var isWidget = null; //var isBrowser = null; //var domLoaded = false; //var doc = document; //var docElement = document.documentElement; var that = this; // private fields var privates = new function() { this.writable = [ "current", "widgets", "connected", "loaded" ]; // Common: this.comm = new Svidget.Communicator(); this.eventContainer = new Svidget.EventContainer([ "loaded" ], that); // todo: move event names to array at bottom this.loaded = false; // Widget: this.current = null; this.connected = false; // Page: this.widgets = null; }(); // private accessors this.setup(privates); // state //this.isWidget = null; // moved to function this.isBrowser = true; // whether in browser or in some other execution environment i.e. Node.js //this.isReady = false; // moved to function this.root = root || window; // i.e. window this.docType = null; this.setCurrent = function(widget) { privates.current = widget; }; // invoke init // todo: convert to private methods this._init(); }; Svidget.Root.prototype = { _init: function() { //this._initDomObjects(); this._initEvents(); this._initPrototypes(); this.initInternal(); this._initReady(); }, _initEvents: function() {}, _initPrototypes: function() { if (this.isWidget()) { Svidget.extend(Svidget.Root, Svidget.Root.WidgetPrototype, true); } else { Svidget.extend(Svidget.Root, Svidget.Root.PagePrototype, true); } }, _initReady: function() { // is DOM loaded? // if not attach handler, if so call ready if (this.isDomReady()) { this._ready(); } else { // add ready handler this.addReadyEvents(); } }, // protected: overriden in prototypes initInternal: function() {}, _ready: function() { // if widget create Widget class this.isReady = true; if (this.isWidget()) { this.readyWidget(); } else { this.readyPage(); } }, getDocType: function() { // determine if in widget var localName = document.documentElement.localName; var namespaceUri = document.documentElement.namespaceURI; if (localName == "svg" && namespaceUri == Svidget.Namespaces.svg) return Svidget.DocType.svg; return Svidget.DocType.html; }, /** * Determines if the framework is instantiated in a widget file. * @method * @memberof Svidget.Root.prototype * @returns {boolean} */ isWidget: function() { this.docType = this.getDocType(); return this.docType == Svidget.DocType.svg; }, // ready if interactive or complete isDomReady: function() { // determine DOM loaded var rs = document.readyState; if (rs == null || !Svidget.DocReadyState[rs]) return false; return Svidget.DocReadyState[rs] >= Svidget.DocReadyState.interactive; }, addReadyEvents: function() { // attach to: DOMContentLoaded, readystatechange, load // we attach at all 3 stages var handler = Svidget.wrap(this.readyHandler, this); Svidget.DOM.on(document, "DOMContentLoaded", handler); Svidget.DOM.on(document, "readystatechange", handler); Svidget.DOM.on(window, "load", handler); }, readyHandler: function() { this.ensureReady(); }, ensureReady: function() { if (!this.isReady) this._ready(); this.isReady = true; }, // note: loaded state only applies to declared widgets ? (needs determiniation) // widgets loaded via svidget.load() markLoaded: function() { if (this.getset("loaded") === true) return; this.getset("loaded", true); this.triggerLoaded(); }, eventContainer: function() { return this.getset("eventContainer"); }, /** * Registers an event handler for the global object. * @method * @memberof Svidget.Root.prototype * @param {string} type - The event type i.e. "load". * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ on: function(type, data, name, handler) { this.eventContainer().on(type, data, name, handler); }, /** * Unregisters an event handler for the global object. * @method * @memberof Svidget.Root.prototype * @param {string} type - The event type i.e. "load". * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ off: function(type, handlerOrName) { this.eventContainer().off(type, handlerOrName); }, // public // triggers the event, using the specified data as input trigger: function(name, value) { // call something on parent widget this.eventContainer().trigger(name, value); }, /** * Registers an event handler for the "load" event for the global object. * @method * @memberof Svidget.Root.prototype * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ // deprecate loaded in favor of onload loaded: function(data, name, handler) { this.onload(data, name, handler); }, onload: function(data, name, handler) { this.on("load", data, name, handler); }, offload: function(handlerOrName) { this.off("load", handlerOrName); }, offdeclaredload: function() { this.off("load", Svidget.declaredHandlerName); }, /** * Registers an event handler for the "widgetload" event for the global object. * @method * @memberof Svidget.Root.prototype * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ // wires up a handler for the "widgetload" event widgetloaded: function(data, name, handler) { this.widgetloaded(data, name, handler); }, onwidgetload: function(data, name, handler) { this.on("widgetload", data, name, handler); }, offwidgetload: function(handlerOrName) { this.off("widgetload", handlerOrName); }, <API key>: function() { this.off("widgetload", Svidget.declaredHandlerName); }, // todo: rename to triggerLoad // internal triggerLoaded: function() { this.trigger("load"); }, // todo: rename to triggerWidgetLoad // internal triggerWidgetLoaded: function(widgetID) { this.trigger("widgetload", widgetID); }, comm: function() { return this.getset("comm"); }, routeFromParent: function(name, payload) { Svidget.log("root: routeFromParent {name: " + name + "}"); this.comm().receiveFromParent(name, payload); }, routeFromWidget: function(name, payload, widgetID) { Svidget.log("root: routeFromWidget {name: " + name + "}"); this.comm().receiveFromWidget(name, payload, widgetID); }, receiveFromParent: function(name, payload) {}, receiveFromWidget: function(name, payload, widgetID) {}, /** * Gets the current widget. * @method * @abstract * @returns {Svidget.Widget} - The current widget. */ current: function() { return null; }, /** * Gets whether the widget is connected to a parent page. * @method * @abstract * @memberof Svidget.Root * @returns {boolean} */ connected: function(val) { var res = this.getset("connected", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; return true; } }; Svidget.extend(Svidget.Root, Svidget.ObjectPrototype); /** * A collection of util methods. * @static * @memberof Svidget */ Svidget.Util = {}; /** * Gets all the values from the query string and returns the result as an object. * @static * @memberof Svidget * @param {bool} duplicates - if true, group duplicates into an array (default == false) * @param {} lastOneWins - if true, then last duplicate encountered will win, else first one will win (default == false) */ Svidget.Util.queryString = function(duplicates, lastOneWins) { var match, pl = /\+/g, // Regex for replacing addition symbol with a space search = /([^&=]+)=?([^&]*)/g, decode = function(s) { return decodeURIComponent(s.replace(pl, " ")); }, query = window.location.search.substring(1); var urlParams = {}; while (match = search.exec(query)) { // index 1 and 2 because those are the subgroups in parens (), index 0 is the whole string match var name = decode(match[1]), value = decode(match[2]); var array; if (duplicates) { if (urlParams[name] !== undefined) { if (Svidget.isArray(urlParams[name])) urlParams[name].push(value); else urlParams[name] = [ urlParams[name], value ]; } else urlParams[name] = value; } else if (lastOneWins || urlParams[name] === undefined) urlParams[name] = value; } return urlParams; }; /** * Represents an widget action, defined by <svidget:action>. * @class * @mixes Svidget.ObjectPrototype * @augments Svidget.EventPrototype * @memberof Svidget * @param {string} name - The name of the action. * @param {object} options - The options for the action param. Example: { enabled: true, description: "An action" } * @param {Svidget.Widget} parent - The widget instance that is the parent for this action. */ Svidget.Action = function(name, options, parent) { this.__type = "Svidget.Action"; // name is not null options = options || {}; parent = parent instanceof Svidget.Widget ? parent : null; // parent can only be a Widget var that = this; // private fields var privates = new function() { this.writable = [ "binding", "enabled", "external", "description" ]; this.params = new Svidget.<API key>([], that); this.name = name; this.description = options.description; this.enabled = options.enabled !== false; this.binding = options.binding || null; this.external = options.external !== false; this.widget = parent; this.bindingFunc = null; }(); // private accessors this.setup(privates); // todo: move to core or util //this.buildBindingFunc = function (bind) { // return bind; // else if (bind != null) { // bind = bind + ""; //coerce to string // var func = Svidget.root[bind]; // if (func == null) return null; // // bind is an expression, so just wrap it in a function // if (bind.substr(0, 7) != "return ") // return new Function("return " + bind); // else // return new Function(bind); // /*//try { // // return eval(options.binding); // //catch (ex) { // // return undefined; // return null; // create bindingFunc from binding // binding can be string or function privates.bindingFunc = Svidget.findFunction(privates.binding); // wire up event bubble parent this.<API key>(Svidget.Action.eventTypes, parent, parent.actionBubble); // add/remove event handlers for params this.<API key>(privates.params, that.paramAdded, that.paramRemoved); }; Svidget.Action.prototype = { /** * Gets the action name. * @method * @returns {string} */ name: function() { var res = this.getPrivate("name"); return res; }, /** * Gets whether the action is attached to the widget. * @method * @returns {boolean} */ attached: function() { var widget = this.getset("widget"); return this.widget != null && this.widget instanceof Svidget.Widget; }, /** * Gets or sets whether the action is enabled. * @method * @param {boolean} [val] - Sets the enabled state when specified. * @returns {boolean} - The enabled state when nothing is passed, or true/false if succeeded or failed when setting. */ enabled: function(val) { var res = this.getset("enabled", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "enabled", value: val }); return true; }, /** * Gets or sets the description. * @method * @param {string} [val] - Sets the value when specified. * @returns {string} - The value for a get, or true/false if succeeded or failed for a set. */ description: function(val) { var res = this.getset("description", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "description", value: val }); return true; }, /** * Gets or sets whether the action is external and can be invoked from the page. * @method * @param {boolean} [val] - Sets the value when specified. * @returns {boolean} - The value for a get, or true/false if succeeded or failed for a set. */ external: function(val) { var res = this.getset("external", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "external", value: val }); return true; }, /** * Gets or sets the binding for the action. This can be a global function name, or a function. * @method * @param {Boolean} [val] - Sets the value when specified. * @returns {Boolean} - The value for a get, or true/false if succeeded or failed for a set. */ binding: function(bind) { // bind can be string or function, so check for both, enforce if (bind !== undefined) { if (typeof bind !== "function") bind = bind + ""; // coerce to string // update bindingFunc var func = Svidget.findFunction(bind); this.getset("bindingFunc", func); } var res = this.getset("binding", bind); // if undefined its a get so return value, if res is false then set failed if (bind === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "binding", value: val }); return true; }, bindingFunc: function() { var bind = this.getset("binding"); var func = Svidget.findFunction(bind); return func; }, /** * Invokes the action. The params passes in will be passed to the action params in order. * @method * @param {...object} args - The arguments that correspond to action params. * @returns {boolean} - True if invoke succeeds. */ invoke: function() { if (!this.enabled()) return false; var func = this.<API key>(); if (!func) return false; var argArray = this.buildArgumentArray(Svidget.array(arguments)); var returnVal = func.apply(null, argArray); //Svidget.root, arguments); //var argObj = this.toArgumentObject(Svidget.array(arguments)); this.trigger("invoke", { returnValue: returnVal }); return true; }, invokeApply: function(args) { this.invoke.apply(this, args); }, <API key>: function() { var func = this.bindingFunc(); if (func == null || typeof func !== "function") return null; return func; }, // builds an array of argument to use in invoke() based on the action params buildArgumentArray: function(args) { var argsArray = []; args = args == null ? [] : args; var col = this.params(); // loop through action params for (var i = 0; i < col.length; i++) { var p = col[i]; var arg = undefined; if (i < args.length) arg = args[i]; if (arg === undefined) arg = p.defvalue(); // an arg wasn't supplied by caller, so use default value from action param if provided argsArray.push(arg); } return argsArray; }, // build an object based on the action params, and values from arguments on invoke toArgumentObject: function(args) { var argsObj = {}; var col = this.params(); // loop through action params for (var i = 0; i < col.length; i++) { var p = col[i]; var arg = undefined; if (i < args.length) arg = args[i]; if (arg === undefined) arg = p.defvalue(); // an arg wasn't supplied by caller, so use default value from action param if provided argsObj[p.name()] = arg; } return argsObj; }, /** * Gets a collection of all ActionParam objects, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * params(0) * params("color") * @method * @param {(string|number)} [selector] - The selector string or integer. * @returns {Svidget.<API key>} - A collection based on the selector, or the entire collection. */ params: function(selector) { var col = this.getset("params"); return this.select(col, selector); }, /** * Gets the ActionParam based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * param(0) * param("color") * @method * @param {(string|number)} selector - The index or ID of the param. * @returns {Svidget.ActionParam} - The ActionParam based on the selector. If selector is invalid, null is returned. */ param: function(selector) { //var item = this.params(selector).first(); var col = this.getset("params"); var item = this.selectFirst(col, selector); return item; }, /** * Adds a ActionParam to the action. If a duplicate name is supplied the ActionParam will fail to add. * Examples: * addParam("backColor") * addParam("backColor", { description: "Background color."}) * @method * @param {string} name - The name of the ActionParam to add. * @param {object} [options] - The options used to contruct the ActionParam. Example: { description: "A param" } * @returns {Svidget.ActionParam} - The ActionParam that was added, or null if ActionParam failed to add. */ addParam: function(name, options) { return this.params().add(name, options, this); }, /** * Removes an ActionParam from the action. * Examples: * removeParam("color") * @method * @param {string} name - The name of the ActionParam to remove. * @returns {boolean} - True if the Param was successfully removed, false otherwise. */ removeParam: function(name) { return this.params().remove(name); }, paramBubble: function(type, event, param) { if (type == "change") this.paramChanged(param, event.value); }, // handle param added paramChanged: function(param, eventValue) { Svidget.log("action: param changed: " + param.name()); this.trigger("paramchange", eventValue, param); }, // handle param added paramAdded: function(param) { Svidget.log("action: param added: " + param.name()); this.trigger("paramadd", param); }, // private // handle param removed paramRemoved: function(param) { Svidget.log("action: param removed: " + param.name()); this.trigger("paramremove", param.name()); }, /** * Adds an event handler for the "change" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onchange: function(data, name, handler) { return this.on("change", data, name, handler); }, ondeclaredchange: function(handler) { return this.onchange(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "change" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offchange: function(handlerOrName) { this.off("change", handlerOrName); }, offdeclaredchange: function() { return this.offchange(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "invoke" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ oninvoke: function(data, name, handler) { return this.on("invoke", data, name, handler); }, ondeclaredinvoke: function(handler) { return this.oninvoke(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "invoke" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offinvoke: function(handlerOrName) { return this.off("invoke", handlerOrName); }, offdeclaredinvoke: function() { return this.offinvoke(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "paramadd" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onparamadd: function(data, name, handler) { return this.on("paramadd", data, name, handler); }, ondeclaredparamadd: function(handler) { return this.onparamadd(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "paramadd" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offparamadd: function(handlerOrName) { return this.off("paramadd", handlerOrName); }, offdeclaredparamadd: function() { return this.offparamadd(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "paramremove" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onparamremove: function(data, name, handler) { return this.on("paramremove", data, name, handler); }, <API key>: function(handler) { return this.onparamremove(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "paramremove" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offparamremove: function(handlerOrName) { return this.off("paramremove", handlerOrName); }, <API key>: function() { return this.offparamremove(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "paramremove" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onparamchange: function(data, name, handler) { return this.on("paramchange", data, name, handler); }, <API key>: function(handler) { return this.onparamchange(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "paramremove" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offparamchange: function(handlerOrName) { return this.off("paramchange", handlerOrName); }, <API key>: function() { return this.offparamchange(Svidget.declaredHandlerName); }, // helpers /** * Serializes the Action object for transport across a window boundary. * @method * @returns {boolean} - A generic serialized object representing the Action. */ toTransport: function() { var transport = { name: this.name(), description: this.description(), external: this.external(), enabled: this.enabled(), //binding: this.binding(), // not accessible by proxy params: this.toParamsTransport() }; return transport; }, toParamsTransport: function() { var col = this.params(); var ps = col.select(function(p) { return p.toTransport(); }).toArray(); return ps; }, // overrides /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.Action { name: "' + this.name() + '" }]'; } }; Svidget.Action.eventTypes = [ "invoke", "change", "paramchange", "paramadd", "paramremove" ]; Svidget.Action.optionProperties = [ "external", "binding", "enabled", "description" ]; Svidget.Action.allProxyProperties = [ "name", "external", "enabled", "description" ]; Svidget.Action.<API key> = []; Svidget.extend(Svidget.Action, Svidget.ObjectPrototype); Svidget.extend(Svidget.Action, new Svidget.EventPrototype(Svidget.Action.eventTypes)); /** * Represents a collection of Action objects. * @class * @augments Svidget.ObjectCollection * @memberof Svidget.Svidget * @param {array} array - An array of Action objects. * @param {Svidget.Widget} parent - The Widget instance that is the parent for this Action collection. */ Svidget.ActionCollection = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.Action ]); this.__type = "Svidget.ActionCollection"; var that = this; this.parent = parent; }; Svidget.ActionCollection.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.ActionCollection, { create: function(name, options, parent) { // create action // call addObject if (name == null || !typeof name === "string") return null; // ensure no other action exists in the collection by that name if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.Action(name, options, parent); //this.push(obj); return obj; } }, true); /** * Represents a param for an action, defined by <svidget:actionparam>. * @class * @mixes Svidget.ObjectPrototype * @augments Svidget.EventPrototype * @memberof Svidget * @param {string} name - The name of the action param. * @param {object} options - The options for the action param. Example: { type: "string", subtype: "regex", description: "An action param" } * @param {Svidget.Widget} parent - The widget instance that is the parent for this action. */ Svidget.ActionParam = function(name, options, parent) { this.__type = "Svidget.ActionParam"; // name is not null options = options || {}; // parent must be Action parent = parent instanceof Svidget.Action ? parent : null; // parent can only be a Action // private fields var privates = new function() { this.writable = [ "type", "subtype", "description", "defvalue" ]; this.name = name; this.type = options.type || "string"; this.subtype = options.subtype || null; this.description = options.description; this.defvalue = options.defvalue; //todo: convert to type this.parent = parent; }(); // private accessors this.setup(privates); // wire up event bubble parent this.<API key>(Svidget.ActionParam.eventTypes, parent, parent.paramBubble); }; Svidget.ActionParam.prototype = { toTransport: function() { var transport = { name: this.name(), type: this.type(), subtype: this.subtype(), description: this.description() }; return transport; }, /** * Adds an event handler for the "change" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onchange: function(data, name, handler) { return this.on("change", data, name, handler); }, ondeclaredchange: function(handler) { return this.onchange(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "change" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offchange: function(handlerOrName) { this.off("change", handlerOrName); }, offdeclaredchange: function() { return this.offchange(Svidget.declaredHandlerName); }, /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.ActionParam { name: "' + this.name + '" }]'; } }; Svidget.ActionParam.eventTypes = [ "change" ]; Svidget.ActionParam.optionProperties = [ "type", "subtype", "description", "defvalue" ]; Svidget.ActionParam.allProxyProperties = [ "name", "type", "subtype", "description", "defvalue" ]; Svidget.ActionParam.<API key> = []; Svidget.extend(Svidget.ActionParam, Svidget.ObjectPrototype); Svidget.extend(Svidget.ActionParam, Svidget.ParamPrototype); Svidget.extend(Svidget.ActionParam, new Svidget.EventPrototype(Svidget.ActionParam.eventTypes)); /** * Represents a collection of ActionParam objects. * @class * @augments Svidget.ObjectCollection * @memberof Svidget.Svidget * @param {array} array - An array of ActionParam objects. * @param {Svidget.Action} parent - The Action instance that is the parent for this ActionParam collection. */ Svidget.<API key> = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.ActionParam ]); this.__type = "Svidget.<API key>"; var that = this; this.parent = parent; }; Svidget.<API key>.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.<API key>, { create: function(name, options, parent) { // create param // call addObject if (name == null || !typeof name === "string") return null; // ensure no other action exists in the collection by that name if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.ActionParam(name, options, parent); //this.push(obj); return obj; } }, true); /** * Represents an user-defined event for a widget, defined by <svidget:event> * @constructor * @mixes ObjectPrototype * @augments EventPrototype * @memberof Svidget * @param {string} name - The name of the event. * @param {object} options - The options for the event. Example: { enabled: true, description: "An event" } * @param {Svidget.Widget} parent - The widget instance that is the parent for this action. */ Svidget.EventDesc = function(name, options, parent) { this.__type = "Svidget.EventDesc"; // name is not null options = options || {}; parent = parent instanceof Svidget.Widget ? parent : null; // parent can only be a Widget var that = this; // private fields var privates = new function() { this.writable = [ "description", "enabled", "external" ]; this.name = name; this.description = options.description; this.external = options.external !== false; this.enabled = options.enabled !== false; this.eventName = "trigger"; // this is the internal name we use for the event this.eventContainer = new Svidget.EventContainer([ this.eventName ], that); }(); // private accessors this.setup(privates); // wire up event bubble parent privates.eventContainer.<API key>(Svidget.EventDesc.eventTypes, parent, parent.eventBubble); }; Svidget.EventDesc.prototype = { /** * Gets the event name. * @method * @returns {string} */ name: function() { var res = this.getPrivate("name"); return res; }, /** * Gets whether the event is attached to the widget. * @method * @returns {boolean} */ attached: function() { var widget = this.getset("widget"); return this.widget != null && this.widget instanceof Svidget.Widget; }, /** * Gets or sets whether the event is enabled. * @method * @param {boolean} [val] - Sets the enabled state when specified. * @returns {boolean} - The enabled state when nothing is passed, or true/false if succeeded or failed when setting. */ enabled: function(val) { var res = this.getset("enabled", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "enabled", value: val }); return true; }, /** * Gets or sets the description. * @method * @param {string} [val] - Sets the value when specified. * @returns {string} - The value for a get, or true/false if succeeded or failed for a set. */ description: function(val) { var res = this.getset("description", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "description", value: val }); return true; }, /** * Gets or sets whether the event is external and can be triggered from the page. * @method * @param {boolean} [val] - Sets the value when specified. * @returns {boolean} - The value for a get, or true/false if succeeded or failed for a set. */ external: function(val) { var res = this.getset("external", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "public", value: val }); return true; }, // private: used internally for a default event name for the container eventName: function() { return this.getPrivate("eventName"); }, eventContainer: function() { return this.getset("eventContainer"); }, /** * Registers an event handler for the EventDesc object. * @method * @param {string} [type] - The event type i.e. "change". If not specified it is assumed it is for the event itself. * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ on: function(type, data, name, handler) { // if type is function, then assume type not passes so use default event name if (Svidget.isFunction(type)) { handler = type; type = this.eventName(); } this.eventContainer().on(type, data, name, handler); }, /** * Adds an event handler for the "trigger" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ ontrigger: function(data, name, handler) { this.eventContainer().on(this.eventName(), data, name, handler); }, ondeclaredtrigger: function(handler) { return this.ontrigger(null, Svidget.declaredHandlerName, handler); }, /** * Unregisters an event handler for the EventDesc object. * @method * @param {string} [type] - The event type i.e. "change", "paramremove". If not specified it is assumed it is for the event itself. * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ off: function(type, handlerOrName) { // if type is function, then assume type not passes so use default event name if (Svidget.isFunction(type)) { handlerOrName = type; type = this.eventName(); } this.eventContainer().off(type, handlerOrName); }, /** * Removes an event handler for the "trigger" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offtrigger: function(handlerOrName) { this.eventContainer().off(this.eventName(), handlerOrName); }, offdeclaredtrigger: function() { return this.offtrigger(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "change" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onchange: function(data, name, handler) { return this.on("change", data, name, handler); }, ondeclaredchange: function(handler) { return this.onchange(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "change" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offchange: function(handlerOrName) { this.off("change", handlerOrName); }, offdeclaredchange: function() { return this.offchange(Svidget.declaredHandlerName); }, /** * Triggers the event for the EventDesc object. * @method * @param {object} value - The value to set to the Event.value property. */ // Note: The use of type as a param is undocumented here. For public use we only want them passing value as a param. trigger: function(type, value) { if (!this.enabled()) return; if (value === undefined) { value = type; type = this.eventName(); } this.eventContainer().trigger(type, value); }, triggerEvent: function(value) { this.trigger(this.eventName(), value); }, // helpers /** * Serializes the EventDesc object for transport across a window boundary. * @method * @returns {boolean} - A generic serialized object representing the EventDesc object. */ toTransport: function() { var transport = { name: this.name(), description: this.description(), external: this.external(), enabled: this.enabled() }; return transport; }, // overrides /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.EventDesc { name: "' + this.name + '" }]'; } }; Svidget.EventDesc.eventTypes = [ "trigger", "change" ]; Svidget.EventDesc.optionProperties = [ "external", "enabled", "description" ]; Svidget.EventDesc.allProxyProperties = [ "name", "external", "enabled", "description", "eventContainer" ]; Svidget.EventDesc.<API key> = []; Svidget.extend(Svidget.EventDesc, Svidget.ObjectPrototype); /** * Represents a collection of EventDesc objects. * @constructor * @augments ObjectCollection * @memberof Svidget * @param {Svidget.EventDesc[]} array - An array of EventDesc objects. * @param {Svidget.Widget} parent - The Widget instance that is the parent for this EventDesc collection. */ Svidget.EventDescCollection = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.EventDesc ]); this.__type = "Svidget.EventDescCollection"; var that = this; this.parent = parent; }; Svidget.EventDescCollection.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.EventDescCollection, { create: function(name, options, parent) { // create param // call addObject if (name == null || !typeof name === "string") return null; // ensure no other action exists in the collection by that name if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.EventDesc(name, options, parent); //this.push(obj); return obj; } }, true); /** * Represents param for a widget, defined by <svidget:param> * @constructor * @mixes ObjectPrototype * @mixes ParamPrototype * @augments EventPrototype * @memberof Svidget * @param {string} name - The name of the param. * @param {object} value - The value for the param. * @param {object} options - The options for the param. Example: { enabled: true, description: "An event" } * @param {Svidget.Widget} parent - The widget that is the parent for this param. */ // example usage: widget1.param("backgroundColor").value(); Svidget.Param = function(name, value, options, parent) { this.__type = "Svidget.Param"; // name is not null options = options || {}; parent = parent instanceof Svidget.Widget ? parent : null; // parent can only be a Widget // private fields var privates = new function() { this.writable = [ "binding", "enabled", "type", "subtype", "value", "description", "defvalue" ]; this.name = name; this.shortname = options.shortname; this.description = options.description; this.enabled = options.enabled !== false; this.type = options.type || "string"; this.subtype = options.subtype || null; this.value = value; this.defvalue = options.defvalue; //todo: convert to type this.sanitizer = options.sanitizer || null; this.widget = parent; this.binding = options.binding || null; this.bindingQuery = null; }(); // private accessors this.setup(privates); // target or binding privates.bindingQuery = Svidget.DOM.select(privates.binding); // create sanitizerFunc from sanitizer // sanitizer can be string or function privates.sanitizerFunc = Svidget.findFunction(privates.sanitizer); this.valuePopulated = false; // flipped to true once a value has been assigned or the default value is applied //this.isProxy; // maybe we do need a separate ParameterProxy class // wire up event bubble parent this.<API key>(Svidget.Param.eventTypes, parent, parent.paramBubble); }; Svidget.Param.prototype = { /** * Gets the shortname value. This is used for params passed from the query string. * @method * @param {boolean} [val] - Sets the enabled state when specified. * @returns {boolean} - The enabled state when nothing is passed, or true/false if succeeded or failed when setting. */ shortname: function() { var res = this.getPrivate("shortname"); return res; }, // public // attached is a state property // gets whether the param is attached to the widget // todo: do we need for action and event too? attached: function() { var widget = this.getset("widget"); return this.widget != null && this.widget instanceof Svidget.Widget; }, /** * Gets or sets whether the event is enabled. * @method * @param {boolean} [val] - Sets the enabled state when specified. * @returns {boolean} - The enabled state when nothing is passed, or true/false if succeeded or failed when setting. */ enabled: function(val) { var res = this.getset("enabled", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "enabled", value: val }); return true; }, /** * Gets or sets the param value. * @method * @param {boolean} [val] - Sets the enabled state when specified. * @returns {boolean} - The enabled state when nothing is passed, or true/false if succeeded or failed when setting. */ value: function(val) { var res = this.getset("value", val, this.validateValue); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // check enabled if (!this.enabled()) return false; // sanitize val using param.sanitizer var sanVal = this.applySanitizer(val); // apply to binding this.applyBinding(sanVal); // fire "set" event this.trigger("valuechange", { value: sanVal }); // for backwards compatibility this.trigger("set", { value: sanVal }); // 0.1.3: replaces "valuechange" return true; }, /** * Gets or sets the param binding. This is a CSS+Attributes selector. * @method * @param {boolean} [val] - Sets the enabled state when specified. * @returns {boolean} - The enabled state when nothing is passed, or true/false if succeeded or failed when setting. */ binding: function(bind) { bind = bind !== undefined ? bind + "" : undefined; // coerce to string var res = this.getset("binding", bind); // if undefined its a get so return value, if res is false then set failed if (bind === undefined || !!!res) return res; // todo: construct bindingQuery object this.getset("bindingQuery", Svidget.DOM.select(bind)); // fire "changed" event this.trigger("change", { property: "binding", value: bind }); return true; }, bindingQuery: function() { return this.getset("bindingQuery"); }, /** * Gets or sets the sanitizer function for the param. The sanitizer function is called on set. * The sanitizer function takes a param and value (param, value) and returns the result value. * This can be a global function name, or a function. * @method * @param {Boolean} [val] - Sets the value when specified. * @returns {Boolean} - The value for a get, or true/false if succeeded or failed for a set. */ sanitizer: function(funcName) { // bind can be string or function, so check for both, enforce if (funcName !== undefined) { if (typeof funcName !== "function") funcName = funcName + ""; // coerce to string // update bindingFunc var func = Svidget.findFunction(funcName); this.getset("sanitizerFunc", func); } var res = this.getset("sanitizer", funcName); // if undefined its a get so return value, if res is false then set failed if (bind === undefined || !!!res) return res; // fire "changed" event this.trigger("change", { property: "sanitizer", value: val }); return true; }, sanitizerFunc: function() { var bind = this.getset("sanitizer"); var func = Svidget.findFunction(bind); return func; }, applySanitizer: function(val) { var func = this.sanitizerFunc(); if (!func) return val; var returnVal = func.call(null, this, val); if (returnVal === undefined) return val; // if they didn't specify a return value, then just revert back to original val return returnVal; }, validateValue: function(val) { return true; }, // helpers applyBinding: function(val) { var bind = this.bindingQuery(); if (bind == null) return; bind.setValue(val); }, /** * Adds an event handler for the "change" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onchange: function(data, name, handler) { return this.on("change", data, name, handler); }, ondeclaredchange: function(handler) { return this.onchange(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "change" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offchange: function(handlerOrName) { this.off("change", handlerOrName); }, offdeclaredchange: function() { return this.offchange(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "set" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onset: function(data, name, handler) { return this.on("set", data, name, handler); }, ondeclaredset: function(handler) { return this.onset(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "set" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offset: function(handlerOrName) { return this.off("set", handlerOrName); }, offdeclaredset: function() { return this.offset(Svidget.declaredHandlerName); }, /** * Serializes the Param object for transport across a window boundary. * @method * @returns {boolean} - A generic serialized object representing the Param object. */ toTransport: function() { var transport = { name: this.name(), shortname: this.shortname(), enabled: this.enabled(), type: this.type(), subtype: this.subtype(), value: this.value() }; return transport; }, // overrides /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.Param { name: "' + this.name + '" }]'; } }; // todo: convert these to functions so that users can't manipulate Svidget.Param.eventTypes = [ "valuechange", "change" ]; Svidget.Param.optionProperties = [ "type", "subtype", "binding", "sanitizer", "enabled", "shortname", "defvalue" ]; Svidget.Param.allProxyProperties = [ "name", "value", "type", "subtype", "enabled", "shortname", "defvalue" ]; // 0.1.3: removed "binding", Svidget.Param.<API key> = [ "value" ]; Svidget.extend(Svidget.Param, Svidget.ObjectPrototype); Svidget.extend(Svidget.Param, Svidget.ParamPrototype); Svidget.extend(Svidget.Param, new Svidget.EventPrototype(Svidget.Param.eventTypes)); /** * Represents a collection of Param objects. * @constructor * @augments ObjectCollection * @memberof Svidget * @param {array} array - An array of Param objects. * @param {Svidget.Widget} parent - The Widget instance that is the parent for this Param collection. */ Svidget.ParamCollection = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.Param ]); this.__type = "Svidget.ParamCollection"; var that = this; this.parent = parent; }; Svidget.ParamCollection.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.ParamCollection, { create: function(name, value, options, parent) { // create param // call addObject if (name == null || !typeof name === "string") return null; // ensure no other parameter exists in the collection by that name if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.Param(name, value, options, parent); //this.push(obj); return obj; } }, true); /** * Represents the widget. * @class * @mixes Svidget.ObjectPrototype * @augments Svidget.EventPrototype * @memberof Svidget */ Svidget.Widget = function() { this.__type = "Svidget.Widget"; var that = this; // privates var privates = new function() { this.writable = [ "id", "enabled", "started", "connected" ]; this.params = new Svidget.ParamCollection([], that); this.actions = new Svidget.ActionCollection([], that); this.events = new Svidget.EventDescCollection([], that); this.enabled = true; // reserved for future use this.connected = false; this.started = false; this.id = null; // provided by parent this.page = null; // todo: get a reference to an object containing details about the page (determine if we need) this.parentElement = null; }(); // private accessors this.setup(privates); // wire events for params add/remove and bubbles this.<API key>(privates.params, that.paramAdded, that.paramRemoved); // wire events for actions add/remove and bubbles this.<API key>(privates.actions, that.actionAdded, that.actionRemoved); // wire events for events add/remove this.<API key>(privates.events, that.eventAdded, that.eventRemoved); this._init(); }; Svidget.Widget.prototype = { _init: function() {}, start: function() { // if DOM not ready then readyConnected(0 will be called when ready() //if (this.loaded) this.readyConnected(); this.getset("started", true); }, connect: function(id) { // if DOM not ready then readyConnected(0 will be called when ready() //if (this.loaded) this.readyConnected(); if (this.connected()) return; this.getset("id", id); this.getset("connected", true); }, // REGION: Parent // internal // called from the root to signal that the parent element has changed, so we update there updateParentElement: function(item) {}, // REGION: Params /** * Gets a collection of all Param objects in the widget, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * params(0) * params("color") * @method * @memberof Svidget.Widget.prototype * @param {object} [selector] - The selector string or integer. * @returns {Svidget.ParamCollection} - A collection based on the selector, or the entire collection. */ params: function(selector) { var col = this.getset("params"); return this.select(col, selector); }, /** * Gets the Param based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * param(0) * param("color") * @method * @memberof Svidget.Widget.prototype * @param {object} selector - The index or ID of the param. * @returns {Svidget.Param} - The Param based on the selector. If selector is invalid, null is returned. */ param: function(selector) { //var item = this.params(selector).first(); var col = this.getset("params"); var item = this.selectFirst(col, selector); return item; }, /** * Adds a Param to the widget. If a duplicate name is supplied the Param will fail to add. * Examples: * addParam("backColor", "#ffee54", { description: "Background color."}) * addParam("color") * @method * @memberof Svidget.Widget.prototype * @param {string} name - The name of the Param to add. * @param {object} value - The value of the Param. * @param {object} [options] - The options used to contruct the Param. Example: { enabled: true, description: "A param" } * @returns {Svidget.Param} - The Param that was added, or null if Param failed to add. */ addParam: function(nameOrObject, value, options) { return this.params().add(nameOrObject, value, options, this); }, /** * Removes an Param from the widget. * Examples: * removeParam("color") * @method * @memberof Svidget.Widget.prototype * @param {string} name - The name of the Param to remove. * @returns {Boolean} - True if the Param was successfully removed, false otherwise. */ removeParam: function(name) { return this.params().remove(name); }, // internal // handle param added paramAdded: function(param) { // raise event //alert('param added'); Svidget.log("widget: param added: " + param.name()); // event.value = param this.trigger("paramadd", param); // signal parent svidget.signalParamAdded(param); }, // internal // handle param removed paramRemoved: function(param) { // raise event //alert('param removed'); Svidget.log("widget: param removed: " + param.name()); // event.value = param.name this.trigger("paramremove", param.name()); // signal parent svidget.signalParamRemoved(param.name()); }, // internal // called from param paramBubble: function(type, event, param) { if (type == "change") this.paramChanged(param, event.value); if (type == "valuechange") this.paramValueChanged(param, event.value); }, // private // eventValue ex = { property: "binding", value: bindValue } paramChanged: function(param, eventValue) { this.trigger("paramchange", eventValue, param); // signal parent svidget.signalParamChanged(param, eventValue); }, // private // eventValue ex = { value: "3" } paramValueChanged: function(param, eventValue) { this.trigger("paramvaluechange", eventValue, param); // signal parent svidget.<API key>(param, eventValue); }, // REGION: Actions /** * Gets a collection of all actions in the widget, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * actions(0) * actions("doSomething") * @method * @memberof Svidget.Widget.prototype * @param {object} [selector] - * @returns {Svidget.ActionCollection} - A collection based on the selector, or the entire collection. */ actions: function(selector) { var col = this.getset("actions"); return this.select(col, selector); }, /** * Gets the action object based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * action(1) * action("doSomething") * @method * @memberof Svidget.Widget.prototype * @param {object} selector - The index or ID of the action. * @returns {Svidget.Action} - The action based on the selector. If selector is invalid, null is returned. */ action: function(selector) { //var item = this.actions(selector).first(); var col = this.getset("actions"); var item = this.selectFirst(col, selector); return item; }, /** * Adds an Action to the widget. If a duplicate name is supplied the action will fail to add. * Examples: * addAction("doIt", { binding: function (s) { do_something(s) }, description: "Background color."}) * @method * @memberof Svidget.Widget.prototype * @param {string} name - The name of the param to add. * @param {object} [options] - The options used to contruct the Action. Example: { enabled: true, description: "An action" } * @returns {Svidget.Action} - The Action that was added, or null if Action failed to add. */ addAction: function(nameOrObject, options) { var action = this.actions().add(nameOrObject, options, this); if (action == null) return action; // add params // options.params if (options == null || options.params == null || !Svidget.isArray(options.params)) return action; for (var i = 0; i < options.params.length; i++) { var p = options.params[i]; if (p != null && p.name != null) { action.addParam(p.name, p); } } }, /** * Removes an Action from the widget. * Examples: * removeAction("someAction") * @method * @memberof Svidget.Widget.prototype * @param {string} name - The name of the Action to remove. * @returns {boolean} - True if the Action was successfully removed, false otherwise. */ removeAction: function(name) { return this.actions().remove(name); }, // private // handle action added actionAdded: function(action) { Svidget.log("widget: action added: " + action.name()); // trigger event // event.value = action this.trigger("actionadd", action); // signal parent svidget.signalActionAdded(action); }, // private // handle action removed actionRemoved: function(action) { Svidget.log("widget: action removed: " + action.name()); // trigger event // event.value = action.name this.trigger("actionremove", action.name()); // signal parent svidget.signalActionRemoved(action.name()); }, // private // internal, called from action actionBubble: function(type, event, action) { if (type == "invoke") this.actionInvoked(action, event.value); if (type == "change") this.actionChanged(action, event.value); // event.target is actionParam that was changed if (type == "paramchange") this.actionParamChanged(action, event.target, event.value); // for add/remove, event.value == actionParam added or removed if (type == "paramadd") this.actionParamAdded(action, event.value); if (type == "paramremove") this.actionParamRemoved(action, event.value); }, // private actionInvoked: function(action, returnData) { this.trigger("actioninvoke", returnData, action); // signal parent svidget.signalActionInvoked(action, returnData); }, // private // eventValue ex = { property: "binding", value: bindValue } actionChanged: function(action, eventValue) { this.trigger("actionchange", eventValue, action); // signal parent svidget.signalActionChanged(action, eventValue); }, // private actionParamChanged: function(action, actionParam, eventValue) { this.trigger("actionparamchange", eventValue, actionParam); // signal parent svidget.<API key>(actionParam, action, eventValue); }, // private actionParamAdded: function(action, actionParam) { this.trigger("actionparamadd", actionParam, action); // signal parent svidget.<API key>(actionParam, action.name()); }, // private actionParamRemoved: function(action, actionParamName) { this.trigger("actionparamremove", actionParamName, action); // signal parent svidget.<API key>(actionParamName, action.name()); }, // REGION: Events /** * Gets a collection of all events in the widget, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * events(0) * events("somethingHappened") * @method * @memberof Svidget.Widget.prototype * @param {object} [selector] - * @returns {Svidget.EventDescCollection} - A collection based on the selector, or the entire collection. */ events: function(selector) { var col = this.getset("events"); return this.select(col, selector); }, /** * Gets the event object based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * event(0) * event("somethingHappened") * @method * @memberof Svidget.Widget.prototype * @param {object} selector - The index or ID of the event. * @returns {Svidget.EventDesc} - The event based on the selector. If selector is invalid, null is returned. */ event: function(selector) { var col = this.getset("events"); var item = this.selectFirst(col, selector); return item; }, /** * Adds an EventDesc object to the widget. If a duplicate name is supplied the EventDesc will fail to add. * Examples: * addEvent("somethingHappened", { description: "An event for that." }) * @method * @memberof Svidget.Widget.prototype * @param {string} name - The name of the EventDesc to add. * @param {object} [options] - The options used to contruct the EventDesc. Example: { enabled: true, description: "An event" } * @returns {Svidget.Action} - The EventDesc that was added, or null if EventDesc failed to add. */ addEvent: function(nameOrObject, options) { return this.events().add(nameOrObject, options, this); }, /** * Removes an EventDesc object from the widget. * Examples: * removeEvent("somethingHappened") * @method * @memberof Svidget.Widget.prototype * @param {string} name - The name of the EventDesc to remove. * @returns {boolean} - True if the EventDesc was successfully removed, false otherwise. */ removeEvent: function(name) { return this.events().remove(name); }, // private // handle event added eventAdded: function(eventDesc) { Svidget.log("widget: event added: " + eventDesc.name()); // trigger event // event.value = event this.trigger("eventadd", eventDesc); // signal parent svidget.signalEventAdded(eventDesc); }, // private // handle event removed eventRemoved: function(eventDesc) { Svidget.log("widget: event removed: " + eventDesc.name()); // trigger event // event.value = event name this.trigger("eventremove", eventDesc.name()); // signal parent svidget.signalEventRemoved(eventDesc.name()); }, // internal, called from eventdesc.EventPrototype eventBubble: function(type, event, eventDesc) { if (type == "trigger") this.eventTrigger(eventDesc, event); if (type == "change") this.eventChanged(eventDesc, event.value); }, // private eventTrigger: function(eventDesc, event) { Svidget.log("widget: event trigger: " + eventDesc.name()); this.trigger("eventtrigger", event.value, eventDesc); // FYI: event.target == eventDesc svidget.<API key>(event.target, event.value); }, // private eventChanged: function(eventDesc, eventValue) { this.trigger("eventchange", eventValue, eventDesc); // signal parent svidget.signalEventChanged(eventDesc, eventValue); }, // REGION: Properties /** * Gets the widget ID. * @method * @memberof Svidget.Widget.prototype * @returns {string} - The widget ID as a string. */ id: function() { return this.getset("id"); }, /** * Gets or sets whether the widget is enabled. * @method * @memberof Svidget.Widget.prototype * @param {Boolean} [val] - Sets the enabled state when specified. * @returns {Boolean} - The enabled state, when nothing is passed, or true/false based on if setting is succeeded or failed. */ enabled: function(val) { var res = this.getset("enabled", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire "changed" event if (this.trigger) this.trigger("change", { property: "enabled", value: val }); return true; }, /** * Gets whether the widget is connected to a parent page. * If true, it means the page initialized the widget and is listening for events. * If false, it means the widget was loaded independently and/or outside of of the control of the framework (standalone mode). * @method * @memberof Svidget.Widget.prototype * @returns {Boolean} - Whether the widget is connected */ connected: function() { return this.getset("connected"); }, /** * Gets whether the widget has started. This is true once the DOM is loaded. * @method * @memberof Svidget.Widget.prototype * @returns {boolean} - Whether the widget is started. */ started: function() { var val = this.getset("started"); return val; }, // REGION: Communication /** * Serializes the Widget object for transport across a window boundary. * @method * @memberof Svidget.Widget.prototype * @returns {boolean} - A generic serialized object representing the Widget. */ // todo: rename to serialize() toTransport: function() { var transport = { id: this.id(), enabled: this.enabled(), params: this.toParamsTransport(), actions: this.toActionsTransport(), events: this.toEventsTransport() }; return transport; }, // private toParamsTransport: function() { var col = this.params(); var ps = col.select(function(p) { return p.toTransport(); }).toArray(); return ps; }, // private toActionsTransport: function() { var col = this.actions(); var acs = col.select(function(a) { return a.toTransport(); }).toArray(); return acs; }, // private toEventsTransport: function() { var col = this.events(); var evs = col.select(function(e) { return e.toTransport(); }).toArray(); return evs; }, /** * Adds an event handler for the "paramadd" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onparamadd: function(data, name, handler) { return this.on("paramadd", data, name, handler); }, ondeclaredparamadd: function(handler) { return this.onparamadd(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "paramadd" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offparamadd: function(handlerOrName) { return this.off("paramadd", handlerOrName); }, offdeclaredparamadd: function() { return this.offparamadd(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "paramremove" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onparamremove: function(data, name, handler) { return this.on("paramremove", data, name, handler); }, <API key>: function(handler) { return this.onparamremove(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "paramremove" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offparamremove: function(handlerOrName) { return this.off("paramremove", handlerOrName); }, <API key>: function() { return this.offparamremove(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "actionadd" event. * @method * @action {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @action {string} [name] - The name of the handler. Useful when removing the handler for the event. * @action {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onactionadd: function(data, name, handler) { return this.on("actionadd", data, name, handler); }, ondeclaredactionadd: function(handler) { return this.onactionadd(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "actionadd" event. * @method * @action {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offactionadd: function(handlerOrName) { return this.off("actionadd", handlerOrName); }, <API key>: function() { return this.offactionadd(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "actionremove" event. * @method * @action {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @action {string} [name] - The name of the handler. Useful when removing the handler for the event. * @action {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onactionremove: function(data, name, handler) { return this.on("actionremove", data, name, handler); }, <API key>: function(handler) { return this.onactionremove(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "actionremove" event. * @method * @action {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offactionremove: function(handlerOrName) { return this.off("actionremove", handlerOrName); }, <API key>: function() { return this.offactionremove(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "eventadd" event. * @method * @event {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @event {string} [name] - The name of the handler. Useful when removing the handler for the event. * @event {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ oneventadd: function(data, name, handler) { return this.on("eventadd", data, name, handler); }, ondeclaredeventadd: function(handler) { return this.oneventadd(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "eventadd" event. * @method * @event {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offeventadd: function(handlerOrName) { return this.off("eventadd", handlerOrName); }, offdeclaredeventadd: function() { return this.offeventadd(Svidget.declaredHandlerName); }, /** * Adds an event handler for the "eventremove" event. * @method * @event {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @event {string} [name] - The name of the handler. Useful when removing the handler for the event. * @event {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ oneventremove: function(data, name, handler) { return this.on("eventremove", data, name, handler); }, <API key>: function(handler) { return this.oneventremove(null, Svidget.declaredHandlerName, handler); }, /** * Removes an event handler for the "eventremove" event. * @method * @event {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offeventremove: function(handlerOrName) { return this.off("eventremove", handlerOrName); }, <API key>: function() { return this.offeventremove(Svidget.declaredHandlerName); }, // overrides /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.Widget { id: "' + this.id() + '" }]'; } }; Svidget.Widget.eventTypes = [ "change", "paramvaluechange", "paramchange", "paramadd", "paramremove", "actioninvoke", "actionchange", "actionadd", "actionremove", "eventtrigger", "eventadd", "eventremove" ]; Svidget.extend(Svidget.Widget, Svidget.ObjectPrototype); Svidget.extend(Svidget.Widget, new Svidget.EventPrototype(Svidget.Widget.eventTypes)); /** * Encapsulates logic for a proxy object that is meant to shadow a concrete one. * @class * @abstract * @mixes ObjectPrototype * @memberof Svidget.Svidget * @param {object} parent - The parent to this object. Usually a Svidget.WidgetReference instance. * @param {object} options - An object containing values to initialize properties. Example: { enabled: true, description: "An event" } * @param {Array} propList - An array of all properties that the underlying object exposes to the proxy. * @param {Array} writePropList - An array of all writable properties that the underlying object exposes to the proxy. A subset of propList. * @param {Array} eventList - An array of all event types that this proxy listens for and/or response to based on the underlying object. */ Svidget.Proxy = function(parent, options, propList, writePropList, eventList) { this.__type = "Svidget.Proxy"; var that = this; options = options || {}; // convert to collections var propCol = new Svidget.Collection(Svidget.isArray(propList) ? propList : null); var writePropCol = new Svidget.Collection(Svidget.isArray(writePropList) ? writePropList : null); // filter so that writable properties are also contained in all properties writePropCol = writePropCol.where(function(i) { return propCol.contains(i); }); // private fields var privates = { writable: writePropCol.toArray(), propertyChangeFuncs: new Svidget.Collection(), eventContainer: new Svidget.EventContainer(eventList, that), parent: parent, connected: options.connected == null ? true : !!options.connected }; // private accessors this.setup(privates); // copy property values to privates for (var p in options) { if (privates[p] === undefined) { privates[p] = options[p]; } } // load functions for each property onto this object for (var i = 0; i < propCol.length; i++) { var prop = propCol[i] + ""; if (prop.length > 0) { this[prop] = buildPropFunc(prop); } } function buildPropFunc(prop) { return function(val) { return this.getsetProp(prop, val); }; } }; Svidget.Proxy.prototype = { /** * Gets the parent object. * @method * @returns {Svidget.WidgetReference} */ parent: function() { var res = this.getPrivate("parent"); return res; }, propertyChangeFuncs: function() { return this.getPrivate("propertyChangeFuncs"); }, /** * Gets whether the proxy is connected to its underlying widget counterpart. * @method * @returns {boolean} */ connected: function(val) { return this.getPrivate("connected"); }, // private // this is invoked when attempting to set a property value on the proxy itself // this in turn notifies the parent, which in turn notifies the widget getsetProp: function(prop, val) { var res = this.getset(prop, val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; // fire propertyChange event // this.<API key>(prop, val); // obsolete this.<API key>(prop, val); return true; }, /** * @abstract */ <API key>: function(name, val) {}, <API key>: function(name, val) { // notifies root that property change, sends it to widget // invoke func(this, name, val) var funcList = this.propertyChangeFuncs(); var that = this; funcList.each(function(func) { func(that, name, val); }); }, // private // this is invoked when the widget communicates that a property was changed <API key>: function(name, val) { // notifies this proxy that property changed on widget if (name == null) return; // update value to match source this.getset(name, val); // trigger change event this.triggerFromWidget("change", { property: name, value: val }, this); }, // internal // refreshes the proxy object with values from the widget refreshProperties: function(propObj) { for (var name in propObj) { var item = this.getPrivate(name); if (item != null) { this.setPrivate(name, propObj[name]); } } }, /** * Gets whether the proxy object is connected to its underlying object. * @method * @returns {boolean} */ connect: function() { this.setPrivate("connected", true); }, // obsolete (9/1/2014) // use regular events ("change", "paramchange") onPropertyChange: function(func) { var funcList = this.propertyChangeFuncs(); if (!typeof func === "function") return false; funcList.add(func); return true; }, // obsolete (9/1/2014) // use regular events ("change", "paramchange") offPropertyChange: function(func) { var funcList = this.propertyChangeFuncs(); return funcList.remove(func); }, eventContainer: function() { return this.getPrivate("eventContainer"); }, /** * Registers an event handler for the proxy object. * @method * @param {string} type - The event type i.e. "change". * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ on: function(type, data, name, handler) { this.eventContainer().on(type, data, name, handler); }, /** * Unregisters an event handler for the proxy object. * @method * @memberof Svidget.Root.prototype * @param {string} type - The event type i.e. "change". * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ off: function(type, handlerOrName) { this.eventContainer().off(type, handlerOrName); }, // Note: no access to trigger() object events here, only from widget // this is invoked from the widget to signal that the event was triggered triggerFromWidget: function(type, value, originalTarget) { this.eventContainer().trigger(type, value, originalTarget); }, <API key>: function(types, bubbleTarget, callback) { this.eventContainer().<API key>(types, bubbleTarget, callback); } }; Svidget.extend(Svidget.Proxy, Svidget.ObjectPrototype); /** * Represents a proxy to an Action object. * @class * @augments Svidget.Proxy * @memberof Svidget.Svidget * @param {string} name - The name of the action. * @param {object} options - The options for the action. Example: { enabled: true, description: "An action" } * @param {Svidget.WidgetReference} parent - The widget reference instance that is the parent for this action proxy. */ Svidget.ActionProxy = function(name, options, parent) { var that = this; var valueObj = { name: name, params: new Svidget.<API key>([], that) }; options = options || {}; // copy property values to privates for (var p in options) { if (valueObj[p] === undefined) valueObj[p] = options[p]; } if (parent) parent = parent instanceof Svidget.WidgetReference ? parent : null; // parent can only be a WidgetReference Svidget.Proxy.apply(this, [ parent, valueObj, Svidget.Action.allProxyProperties, Svidget.Action.<API key> ]); this.__type = "Svidget.ActionProxy"; // register callback from action to widget, for event bubbles this.<API key>(Svidget.Action.eventTypes, parent, parent.actionProxyBubble); // add/remove event handlers for params this.<API key>(valueObj.params, that.paramAdded, that.paramRemoved); }; Svidget.ActionProxy.prototype = new Svidget.Proxy(); Svidget.extend(Svidget.ActionProxy, { /** * Invokes the action. The params passes in will be passed to the action params in order. * @method * @param {...object} args - The arguments that correspond to action params. * @returns {boolean} - True if invoke succeeds. */ invoke: function() { // build args obj from arguments if (!this.canInvoke()) return false; var args = Svidget.array(arguments); svidget.signalActionInvoke(this.parent(), this, args); return true; }, canInvoke: function() { return this.getset("external"); }, invokeFromWidget: function(returnVal) { this.triggerFromWidget("invoke", { returnValue: returnVal }, this); }, /** * Gets a collection of all ActionParamProxy objects, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * params(0) * params("color") * @method * @param {(string|number)} [selector] - The selector string or integer. * @returns {Svidget.<API key>} - A collection based on the selector, or the entire collection. */ params: function(selector) { var col = this.getset("params"); return this.select(col, selector); }, /** * Gets the ActionParamProxy based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * param(0) * param("color") * @method * @param {(string|number)} selector - The index or ID of the param. * @returns {Svidget.ActionParam} - The ActionParamProxy based on the selector. If selector is invalid, null is returned. */ param: function(selector) { var col = this.getset("params"); var item = this.selectFirst(col, selector); return item; }, // internal addParam: function(nameOrObject, options) { return this.params().add(nameOrObject, options, this); }, // internal removeParam: function(name) { return this.params().remove(name); }, paramProxyBubble: function(type, event, param) { if (type == "change") this.paramChanged(param, event.value); }, // private // eventValue ex = { property: "binding" } paramChanged: function(param, eventValue) { this.triggerFromWidget("paramchange", eventValue, param); }, // handle param added paramAdded: function(param) { this.triggerFromWidget("paramadd", param); }, // private // handle param removed paramRemoved: function(param) { this.triggerFromWidget("paramremove", param.name()); }, /** * Adds an event handler for the "change" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onchange: function(data, name, handler) { return this.on("change", data, name, handler); }, /** * Removes an event handler for the "change" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offchange: function(handlerOrName) { this.off("change", handlerOrName); }, /** * Adds an event handler for the "invoke" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ oninvoke: function(data, name, handler) { return this.on("invoke", data, name, handler); }, /** * Removes an event handler for the "invoke" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offinvoke: function(handlerOrName) { return this.off("invoke", handlerOrName); }, /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.ActionProxy { name: "' + this.name + '" }]'; } }, true); /** * Represents a collection of ActionProxy objects. * @class * @augments Svidget.ObjectCollection * @memberof Svidget.Svidget * @param {array} array - An array of ActionProxy objects. * @param {Svidget.WidgetReference} parent - The WidgetReference instance that is the parent for this ActionParamProxy collection. */ Svidget.<API key> = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.ActionProxy ]); this.__type = "Svidget.<API key>"; var that = this; this.parent = parent; }; Svidget.<API key>.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.<API key>, { create: function(name, options, parent) { // create param // call addObject if (name == null || !typeof name === "string") return null; // ensure no other action exists in the collection by that name if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.ActionProxy(name, options, parent); //this.push(obj); return obj; } }, true); /** * Represents a proxy to an ActionParam object. * @class * @augments Svidget.Proxy * @memberof Svidget * @param {string} name - The name of the action param. * @param {object} options - The options for the action param. Example: { type: "string", subtype: "regex", description: "An action param" } * @param {Svidget.WidgetReference} parent - The widget reference instance that is the parent for this action param proxy. */ Svidget.ActionParamProxy = function(name, options, parent) { var that = this; var valueObj = { name: name }; options = options || {}; // copy property values to privates for (var p in options) { if (valueObj[p] === undefined) valueObj[p] = options[p]; } if (parent) parent = parent instanceof Svidget.ActionProxy ? parent : null; // parent can only be a WidgetReference Svidget.Proxy.apply(this, [ parent, valueObj, Svidget.ActionParam.allProxyProperties, Svidget.ActionParam.<API key> ]); this.__type = "Svidget.ActionParamProxy"; // register callback from action to widget, for event bubbles this.<API key>(Svidget.ActionParam.eventTypes, parent, parent.paramProxyBubble); }; Svidget.ActionParamProxy.prototype = new Svidget.Proxy(); Svidget.extend(Svidget.ActionParamProxy, { /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.ActionParamProxy { name: "' + this.name + '" }]'; } }, true); /** * Represents a collection of ActionParamProxy objects. * @class * @augments Svidget.ObjectCollection * @memberof Svidget.Svidget * @param {array} array - An array of ActionParamProxy objects. * @param {Svidget.ActionProxy} parent - The ActionProxy instance that is the parent for this ActionParamProxy collection. */ Svidget.<API key> = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.ActionParamProxy ]); this.__type = "Svidget.<API key>"; var that = this; this.parent = parent; }; Svidget.<API key>.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.<API key>, { create: function(name, options, parent) { if (name == null || !typeof name === "string") return null; // ensure no duplicates with same name, return null if true if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.ActionParamProxy(name, options, parent); return obj; } }, true); /** * Represents a proxy to an EventDesc object. * @class * @augments Svidget.Proxy * @memberof Svidget * @param {string} name - The name of the event. * @param {object} options - The options for the event. Example: { enabled: true, description: "An event" } * @param {Svidget.WidgetReference} parent - The widget reference instance that is the parent for this event proxy. */ Svidget.EventDescProxy = function(name, options, parent) { var eventName = "trigger"; var that = this; var valueObj = { name: name, eventName: eventName }; options = options || {}; // copy property values to privates for (var p in options) { if (valueObj[p] === undefined) valueObj[p] = options[p]; } if (parent) parent = parent instanceof Svidget.WidgetReference ? parent : null; // parent can only be a WidgetReference Svidget.Proxy.apply(this, [ parent, valueObj, Svidget.EventDesc.allProxyProperties, Svidget.EventDesc.<API key> ]); this.__type = "Svidget.EventDescProxy"; // register callback from action to widget, for event bubbles this.<API key>(Svidget.EventDesc.eventTypes, parent, parent.eventProxyBubble); }; Svidget.EventDescProxy.prototype = new Svidget.Proxy(); Svidget.extend(Svidget.EventDescProxy, { triggerEventName: function() { return this.getPrivate("eventName"); }, /** * Registers an event handler for the EventDescProxy object. * @method * @param {string} [type] - The event type i.e. "change". If not specified it is assumed it is for the event itself. * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ on: function(type, data, name, handler) { // if type is function, then assume type not passes so use default event name if (Svidget.isFunction(type)) { handler = type; type = this.triggerEventName(); } this.eventContainer().on(type, data, name, handler); }, /** * Adds an event handler for the "trigger" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ ontrigger: function(data, name, handler) { this.eventContainer().on(this.eventName(), data, name, handler); }, /** * Unregisters an event handler for the EventDescProxy object. * @method * @param {string} [type] - The event type i.e. "change", "paramremove". If not specified it is assumed it is for the event itself. * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ off: function(type, handlerOrName) { // if type is function, then assume type not passes so use default event name if (Svidget.isFunction(type)) { handlerOrName = type; type = this.triggerEventName(); } this.eventContainer().off(type, handlerOrName); }, /** * Removes an event handler for the "trigger" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offtrigger: function(handlerOrName) { this.eventContainer().off(this.eventName(), handlerOrName); }, /** * Adds an event handler for the "change" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onchange: function(data, name, handler) { return this.on("change", data, name, handler); }, /** * Removes an event handler for the "change" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offchange: function(handlerOrName) { this.off("change", handlerOrName); }, /** * Triggers the event for the EventDesc object. Event must be external. * @method * @param {object} value - The value to set to the Event.value property. */ trigger: function(value) { // generally an event wouldn't be triggerable from outside, but we leave in the ability for testing purposes if (!this.canTrigger()) return false; svidget.signalEventTrigger(this.parent(), this, value); return true; }, canTrigger: function() { return this.getset("external"); }, // overwrites: Svidget.Proxy.triggerFromWidget // this is invoked from the widget to signal that the event was triggered <API key>: function(value) { this.eventContainer().trigger(this.triggerEventName(), value); }, // overrides /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.EventDescProxy { name: "' + this.name + '" }]'; } }, true); /** * Represents a collection of EventDescProxy objects. * @constructor * @augments ObjectCollection * @memberof Svidget * @param {array} array - An array of EventDescProxy objects. * @param {Svidget.WidgetReference} parent - The WidgetReference instance that is the parent for this EventDescProxy collection. */ Svidget.<API key> = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.EventDescProxy ]); this.__type = "Svidget.<API key>"; var that = this; this.parent = parent; }; Svidget.<API key>.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.<API key>, { create: function(name, options, parent) { if (name == null || !typeof name === "string") return null; // ensure no other parameter exists in the collection by that name if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.EventDescProxy(name, options, parent); return obj; } }, true); /** * Represents a proxy to an Param object. * @class * @augments Svidget.Proxy * @memberof Svidget * @param {string} name - The name of the param proxy. * @param {object} value - The value for the param proxy. * @param {object} options - The options for the param proxy. Example: { enabled: true, description: "An event" } * @param {Svidget.WidgetReference} parent - The widget reference that is the parent for this param. */ Svidget.ParamProxy = function(name, value, options, parent) { var valueObj = { name: name, value: value }; options = options || {}; // copy property values to privates for (var p in options) { valueObj[p] = options[p]; } if (parent) parent = parent instanceof Svidget.WidgetReference ? parent : null; // parent can only be a WidgetReference Svidget.Proxy.apply(this, [ parent, valueObj, Svidget.Param.allProxyProperties, Svidget.Param.<API key> ]); this.__type = "Svidget.ParamProxy"; // register callback from action to widget, for event bubbles this.<API key>(Svidget.Param.eventTypes, parent, parent.paramProxyBubble); }; Svidget.ParamProxy.prototype = new Svidget.Proxy(); Svidget.extend(Svidget.ParamProxy, { // overrides <API key>: function(name, val) { if (name == "value") { svidget.<API key>(this.parent(), this, "param", name, val); } }, // private // this is invoked when the widget communicates that a property was changed notifyValueChange: function(val) { // notifies this proxy that property changed on widget // update value to match source this.getset("value", val); // trigger change event this.triggerFromWidget("valuechange", { value: val }, this); // deprecated: set is the official event this.triggerFromWidget("set", { value: val }, this); }, /** * Adds an event handler for the "change" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onchange: function(data, name, handler) { return this.on("change", data, name, handler); }, /** * Removes an event handler for the "change" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offchange: function(handlerOrName) { this.off("change", handlerOrName); }, /** * Adds an event handler for the "set" event. * @method * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ onset: function(data, name, handler) { return this.on("set", data, name, handler); }, /** * Removes an event handler for the "set" event. * @method * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ offset: function(handlerOrName) { return this.off("set", handlerOrName); }, /** * Gets a string representation of this object. * @method * @returns {string} */ toString: function() { return '[Svidget.ParamProxy { name: "' + this.name + '" }]'; } }, true); /** * Represents a collection of ParamProxy objects. * @constructor * @augments ObjectCollection * @memberof Svidget * @param {array} array - An array of ParamProxy objects. * @param {Svidget.WidgetReference} parent - The WidgetReference instance that is the parent for this ParamProxy collection. */ Svidget.<API key> = function(array, parent) { Svidget.ObjectCollection.apply(this, [ array, Svidget.ParamProxy ]); this.__type = "Svidget.<API key>"; var that = this; this.parent = parent; }; Svidget.<API key>.prototype = new Svidget.ObjectCollection(); Svidget.extend(Svidget.<API key>, { create: function(name, value, options, parent) { // create param // call addObject if (name == null || !typeof name === "string") return null; // ensure no other parameter exists in the collection by that name if (this.getByName(name) != null) return null; // create obj var obj = new Svidget.ParamProxy(name, value, options, parent); //this.push(obj); return obj; } }, true); /** * Represents a reference to a widget from the page level. * @constructor * @mixes ObjectPrototype * @memberof Svidget * @param {string} id - The id of the widget this object represents. * @param {object} paramValueObj - The initializing param object. These are usually parsed from the <object> tag. * @param {HTMLElement} declaringElement - The HTML element that was used to declare the widget on the page. This is the <object> element. * @param {HTMLElement} [element] - The element that contains the actual widget. This can be either an <object> or <iframe> element. * @param {boolean} [connected] - Whether the reference is connected to the underlying widget. If false, it passes the params to the widgets then ceases any further communications with it. * @param {boolean} [crossdomain] - Whether the widget is hosted on another domain. This is a hint value to optimize setting up when it is known in advance that the widget is cross domain. */ Svidget.WidgetReference = function(id, paramValueObj, declaringElement, element, connected, crossdomain) { this.__type = "Svidget.WidgetReference"; var that = this; // privates var privates = new function() { this.writable = [ "enabled", "started", "populated" ]; this.params = new Svidget.<API key>([], that); this.actions = new Svidget.<API key>([], that); this.events = new Svidget.<API key>([], that); this.eventContainer = new Svidget.EventContainer(Svidget.Widget.eventTypes, that); this.paramValues = paramValueObj; this.enabled = true; this.started = false; this.populated = false; this.connected = !!connected; // whether widget is connected/disconnected this.crossdomain = !!crossdomain; // whether widget in forced crossdomain mode this.state = "declared"; this.id = id; this.element = element; this.declaringElement = declaringElement; this.url = declaringElement.getAttribute("data"); }(); // private accessors this.setup(privates); this.setElement = function(ele) { if (privates.element != null) return false; if (!Svidget.DOM.isElement(ele)) return false; privates.element = ele; // self-destructing set accessor, todo: delete too? this.setElement = null; }, // initialize params from <object> tag on page, these will be replaced when the widget updates the values and sends them back to the page <API key>.call(that, paramValueObj); // set an instance to this on declaring element declaringElement.widgetReference = this; // wire events for params add/remove and bubbles this.<API key>(privates.params, that.paramProxyAdded, that.paramProxyRemoved); // wire events for actions add/remove and bubbles this.<API key>(privates.actions, that.actionProxyAdded, that.actionProxyRemoved); // wire events for events add/remove this.<API key>(privates.events, that.eventProxyAdded, that.eventProxyRemoved); function <API key>(paramValueObj) { if (paramValueObj == null) return; for (var name in paramValueObj) { this.addParamProxy(name, paramValueObj[name], { connected: false }); } } }; Svidget.WidgetReference.prototype = { /** * Gets the widget ID. * @method * @memberof Svidget.WidgetReference.prototype * @returns {string} - The widget ID as a string. */ id: function() { var id = this.getset("id"); return id; }, name: function() { return this.id(); }, /** * Gets whether the widget is enabled. * @method * @memberof Svidget.WidgetReference.prototype * @returns {boolean} - The enabled state. */ enabled: function() { var enabled = this.getset("enabled"); return enabled; }, /** * Gets the url to the widget. * @method * @memberof Svidget.WidgetReference.prototype * @returns {string} */ url: function() { var url = this.getset("url"); return url; }, /** * Gets the html element that contains the widget. This is either <object> or <iframe>. * @method * @memberof Svidget.WidgetReference.prototype * @returns {HTMLElement} */ element: function() { var ele = this.getset("element"); return ele; }, /** * Gets the declaring html element that contains the widget. This is the <object> element, or null if declared programatically. * @method * @memberof Svidget.WidgetReference.prototype * @returns {HTMLElement} */ declaringElement: function() { var ele = this.getset("declaringElement"); return ele; }, /** * Gets the svidget global object for the widget. Only available for same domain widgets. * @method * @memberof Svidget.WidgetReference.prototype * @returns {object} */ root: function() { // gets access to widget's root object, if same domain if (this.isCrossDomain()) { return null; } var doc = this.document(); var win = doc.parentWindow || doc.defaultView; //var f = window.frames[0]; // ele = this.element(); //var s = win.$getSvidget(); // note: is some browsers, this may not be available until its DOM is loaded return win.svidget; }, /** * Gets the window object for the widget. Only available for same domain widgets. * @method * @memberof Svidget.WidgetReference.prototype * @returns {Window} */ window: function() { // gets access to widget's window object, if different domain var ele = this.element(); if (ele == null) return null; // note: only FF supports <object>.contentWindow // ele is usually a <iframe> return ele.contentWindow; }, /** * Gets the document object for the widget. Only available for same domain widgets. * @method * @memberof Svidget.WidgetReference.prototype * @returns {HTMLDocument} */ document: function() { var ele = this.element(); return Svidget.DOM.getDocument(ele); }, /** * Gets whether this widget reference is connected to its underlying widget. If false, then the widget is cut off from the page. * @method * @memberof Svidget.WidgetReference.prototype * @returns {HTMLDocument} */ connected: function(val) { var res = this.getset("connected", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; return true; }, /** * Gets whether this widget reference has specified that it prefers to connect to the underlying widget as a cross-domain widget, irregardless if it is actually cross-domain or not. * @method * @memberof Svidget.WidgetReference.prototype * @param {boolean} - Sets the property. * @returns {boolean} - True/false if crossdomain, or if setting then true/false if set succeeded. */ crossdomain: function(val) { var res = this.getset("crossdomain", val); // if undefined its a get so return value, if res is false then set failed if (val === undefined || !!!res) return res; return true; }, /** * Gets a collection of all ParamProxy objects in the widget reference, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * params(0) * params("color") * @method * @memberof Svidget.WidgetReference.prototype * @param {object} [selector] - The selector string or integer. * @returns {Svidget.<API key>} - A collection based on the selector, or the entire collection. */ params: function(selector) { var col = this.getset("params"); return this.select(col, selector); }, /** * Gets the ParamProxy based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * param(0) * param("color") * @method * @memberof Svidget.WidgetReference.prototype * @param {object} selector - The index or ID of the param. * @returns {Svidget.ParamProxy} - The ParamProxy based on the selector. If selector is invalid, null is returned. */ param: function(selector) { var col = this.getset("params"); var item = this.selectFirst(col, selector); return item; }, /** * Gets a collection of all ActionProxy objects in the widget reference, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * actions(0) * actions("doSomething") * @method * @memberof Svidget.WidgetReference.prototype * @param {object} [selector] - The selector string or integer. * @returns {Svidget.<API key>} - A collection based on the selector, or the entire collection. */ actions: function(selector) { var col = this.getset("actions"); return this.select(col, selector); }, /** * Gets the ActionProxy based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * action(1) * action("doSomething") * @method * @memberof Svidget.WidgetReference.prototype * @param {object} selector - The index or ID of the param. * @returns {Svidget.ActionProxy} - The ActionProxy based on the selector. If selector is invalid, null is returned. */ action: function(selector) { //var item = this.actions(selector).first(); var col = this.getset("actions"); var item = this.selectFirst(col, selector); return item; }, /** * Gets a collection of all EventDescProxy objects in the widget reference, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * events(0) * events("somethingHappened") * @method * @memberof Svidget.WidgetReference.prototype * @param {object} [selector] - The selector string or integer. * @returns {Svidget.<API key>} - A collection based on the selector, or the entire collection. */ events: function(selector) { var col = this.getset("events"); return this.select(col, selector); }, /** * Gets the EventDescProxy based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * events(0) * events("somethingHappened") * @method * @memberof Svidget.WidgetReference.prototype * @param {object} selector - The index or ID of the param. * @returns {Svidget.EventDescProxy} - The EventDescProxy based on the selector. If selector is invalid, null is returned. */ event: function(selector) { var col = this.getset("events"); var item = this.selectFirst(col, selector); return item; }, // internal paramValues: function() { var val = this.getset("paramValues"); return val; }, // internal addParamProxy: function(nameOrObject, value, options) { return this.params().add(nameOrObject, value, options, this); }, // internal removeParamProxy: function(name) { return this.params().remove(name); }, // internal // adds or updates the param proxy refreshParamProxy: function(name, value, options) { var p = this.param(name); if (p == null) return this.params().add(nameOrObject, value, options, this); else { p.refreshProperties(options); return p; } }, // internal // handle param added paramProxyAdded: function(param) { // raise event //alert('param added'); Svidget.log("page: param proxy added: " + param.name()); // trigger event this.triggerFromWidget("paramadd", param); }, // internal // handle param removed paramProxyRemoved: function(param) { // raise event //alert('param removed'); Svidget.log("page: param proxy removed: " + param.name()); // trigger event this.triggerFromWidget("paramremove", param.name()); }, // internal // called from ParamProxy paramProxyBubble: function(type, event, param) { Svidget.log("page: param proxy bubble: " + param.name()); if (type == "change") this.paramProxyChanged(param, event.value); if (type == "valuechange") this.<API key>(param, event.value); }, // private // eventValue ex = { property: "binding", value: bindValue } paramProxyChanged: function(param, eventValue) { Svidget.log("page: param proxy change: " + param.name()); this.triggerFromWidget("paramchange", eventValue, param); }, // private // eventValue ex = { value: "3" } <API key>: function(param, eventValue) { Svidget.log("page: param proxy value change: " + param.name()); this.triggerFromWidget("paramvaluechange", eventValue, param); }, // internal addActionProxy: function(nameOrObject, options) { return this.actions().add(nameOrObject, options, this); }, // internal removeActionProxy: function(name) { return this.actions().remove(name); }, // internal // handle param added actionProxyAdded: function(action) { // raise event Svidget.log("page: action proxy added: " + action.name()); // trigger event this.triggerFromWidget("actionadd", action); }, // internal // handle param removed actionProxyRemoved: function(action) { Svidget.log("page: action proxy removed: " + action.name()); // trigger event this.triggerFromWidget("actionremove", action.name()); }, // internal // called from action actionProxyBubble: function(type, event, action) { Svidget.log("page: action proxy bubble: " + action.name()); if (type == "invoke") this.actionProxyInvoked(action, event.value); if (type == "change") this.actionProxyChanged(action, event.value); // event.target is actionParam that was changed if (type == "paramchange") this.<API key>(action, event.target, event.value); // for add/remove, event.value == actionParam added or removed if (type == "paramadd") this.<API key>(action, event.value); if (type == "paramremove") this.<API key>(action, event.value); }, // private actionProxyInvoked: function(action, eventValue) { this.triggerFromWidget("actioninvoke", eventValue, action); }, // private actionProxyChanged: function(action, eventValue) { this.triggerFromWidget("actionchange", eventValue, action); }, // private <API key>: function(action, actionParam) { this.triggerFromWidget("actionparamadd", actionParam, action); }, // private <API key>: function(action, actionParamName) { this.triggerFromWidget("actionparamremove", actionParamName, action); }, // private <API key>: function(action, actionParam, eventValue) { this.triggerFromWidget("actionparamchange", eventValue, actionParam); }, // internal addEventProxy: function(nameOrObject, options) { return this.events().add(nameOrObject, options, this); }, // internal removeEventProxy: function(name) { return this.events().remove(name); }, // internal // handle param added eventProxyAdded: function(ev) { Svidget.log("page: event proxy added: " + ev.name()); // trigger event this.triggerFromWidget("eventadd", ev); }, // internal // handle param removed eventProxyRemoved: function(ev) { Svidget.log("page: event proxy removed: " + ev.name()); // trigger event this.triggerFromWidget("eventremove", ev.name()); }, // internal, called from eventdescproxy eventProxyBubble: function(type, event, eventDesc) { Svidget.log("page: event proxy bubble: " + eventDesc.name()); if (type == "trigger") this.eventProxyTriggered(eventDesc, event); if (type == "change") this.eventProxyChanged(eventDesc, event.value); }, // private eventProxyTriggered: function(eventDesc, event) { Svidget.log("page: event proxy trigger: " + eventDesc.name()); this.triggerFromWidget("eventtrigger", event.value, eventDesc); }, // private eventProxyChanged: function(eventDesc, eventValue) { Svidget.log("page: event proxy change: " + eventDesc.name()); this.triggerFromWidget("eventchange", eventValue, eventDesc); }, eventContainer: function() { return this.getPrivate("eventContainer"); }, /** * Registers an event handler for the WidgetReference. * @method * @memberof Svidget.WidgetReference.prototype * @param {string} type - The event type i.e. "change", "paramremove". * @param {object} [data] - Arbirary data to initialize Event object with when event is triggered. * @param {string} [name] - The name of the handler. Useful when removing the handler for the event. * @param {Function} handler - The event handler. * @returns {boolean} - True if the event handler was successfully added. */ on: function(type, data, name, handler) { this.eventContainer().on(type, data, name, handler); }, /** * Unregisters an event handler for the WidgetReference. * @method * @memberof Svidget.WidgetReference.prototype * @param {string} type - The event type i.e. "change", "paramremove". * @param {(Function|string)} handlerOrName - The handler function and/or the handler name used when calling on(). * @returns {boolean} - True if the event handler was successfully removed. */ off: function(type, handlerOrName) { this.eventContainer().off(type, handlerOrName); }, // internal // Note: no access to trigger() object events here, only from widget // this is invoked from the widget to signal that the event was triggered triggerFromWidget: function(type, value, originalTarget) { this.eventContainer().trigger(type, value, originalTarget); }, hasElement: function() { return this.element() != null; }, // True if element is valid <object> or <iframe> and part of DOM. isAttached: function() { var ele = this.element(); return ele != null && ele.parentNode != null; }, isCrossDomain: function() { return this.element() !== this.declaringElement(); }, started: function() { var val = this.getset("started"); return val; }, populated: function() { var val = this.getset("populated"); return val; }, // internal // indicates from the widget that it has started. start: function() { this.getset("started", true); }, // REGION: Populate // internal // Inflates this object with the transport JSON object populate: function(widgetObj) { if (this.populated()) return; // enabled this.enabled(widgetObj.enabled); // params this._populateParams(widgetObj.params); // actions this._populateActions(widgetObj.actions); // events this._populateEvents(widgetObj.events); this.getset("populated", true); }, // private // Populates the params from the transport object to this instance _populateParams: function(params) { if (params && Svidget.isArray(params)) { for (var i = 0; i < params.length; i++) { var p = params[i]; // refresh - add or update param var paramProxy = this.refreshParamProxy(p.name, p.value, p); paramProxy.connect(); } } }, // private // Populates the params from the transport object to this instance _populateActions: function(actions) { if (actions && Svidget.isArray(actions)) { for (var i = 0; i < actions.length; i++) { var a = actions[i]; var action = this.addActionProxy(a.name, a); this.<API key>(a.params, action); } } }, // private // Populates the actions from the transport object to this instance <API key>: function(actionParams, action) { if (actionParams && Svidget.isArray(actionParams)) { for (var i = 0; i < actionParams.length; i++) { var ap = actionParams[i]; action.addParam(ap.name, ap); } } }, // private // Populates the events from the transport object to this instance _populateEvents: function(events) { if (events && Svidget.isArray(events)) { for (var i = 0; i < events.length; i++) { var e = events[i]; this.addEventProxy(e.name, e); } } } }; Svidget.extend(Svidget.WidgetReference, Svidget.ObjectPrototype); Svidget.Root.PagePrototype = { // REGION: Initializing initInternal: function() { this.idSeed = 1; // seed for widget IDs window._svidget = "page"; this.connected(true); }, readyPage: function() { Svidget.log("page: readyPage"); //alert("page"); this.loadPageWidgets(); }, // REGION: Widget Loading // Parses page for <object role="svidget"> and loads those as widgets loadPageWidgets: function() { // parse page for object role="svidget" var that = this; var svidgetEles = this.<API key>(); svidgetEles.each(function(item) { that.loadPageWidget(item); }); }, // Loads a widget based on its <object> element. // objEle = <object role="svidget" data="(url)"> // paramValues: passed in when adding widget dynamically via load() loadPageWidget: function(objEle, paramValues) { var widget = this.<API key>(objEle, paramValues); this.addWidget(widget); //if (!Svidget.DOM.<API key>(objEle)) { this.<API key>(widget, objEle); return widget; }, <API key>: function(objEle, paramValues) { var paramObj; // parse <params> if not provided (provided for dynamic loading) if (paramValues === undefined) paramObj = this.parseParamElements(objEle); else paramObj = paramValues; // check for forced values var connected = objEle.getAttribute("data-connected") != "false"; //todo: allow case-insensitive var crossdomain = objEle.getAttribute("data-crossdomain") == "true"; //todo: allow case-insensitive // generate ID // tests: test an element with same id before and test with one after declared element var widgetID = this.<API key>(objEle); //(objEle.id == null) ? this.generateWidgetID() : objEle.id; // resolve core element, if widget DOM not ready this will return null var coreEle = this.<API key>(objEle, null, crossdomain); // create WidgetReference var wRef = new Svidget.WidgetReference(widgetID, paramObj, objEle, coreEle, connected, crossdomain); return wRef; }, <API key>: function(widget, objEle) { // if <iframe> already loaded due to data-crossdomain var ele = widget.element() || objEle; this.addWidgetLoadEvents(ele, widget); }, addWidgetLoadEvents: function(objEle, widget) { Svidget.log("page: addWidgetLoadEvents: id = " + objEle.id + ", tag = " + objEle.tagName); var handler = Svidget.wrap(this.finishPageWidget, this); var wrapper = function() { handler(widget); }; widget._waitingForDOM = true; Svidget.DOM.on(objEle, "load", wrapper); }, // Finishes page widget: // Makes sure widget element is loaded // Makes sure widget is started finishPageWidget: function(widget) { //objEle) { Svidget.log("page: finishPageWidget: id = " + widget.id()); //var widget = objEle.widgetReference; // this.createPageWidget(objEle); widget._waitingForDOM = false; // if <object> replaced with <iframe> var finalEle = this.<API key>(widget); if (finalEle != null && finalEle != widget.declaringElement()) this.<API key>(widget, widget.element()); else this.ensureWidgetStarted(widget); }, <API key>: function(widget) { if (widget.hasElement()) return null; var coreEle = this.<API key>(widget.declaringElement(), widget, widget.crossdomain()); // objEle); if (coreEle != null) { Svidget.log("page: CoreElementCreated: " + coreEle.tagName + " id:" + widget.id()); widget.setElement(coreEle); return coreEle; } return null; }, ensureWidgetStarted: function(widget) { // if core element hasn't been defined yet, then return and try again later if (!widget.hasElement()) return; if (!widget.started() && Svidget.DOM.<API key>(widget.element())) { this.signalStart(widget, widget.paramValues()); } }, // if DOM not yet laoded, returns null // if <object> is determined to be cross-domain, disables it and returns an alternate <iframe> // else returns declaring <object> <API key>: function(objEle, widget, crossdomain) { // try to get widget contentDocument var widgetDoc = Svidget.DOM.getDocument(objEle); // widget is not ready, so return null, we'll try again later // but if crossDomain flag is set, then we use iframe uncondtionally if (widgetDoc === null && !crossdomain) return null; var ifmEle = null; var coreEle = objEle; // if undefined, it means access was denied making it cross domain widget // so we disable and hide <object> and replace with <iframe> if (widgetDoc === undefined || crossdomain) { ifmEle = this.buildIFrameElement(objEle); objEle.parentNode.insertBefore(ifmEle, objEle); this.disableAndHide(objEle); coreEle = ifmEle; } return coreEle; }, waitForWidgets: function() { setTimeout(Svidget.wrap(this.<API key>, this), 50); }, <API key>: function() { // loops through each widget references with missing element // and checks if its document is ready // called from handle widget initialized // var unfinalWidgets = if (this.allWidgetsStarted) return; Svidget.log("page: <API key>"); var that = this; var count = 0; this.widgets().where(function(w) { return that.needsFinishing(w); }).each(function(w) { // return !w.hasElement() && Svidget.DOM.<API key>(w.declaringElement()); //}).each(function (w) { count++; that.finishPageWidget(w); }); // set flag so that we stop checking for unfinalized widgets //if (count == 0) this.allWidgetsFinalized = true; this.waitForWidgets(); }, needsFinishing: function(widget) { if (widget._waitingForDOM) return false; // if widget element hasn't been finalized or started, and declaring element is ready, then it needs finalizing if ((!widget.hasElement() || !widget.started()) && Svidget.DOM.<API key>(widget.declaringElement())) return true; // if widget element is an <iframe> due to being cross domain, and the DOM for that <iframe> is ready, but it hasn't been started, it needs finalizing if (widget.hasElement() && widget.isCrossDomain() && !widget.started() && Svidget.DOM.<API key>(widget.element())) return true; // doesn't need finalizing return false; }, <API key>: function() { return this.widgets().all(function(w) { return w.started(); }); }, disableAndHide: function(ele) { ele.data = ""; //todo: confirm this works Svidget.DOM.disable(ele); Svidget.DOM.hide(ele); }, <API key>: function(objEle) { var id = objEle.id; //(objEle.id == null) ? this.generateWidgetID() : objEle.id; // if id points to element (no duplicates, then just use that) if (id != null && document.getElementById(id) == objEle) return id; return this.newWidgetID(); }, newWidgetID: function() { var prefix = "_svidget_"; if (this.idCounter === undefined) this.idCounter = 1; var idNum = this.idCounter; var id; while (true) { var id = prefix + idNum; idNum++; if (document.getElementById(id) == null) break; } this.idCounter = idNum; return id; }, buildIFrameElement: function(objEle) { var iframe = document.createElement("iframe"); var objItem = Svidget.DOM.wrap(objEle); objItem.attributes().each(function(a) { if (a.name() == "data") iframe.setAttribute("src", a.value()); else if (a.name() == "id") iframe.setAttribute("id", a.value() + "_frame"); else iframe.setAttribute(a.name(), a.value()); }); return iframe; }, buildObjectElement: function(options, paramObj) { var objEle = document.createElement("object"); objEle.setAttribute("role", "svidget"); objEle.setAttribute("data", options.url); if (options.id) objEle.setAttribute("id", options.id); if (options.width) objEle.setAttribute("width", options.width); if (options.height) objEle.setAttribute("height", options.height); // yes, if these values are false we dont want to write them out if (options.standalone) objEle.setAttribute("data-standalone", options.standalone); if (options.crossdomain) objEle.setAttribute("data-crossdomain", options.crossdomain); // params for (var key in paramObj) { var paramEle = document.createElement("param"); paramEle.setAttribute("name", key); } return objEle; }, createObjectElement: function(container, options, paramObj) { var objEle = this.buildObjectElement(options, paramObj); container.appendChild(objEle); return objEle; }, // this is called once the params/actions and widget data are sent from the widget <API key>: function(widgetRef, widgetTransport) { Svidget.log("page: <API key>"); if (!widgetRef.populated()) { widgetRef.populate(widgetTransport); } }, <API key>: function() { var objectEles = Svidget.DOM.getByName("object", true); //document.<API key>("object"); var svidgetEles = objectEles.where(function(item) { return Svidget.DOM.attrValue(item, "role") == "svidget"; }); return svidgetEles; }, // Parses the <param> elements inside of the <object> element for the widget. parseParamElements: function(objEle) { var paramEles = Svidget.DOM.getChildrenByName(objEle, "param", true); //Svidget.array(objEle.<API key>("param"))); // return object with name/value (string/string) var obj = {}; for (var i = 0; i < paramEles.length; i++) { var name = paramEles[i].getAttribute("name"); if (name != null && name.length > 0) obj[name] = paramEles[i].getAttribute("value"); } return obj; }, // RETURNS // A WidgetReference object by that ID getWidget: function(id) { if (id == null) return null; var col = this.widgets(); return col.first(function(w) { return w.id() === id; }); }, // internal addWidget: function(widget) { if (this.widgets().contains(widget)) return false; this.widgets().add(widget); return true; }, // REGION: Public Methods /** * Registers an event handler for the "widgetload" event for the global object. * Examples: * svidget.load("#container", "mywidget.svg") * svidget.load("#container", "mywidget.svg", { color: "red" }, loadCallback) * svidget.load("#container", { url: "mywidget.svg", crossdomain: true }, { color: "red" }) * @method * @memberof Svidget.Root.prototype * @param {string} selector - Arbirary data to initialize Event object with when event is triggered. * @param {(string|object)} urlOrOptions - The url to the widget, or an options object contains properties to initialize the widget reference with. * @param {object} paramObj - The object to initialize params with. * @param {Function} callback - A function to call when loading is complete. * @returns {Svidget.WidgetReference} - The widget reference created, or null if create fails. */ load: function(selector, urlOrOptions, paramObj, callback) { // should we allow multiple sel and create a Widget for each? (hint test a jquery plugin) also: we can have a loadAll (named like queryselectorAll) // resolve container var container = Svidget.DOM.selectElement(selector); if (container == null) return null; // resolve urlOrOptions var options = null; if (typeof urlOrOptions === "string") options = { url: urlOrOptions }; else if (urlOrOptions == null) return null; else options = urlOrOptions; if (options.url == null) return; // clear state this.allWidgetsStarted = false; // build out <object> element var widgetEle = this.createObjectElement(container, options, paramObj); var widget = this.loadPageWidget(widgetEle, paramObj); // note: if this is called before ready, then it is queued // returns the WidgetReference object // if callback defined, call it if (callback && typeof callback === "function") callback(widget); //this.waitForWidgets(); // return widget return widget; }, // REGION: Public Properties /** * Gets a collection of all widgets, or a sub-collection based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * widgets(0) * widgets("widget-1") * @method * @memberof Svidget.Root.prototype * @param {object} [selector] - An integer index or string ID * @returns {Svidget.ObjectCollection} - A collection based on the selector, or the entire collection. */ widgets: function(selector) { var col = this.getWidgets(); return this.select(col, selector); }, /** * Gets the widget based on the selector. * Selector can be an integer to get the zero-based item at that index, or a string to select by that ID. * Examples: * widgets(0) * widgets("widget-1") * @method * @memberof Svidget.Root.prototype * @param {object} selector - The index or ID of the widget. * @returns {Svidget.WidgetReference} - The widget reference based on the selector. If selector is invalid, null is returned. */ widget: function(selector) { var col = this.getWidgets(); var item = this.selectFirst(col, selector); return item; }, // private getWidgets: function() { var col = this.getset("widgets"); if (col == null) { col = new Svidget.ObjectCollection(null, Svidget.WidgetReference); this.getset("widgets", col); } return col; }, // private triggerWidgetEvent: function(widgetRef, eventName, data) { var ev = widgetRef.event(eventName); if (ev == null) return; ev.triggerFromWidget(data); }, // REGION: Communication receiveFromWidget: function(name, payload, widgetID) { Svidget.log("page: receiveFromWidget {name: " + name + ", widgetID: " + widgetID + "}"); var widget = this.getWidget(widgetID); //if (widget == null && name != "initialized") return; // widgetID may be null if widget hasn't been assigned an ID // invoke handler for message switch (name) { // lifecycle handlers // payload == widget transport { id: "", enabled: true, params: [], actions: [] } //case "initialized": this.<API key>(); break; //widget, payload); break; //case "loaded": this.<API key>(widget, payload); break; // params handlers // payload == param transport { name: "background", type: "", value: 3 } case "paramadded": this.<API key>(widget, payload); break; case "paramremoved": this.<API key>(widget, payload); break; case "paramchanged": this.<API key>(widget, payload); break; case "paramvaluechanged": this.<API key>(widget, payload); break; // actions handlers case "actionadded": this.<API key>(widget, payload); break; case "actionremoved": this.<API key>(widget, payload); break; case "actionchanged": this.<API key>(widget, payload); break; case "actioninvoked": this.<API key>(widget, payload); break; case "actionparamadded": this.<API key>(widget, payload); break; case "actionparamremoved": this.<API key>(widget, payload); break; case "actionparamchanged": this.<API key>(widget, payload); break; // events handlers case "eventadded": this.<API key>(widget, payload); break; case "eventremoved": this.<API key>(widget, payload); break; case "eventchanged": this.<API key>(widget, payload); break; case "eventtriggered": this.<API key>(widget, payload); break; // acks case "startack": this.<API key>(widget, payload); break; } }, // signal widget to start, effectively establishing a connection from parent to it signalStart: function(widgetRef, paramValues) { Svidget.log("page: signalStart {id: " + widgetRef.id() + ", url: " + widgetRef.url() + ", tag: " + widgetRef.element().tagName + "}"); //var paramValues = {}; var payload = { id: widgetRef.id(), params: paramValues, connected: widgetRef.connected() }; this.comm().signalWidget(widgetRef, "start", payload); }, <API key>: function(widgetRef, obj, objType, propName, propValue) { if (!widgetRef.started() || !widgetRef.connected()) return; Svidget.log("page: <API key> {id: " + widgetRef.id() + ", type: " + objType + "}"); var payload = { type: objType, name: obj.name(), propertyName: propName, value: propValue }; this.comm().signalWidget(widgetRef, "propertychange", payload); }, signalActionInvoke: function(widgetRef, actionProxy, argList) { if (!widgetRef.started() || !widgetRef.connected()) return; Svidget.log("page: signalActionInvoke {id: " + widgetRef.id() + ", url: " + widgetRef.url() + "}"); //var paramValues = {}; var payload = { action: actionProxy.name(), args: argList }; this.comm().signalWidget(widgetRef, "actioninvoke", payload); }, signalEventTrigger: function(widgetRef, eventDescProxy, data) { if (!widgetRef.started() || !widgetRef.connected()) return; Svidget.log("page: signalEventTrigger {id: " + widgetRef.id() + "}"); var payload = { event: eventDescProxy.name(), data: data }; this.comm().signalWidget(widgetRef, "eventtrigger", payload); }, // invoked by widget to notify parent that it has been instantiated <API key>: function() { //widgetRef, widgetTransport) { Svidget.log("page: <API key>"); }, // invoked by widget to notify parent that it is loaded and ready <API key>: function(widgetRef, widgetTransport) { //this.signalStart(widgetProxy); // moved to initialized // in most cases, widget should be finalized, but call one more time just in case // commented out because it no longer makes sense because if widgetRef is not null then it means that start was already called // this.finalizePageWidget(widgetRef.declaringElement()); // trigger load widget event // if null, it means that widget DOM loaded before start was called, so defer if (widgetRef == null) { this.<API key>(); return; } this.<API key>(widgetRef, widgetTransport); }, // invoked by widget to notify parent that it received start message // if the widget is to be in standalone mode then this will not be invoked <API key>: function(widgetRef, widgetTransport) { Svidget.log("page: <API key> {widget: " + widgetRef.id() + "}"); // ignore subsequent acks if (widgetRef.started()) return; widgetRef.start(); this.<API key>(widgetRef, widgetTransport); this.triggerWidgetLoaded(widgetRef.id()); // check if all widgets loaded, if so fire loaded // note: this is probably a bit inefficient, but we'll optimize later if (this.<API key>()) { this.allWidgetsStarted = true; this.markLoaded(); } }, // Handle: Params // invoked by widget to notify parent that a param was added <API key>: function(widgetRef, paramPayload) { Svidget.log("page: <API key> {param: " + paramPayload.name + "}"); // paramPayload == param transport // add the paramProxy from param transport, this will trigger any events associated with the add widgetRef.addParamProxy(paramPayload.name, paramPayload); }, // invoked by widget to notify parent that a param was removed <API key>: function(widgetRef, paramName) { Svidget.log("page: <API key> {param: " + paramName + "}"); // remove the paramProxy, this will trigger any events associated with the add widgetRef.removeParamProxy(paramName); }, // changeData: { name: actionName, property: "enabled", value: val } <API key>: function(widgetRef, changePayload) { Svidget.log("page: <API key> {param: " + changePayload.name + "}"); var param = widgetRef.param(changePayload.name); if (param == null) return; param.<API key>(changePayload.property, changePayload.value); }, // valueData: { name: actionName, value: val } <API key>: function(widgetRef, valueChangePayload) { Svidget.log("page: <API key> {param: " + valueChangePayload.name + "}"); var param = widgetRef.param(valueChangePayload.name); if (param == null) return; param.notifyValueChange("value", valueChangePayload.value); }, // Handle: Actions // invoked by widget to notify parent that a param was added <API key>: function(widgetRef, actionPayload) { Svidget.log("page: <API key> {action: " + actionPayload.name + "}"); // actionPayload == action transport // add the actionProxy from action transport, this will trigger any events associated with the add widgetRef.addActionProxy(actionPayload.name, actionPayload); }, // invoked by widget to notify parent that a param was removed <API key>: function(widgetRef, actionName) { Svidget.log("page: <API key> {action: " + actionName + "}"); // remove the paramProxy, this will trigger any events associated with the add widgetRef.removeActionProxy(actionName); }, // changeData: { name: actionName, property: "enabled", value: val } <API key>: function(widgetRef, changePayload) { Svidget.log("page: <API key> {action: " + changePayload.name + "}"); var action = widgetRef.action(changePayload.name); if (action == null) return; action.<API key>(changePayload.property, changePayload.value); }, // actionReturnPayload = { name: actionName, returnValue: "value returned from action" } <API key>: function(widgetRef, actionReturnPayload) { Svidget.log("page: <API key> {action: " + actionReturnPayload.name + "}"); var action = widgetRef.action(actionReturnPayload.name); if (action == null) return; action.invokeFromWidget(actionReturnPayload.returnValue); }, // invoked by widget to notify parent that a param was added <API key>: function(widgetRef, actionParamPayload) { Svidget.log("page: <API key> {actionparam: " + actionParamPayload.name + "}"); // actionPayload == action transport // add the actionProxy from action transport, this will trigger any events associated with the add var action = widgetRef.action(actionParamPayload.actionName); if (action == null) return; action.addParam(actionParamPayload.name, actionParamPayload); }, // invoked by widget to notify parent that a param was removed // { name: actionParamName, actionName: actionName } <API key>: function(widgetRef, <API key>) { Svidget.log("page: <API key> {actionparam: " + <API key> + "}"); // remove the paramProxy, this will trigger any events associated with the add var action = widgetRef.action(<API key>.actionName); if (action == null) return; action.removeParam(<API key>.name); }, // changeData: { name: actionParamName, actionName: actionName, property: "enabled", value: val } <API key>: function(widgetRef, changePayload) { Svidget.log("page: <API key> {actionparam: " + changePayload.name + "}"); var action = widgetRef.action(changePayload.actionName); if (action == null) return; var actionParam = action.param(changePayload.name); if (actionParam == null) return; actionParam.<API key>(changePayload.property, changePayload.value); }, // Handle: Events <API key>: function(widgetRef, eventDescPayload) { Svidget.log("page: <API key> {event: " + eventDescPayload.name + "}"); // eventPayload == eventDesc transport // add the eventDescProxy from eventDesc transport, this will trigger any events associated with the add widgetRef.addEventProxy(eventDescPayload.name, eventDescPayload); }, <API key>: function(widgetRef, eventDescName) { Svidget.log("page: <API key> {event: " + eventDescName + "}"); // eventPayload == eventDesc.name // remove the eventDescProxy by its name, this will trigger any events associated with the remove widgetRef.removeEventProxy(eventDescName); }, // changeData: { name: eventName, property: "enabled", value: val } <API key>: function(widgetRef, changePayload) { Svidget.log("page: <API key> {event: " + changePayload.name + "}"); var ev = widgetRef.event(changePayload.name); if (ev == null) return; ev.<API key>(changePayload.property, changePayload.value); }, // invoked by widget to notify parent that an event was triggered <API key>: function(widgetRef, eventDataPayload) { Svidget.log("page: <API key> {event: " + eventDataPayload.name + "}"); //{ "name": eventDesc.name(), "value": value }; var ev = widgetRef.event(eventDataPayload.name); if (ev == null) return; ev.<API key>(eventDataPayload.value); } }; Svidget.Root.WidgetPrototype = { // REGION: Initializing initInternal: function() { // init widget object this.loadCurrent(); // notify parent that widget is initialized and ready to be started //this.signalInitialized(); window._svidget = "widget"; }, readyWidget: function() { Svidget.log("widget: readyWidget"); //alert("widget"); //this.loadCurrent(); // start widget this.startWidget(); }, // REGION: Widget Element Loading // widget object should be instantiated before ready loadCurrent: function() { // load widget object var widget = new Svidget.Widget(); this.setCurrent(widget); this.setCurrent = null; }, startWidget: function() { var widget = this.current(); // populate objects this.populateObjects(); // set up widget as either standalone or connected if (!this.connected()) this.<API key>(widget); else this.<API key>(widget); }, <API key>: function(widget) { // read values from query string and populate params var paramValues = this.<API key>(); this.setParamValues(widget, paramValues, true); widget.start(); }, <API key>: function(widget) { if (this.paramValues != null) { this.setParamValues(this.paramValues); this.paramValues = null; } widget.start(); }, populateObjects: function() { // get <svidget:params> xml element var paramsElement = this.getParamsElement(); // populate params this.populateParams(paramsElement); // get <svidget:actions> xml element var actionsElement = this.getActionsElement(); // populate actions this.populateActions(actionsElement); // get <svidget:events> xml element var eventsElement = this.getEventsElement(); // populate events this.populateEvents(eventsElement); }, getParamsElement: function() { return this.getSvidgetElement("params"); }, getActionsElement: function() { return this.getSvidgetElement("actions"); }, getEventsElement: function() { return this.getSvidgetElement("events"); }, getSvidgetElement: function(name) { var eles = Svidget.DOM.getByNameSvidget(name, true); if (eles.length == 0) return null; return eles[0]; }, // Populates Params into the widget based on the // xele == <svidget:params> element populateParams: function(xele) { if (xele == null) return; // param element missing var that = this; var widget = this.current(); this.<API key>(xele, function(nextEle, widget) { var param = that.buildParam(nextEle, widget); if (param != null) widget.addParam(param); }); // 0.1.3: wire declared add/remove handlers this.wireDeclaredHandler(widget, widget.ondeclaredparamadd, Svidget.DOM.attrValue(xele, "onadd")); this.wireDeclaredHandler(widget, widget.<API key>, Svidget.DOM.attrValue(xele, "onremove")); }, buildParam: function(xele, widget) { if (!this.<API key>(xele, "param")) return null; var name = Svidget.DOM.attrValue(xele, "name"); //xele.attributes["name"]; if (name == null) return null; // don't allow a param without a name var value = Svidget.DOM.attrValue(xele, "value"); //xele.attributes["value"]; var options = this.buildOptions(xele, Svidget.Param.optionProperties); var param = new Svidget.Param(name, value, options, widget); this.<API key>(param, Svidget.DOM.attrValue(xele, "onchange")); this.<API key>(param, Svidget.DOM.attrValue(xele, "onset")); return param; }, populateActions: function(xele) { if (xele == null) return; // action element missing var that = this; var widget = this.current(); this.<API key>(xele, function(nextEle, widget) { var action = that.buildAction(nextEle, widget); if (action != null) { widget.addAction(action); that.<API key>(nextEle, action); } }); // 0.1.3: wire declared add/remove handlers this.wireDeclaredHandler(widget, widget.ondeclaredactionadd, Svidget.DOM.attrValue(xele, "onadd")); this.wireDeclaredHandler(widget, widget.<API key>, Svidget.DOM.attrValue(xele, "onremove")); }, // Populates action params into the action // actionEle == <svidget:action> element <API key>: function(actionEle, action) { if (actionEle == null) return; // actionparam element missing var that = this; this.<API key>(actionEle, function(nextEle, widget) { var param = that.buildActionParam(nextEle, action); if (param != null) action.addParam(param); }); }, buildAction: function(xele, widget) { if (!this.<API key>(xele, "action")) return null; var name = Svidget.DOM.attrValue(xele, "name"); //xele.attributes["name"]; if (name == null) return null; // don't allow a param without a name var options = this.buildOptions(xele, Svidget.Action.optionProperties); var action = new Svidget.Action(name, options, widget); // 0.1.3: wire declared add/remove handlers this.<API key>(action, Svidget.DOM.attrValue(xele, "onchange")); this.<API key>(action, Svidget.DOM.attrValue(xele, "oninvoke")); this.<API key>(action, Svidget.DOM.attrValue(xele, "onparamadd")); this.<API key>(action, Svidget.DOM.attrValue(xele, "onparamremove")); this.<API key>(action, Svidget.DOM.attrValue(xele, "onparamchange")); return action; }, buildActionParam: function(xele, action) { if (!this.<API key>(xele, "actionparam")) return null; var name = Svidget.DOM.attrValue(xele, "name"); //xele.attributes["name"]; if (name == null) return null; // don't allow a param without a name var options = this.buildOptions(xele, Svidget.ActionParam.optionProperties); var param = new Svidget.ActionParam(name, options, action); this.<API key>(param, Svidget.DOM.attrValue(xele, "onchange")); return param; }, // Populates Params into the widget based on the // xele == <svidget:events> element populateEvents: function(xele) { if (xele == null) return; // event element missing var that = this; var widget = this.current(); this.<API key>(xele, function(nextEle, widget) { var ev = that.buildEvent(nextEle, widget); if (ev != null) widget.addEvent(ev); }); // 0.1.3: wire declared add/remove handlers this.wireDeclaredHandler(widget, widget.ondeclaredeventadd, Svidget.DOM.attrValue(xele, "onadd")); this.wireDeclaredHandler(widget, widget.<API key>, Svidget.DOM.attrValue(xele, "onremove")); }, buildEvent: function(xele, widget) { if (!this.<API key>(xele, "event")) return null; var name = Svidget.DOM.attrValue(xele, "name"); //xele.attributes["name"]; if (name == null) return null; // don't allow a param without a name var options = this.buildOptions(xele, Svidget.EventDesc.optionProperties); var ev = new Svidget.EventDesc(name, options, widget); this.<API key>(ev, Svidget.DOM.attrValue(xele, "onchange")); this.<API key>(ev, Svidget.DOM.attrValue(xele, "ontrigger")); return ev; }, <API key>: function(xele, eachAction) { if (xele == null || xele.childNodes == null) return; var widget = this.current(); var nextEle = xele.firstElementChild; while (nextEle != null) { if (eachAction) eachAction(nextEle, widget); nextEle = nextEle.nextElementSibling; } }, buildOptions: function(xele, optionProps) { var options = {}; if (optionProps == null || !Svidget.isArray(optionProps)) return options; for (var i = 0; i < optionProps.length; i++) { var optName = optionProps[i]; var optVal = Svidget.DOM.attrValue(xele, optName); if (optVal != null) options[optName] = optVal; } return options; }, <API key>: function(obj, funcStr) { this.wireDeclaredHandler(obj, obj.ondeclaredchange, funcStr); }, <API key>: function(param, funcStr) { this.wireDeclaredHandler(param, param.ondeclaredset, funcStr); }, <API key>: function(action, funcStr) { this.wireDeclaredHandler(action, action.ondeclaredinvoke, funcStr); }, <API key>: function(event, funcStr) { this.wireDeclaredHandler(event, event.ondeclaredtrigger, funcStr); }, <API key>: function(action, funcStr) { this.wireDeclaredHandler(action, action.ondeclaredparamadd, funcStr); }, <API key>: function(action, funcStr) { this.wireDeclaredHandler(action, action.<API key>, funcStr); }, <API key>: function(action, funcStr) { this.wireDeclaredHandler(action, action.<API key>, funcStr); }, wireDeclaredHandler: function(obj, wireFunc, funcStr) { if (wireFunc == null) return; var func = Svidget.findFunction(funcStr); if (func == null || !Svidget.isFunction(func)) return; wireFunc.call(obj, func); }, // Called by parent (via global object) to signal that is has established its relationship with the parent page. // Params: // id: the ID assigned to this widget // paramValues: the param values as they were declared on the page, or provided if widget declared programmatically // connected: whether the widget is connected to its parent, if false it will remain in standalone mode and cease any further communication with the parent // Remarks: // start() may be called at any point during the DOM lifecycle for this widget, i.e. while DOM is still parsing or when completed connectWidget: function(id, paramValues, connected) { var widget = this.current(); if (widget.connected()) return; // connect, setting id if (connected) { Svidget.log("widget: connect {id: " + id + "}"); widget.connect(id); this.getset("connected", true); } else { Svidget.log("widget: standalone {id: " + id + "}"); } //Svidget.log("widget: connect {id: " + id + "}"); //widget.connect(id); //this.getset("connected", true); // set params //this.setParamValues(paramValues); this.paramValues = paramValues || {}; }, <API key>: function() { var widget = this.current(); if (widget.started()) { this.setParamValues(widget, this.paramValues); } }, // Gets the param values from the query string. <API key>: function() { var qs = Svidget.Util.queryString(); return qs; }, // SUMMARY // Sets the param values for every param using the values from the specified object. This object can be from the query string or parent. // Params initialized with a value will be skipped if there is no matching entry in the values object. setParamValues: function(widget, paramValues, qsMode) { // note: can only be called internally // loop through all params, if value in paramValues then overwrite, if value not yet populated on param then use default value, otherwise skip //var widget = this.current(); var col = widget.params(); if (col == null) return; col.each(function(p) { var key = qsMode ? p.shortname() || p.name() : p.name(); var val = paramValues[key]; // query string value present so use it if (val === undefined) val = p.defvalue(); // 0.1.3: query string value not present, so use defvalue if (key !== undefined) { // value is present in query string or defvalue attr p.value(val); } }); }, <API key>: function(xele, name) { return xele != null && xele.localName == name && xele.namespaceURI == Svidget.Namespaces.svidget; }, // REGION: Public Properties /** * Gets the current widget. * @method * @memberof Svidget.Root * @returns {Svidget.Widget} - The current widget. */ current: function() { return this.getset("current"); }, /** * Gets whether the widget is connected to a parent page. * @method * @memberof Svidget.Root * @returns {boolean} */ connected: function() { return this.getset("connected"); }, // REGION: Communications receiveFromParent: function(name, payload) { Svidget.log("widget: receiveFromParent {name: " + name + "}"); if (name == "start") this.<API key>(payload); else if (name == "actioninvoke") this.<API key>(payload); else if (name == "eventtrigger") this.<API key>(payload); else if (name == "propertychange") this.<API key>(payload); }, signalStartAck: function() { Svidget.log("widget: signalStartAck {id: " + this.current().id() + "}"); var t = this.current().toTransport(); this.comm().signalParent("startack", t, this.current().id()); }, // for any other signals, if widget isn't connected then don't signal // Params signalParamAdded: function(param) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalParamAdded {id: " + this.current().id() + "}"); var transport = param.toTransport(); this.comm().signalParent("paramadded", transport, this.current().id()); }, signalParamRemoved: function(paramName) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalParamRemoved {id: " + this.current().id() + "}"); //var transport = param.name(); this.comm().signalParent("paramremoved", paramName, this.current().id()); }, signalParamChanged: function(param, changeData) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalParamChanged {id: " + this.current().id() + "}"); changeData.name = param.name(); // add param name this.comm().signalParent("paramchanged", changeData, this.current().id()); }, <API key>: function(param, changeData) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: <API key> {id: " + this.current().id() + "}"); changeData.name = param.name(); // add param name this.comm().signalParent("paramvaluechanged", changeData, this.current().id()); }, // Actions/Action Params signalActionAdded: function(action) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalActionAdded {id: " + this.current().id() + "}"); var transport = action.toTransport(); this.comm().signalParent("actionadded", transport, this.current().id()); }, signalActionRemoved: function(actionName) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalActionRemoved {id: " + this.current().id() + "}"); //var t = action.name(); this.comm().signalParent("actionremoved", actionName, this.current().id()); }, // changeData: { name: actionName, property: "enabled", value: val } signalActionChanged: function(action, changeData) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalActionChanged {id: " + this.current().id() + "}"); changeData.name = action.name(); // add action name this.comm().signalParent("actionchanged", changeData, this.current().id()); }, // returnData: { name: actionName, returnValue: "enabled", value: val } signalActionInvoked: function(action, returnData) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalActionInvoked {id: " + this.current().id() + "}"); //var transport = { name: action.name(), retu: argObj }; returnData.name = action.name(); this.comm().signalParent("actioninvoked", returnData, this.current().id()); }, <API key>: function(actionParam, actionName) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: <API key> {id: " + this.current().id() + "}"); var transport = actionParam.toTransport(); transport.actionName = actionName; this.comm().signalParent("actionparamadded", transport, this.current().id()); }, <API key>: function(actionParamName, actionName) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: <API key> {id: " + this.current().id() + "}"); //var t = action.name(); var transport = { name: actionParamName, actionName: actionName }; this.comm().signalParent("actionparamremoved", transport, this.current().id()); }, <API key>: function(actionParam, action, changeData) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: <API key> {id: " + this.current().id() + "}"); changeData.name = actionParam.name(); // add actionparam name changeData.actionName = action.name(); // add actionparam name this.comm().signalParent("actionparamchanged", changeData, this.current().id()); }, // Events signalEventAdded: function(eventDesc) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalEventAdded {id: " + this.current().id() + "}"); var transport = eventDesc.toTransport(); this.comm().signalParent("eventadded", transport, this.current().id()); }, signalEventRemoved: function(eventDescName) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalEventRemoved {id: " + this.current().id() + "}"); //var transport = eventDesc.name(); this.comm().signalParent("eventremoved", eventDescName, this.current().id()); }, signalEventChanged: function(eventDesc, changeData) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: signalEventChanged {id: " + this.current().id() + "}"); changeData.name = eventDesc.name(); // add event name this.comm().signalParent("eventchanged", changeData, this.current().id()); }, <API key>: function(eventDesc, value) { if (!this.connected()) return; // no signaling if not connected Svidget.log("widget: <API key> {id: " + this.current().id() + "}"); var transport = { name: eventDesc.name(), value: value }; this.comm().signalParent("eventtriggered", transport, this.current().id()); }, // payload == { id: widgetRef.id(), params: paramValues }; <API key>: function(payload) { payload = payload || {}; //this.current().start(payload.id, payload.params); // wire up data from parent var connected = payload.connected !== false; this.connectWidget(payload.id, payload.params, connected); // we default to connected, so if undefined then true // tell the parent that we got the start signal - before we set anything on widget from parent if (connected) this.signalStartAck(); // if widget already started, update param values with ones passed from page this.<API key>(); }, <API key>: function(payload) { payload = payload || {}; var objType = payload.type; // only support param.value for now if (payload.type == "param" && payload.propertyName == "value" && payload.name != null) { var param = this.current().param(payload.name); if (param != null) { param.value(payload.value); } } }, // payload == { action: actionProxy.name(), args: argList } <API key>: function(payload) { payload = payload || {}; var actionName = payload.action; var action = this.current().action(actionName); if (action == null || !action.external()) return; // todo: maybe send some fail message? action.invokeApply(payload.args); }, <API key>: function(payload) { payload = payload || {}; var eventName = payload.event; var ev = this.current().event(eventName); if (ev == null || !ev.external()) return; // todo: maybe send some fail message? ev.trigger(payload.data); } }; this.svidget = new Svidget.Root(this); }).call(this);
goog.provide('gmfapp.objectediting'); goog.require('gmf.Themes'); goog.require('gmf.TreeManager'); /** @suppress {extraRequire} */ goog.require('gmf.layertreeDirective'); /** @suppress {extraRequire} */ goog.require('gmf.mapDirective'); /** @suppress {extraRequire} */ goog.require('gmf.<API key>'); goog.require('gmf.<API key>'); goog.require('ngeo.ToolActivate'); goog.require('ngeo.ToolActivateMgr'); /** @suppress {extraRequire} */ goog.require('ngeo.proj.EPSG21781'); goog.require('ol.Collection'); goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.layer.Tile'); goog.require('ol.layer.Vector'); goog.require('ol.source.OSM'); goog.require('ol.source.Vector'); /** @type {!angular.Module} **/ gmfapp.module = angular.module('gmfapp', ['gmf']); /** * @param {gmf.<API key>} <API key> The gmf * ObjectEditing manager service. * @param {gmf.Themes} gmfThemes The gmf themes service. * @param {gmf.TreeManager} gmfTreeManager gmf Tree Manager service. * @param {ngeo.ToolActivateMgr} ngeoToolActivateMgr Ngeo ToolActivate manager * service. * @constructor * @ngInject */ gmfapp.MainController = function(<API key>, gmfThemes, gmfTreeManager, ngeoToolActivateMgr) { /** * @type {gmf.TreeManager} * @private */ this.gmfTreeManager_ = gmfTreeManager; gmfThemes.loadThemes(); var projection = ol.proj.get('EPSG:21781'); projection.setExtent([485869.5728, 76443.1884, 837076.5648, 299941.7864]); /** * @type {ol.source.Vector} * @private */ this.vectorSource_ = new ol.source.Vector({ wrapX: false }); /** * @type {ol.layer.Vector} * @private */ this.vectorLayer_ = new ol.layer.Vector({ source: this.vectorSource_ }); /** * @type {ol.Collection.<ol.Feature>} * @export */ this.sketchFeatures = new ol.Collection(); /** * @type {ol.layer.Vector} * @private */ this.sketchLayer_ = new ol.layer.Vector({ source: new ol.source.Vector({ features: this.sketchFeatures, wrapX: false }) }); /** * @type {ol.Map} * @export */ this.map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ projection: 'EPSG:21781', resolutions: [200, 100, 50, 20, 10, 5, 2.5, 2, 1, 0.5], center: [537635, 152640], zoom: 2 }) }); gmfThemes.getThemesObject().then(function(themes) { if (themes) { // Add layer vector after this.map.addLayer(this.vectorLayer_); this.map.addLayer(this.sketchLayer_); } }.bind(this)); /** * @type {?string} * @export */ this.<API key> = <API key>.getGeomType(); /** * @type {?number} * @export */ this.<API key> = <API key>.getLayerNodeId(); /** * @type {boolean} * @export */ this.objectEditingActive = true; var <API key> = new ngeo.ToolActivate( this, 'objectEditingActive'); ngeoToolActivateMgr.registerTool( 'mapTools', <API key>, true); /** * @type {boolean} * @export */ this.dummyActive = false; var dummyToolActivate = new ngeo.ToolActivate( this, 'dummyActive'); ngeoToolActivateMgr.registerTool( 'mapTools', dummyToolActivate, false); /** * @type {?ol.Feature} * @export */ this.<API key> = null; <API key>.getFeature().then(function(feature) { this.<API key> = feature; if (feature) { this.vectorSource_.addFeature(feature); } }.bind(this)); }; gmfapp.module.controller('MainController', gmfapp.MainController);
package mvc.exceptions; public class <API key> extends Exception { }
package microsoft.exchange.webservices.data; import java.util.EnumSet; /** * Represents response object property defintion. */ public class <API key> extends PropertyDefinition { /** * Initializes a new instance of the <API key> * class. * * @param xmlElementName * the xml element name * @param uri * the uri * @param version * the version */ protected <API key>(String xmlElementName, String uri, ExchangeVersion version) { super(xmlElementName, uri, version); } /** * Loads from XML. * * @param reader * the reader * @param propertyBag * the property bag * @throws Exception * the exception */ protected final void <API key>(EwsServiceXmlReader reader, PropertyBag propertyBag) throws Exception { EnumSet<ResponseActions> value = EnumSet.noneOf(ResponseActions.class); value.add(ResponseActions.None); reader.<API key>(XmlNamespace.Types, this .getXmlElement()); if (!reader.isEmptyElement()) { do { reader.read(); if (reader.isStartElement()) { if (reader.getLocalName() .equals(XmlElementNames.AcceptItem)) { value.add(ResponseActions.Accept); } else if (reader.getLocalName().equals( XmlElementNames.<API key>)) { value.add(ResponseActions.TentativelyAccept); } else if (reader.getLocalName().equals( XmlElementNames.DeclineItem)) { value.add(ResponseActions.Decline); } else if (reader.getLocalName().equals( XmlElementNames.ReplyToItem)) { value.add(ResponseActions.Reply); } else if (reader.getLocalName().equals( XmlElementNames.ForwardItem)) { value.add(ResponseActions.Forward); } else if (reader.getLocalName().equals( XmlElementNames.ReplyAllToItem)) { value.add(ResponseActions.ReplyAll); } else if (reader.getLocalName().equals( XmlElementNames.CancelCalendarItem)) { value.add(ResponseActions.Cancel); } else if (reader.getLocalName().equals( XmlElementNames.RemoveItem)) { value.add(ResponseActions.RemoveFromCalendar); } else if (reader.getLocalName().equals( XmlElementNames.SuppressReadReceipt)) { value.add(ResponseActions.SuppressReadReceipt); } else if (reader.getLocalName().equals( XmlElementNames.PostReplyItem)) { value.add(ResponseActions.PostReply); } } } while (!reader.isEndElement(XmlNamespace.Types, this .getXmlElement())); } else { reader.read(); } propertyBag.<API key>(this, value); } /** * Writes to XML. * * @param writer * the writer * @param propertyBag * the property bag * @param isUpdateOperation * the is update operation */ protected void <API key>(EwsServiceXmlWriter writer, PropertyBag propertyBag, boolean isUpdateOperation) { // ResponseObjects is a read-only property, no need to implement this. } /** * Gets a value indicating whether this property * definition is for a nullable type (ref, int?, bool?...). */ @Override protected boolean isNullable() { return false; } /** * Gets the property type. */ @Override public Class getType() { return ResponseActions.class; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pagina 3</title> </head> <body> <h1>Pagina 3</h1> </body> </html>
""" Set up the plot figures, axes, and items to be done for each frame. This module is imported by the plotting routines and then the function setplot is called to set the plot parameters. """ import os import numpy as np import matplotlib.pyplot as plt import datetime from clawpack.geoclaw.util import <API key> from clawpack.visclaw import colormaps, gaugetools import clawpack.clawutil.data import clawpack.amrclaw.data import clawpack.geoclaw.data import clawpack.geoclaw.surge.plot as surge try: from setplotfg import setplotfg except: setplotfg = None def setplot(plotdata): r"""Setplot function for surge plotting""" plotdata.clearfigures() # clear any old figures,axes,items data plotdata.format = 'binary' # Load data from output clawdata = clawpack.clawutil.data.ClawInputData(2) clawdata.read(os.path.join(plotdata.outdir,'claw.data')) physics = clawpack.geoclaw.data.GeoClawData() physics.read(os.path.join(plotdata.outdir,'geoclaw.data')) surge_data = clawpack.geoclaw.data.SurgeData() surge_data.read(os.path.join(plotdata.outdir,'surge.data')) friction_data = clawpack.geoclaw.data.FrictionData() friction_data.read(os.path.join(plotdata.outdir,'friction.data')) # Load storm track32 track = surge.track_data(os.path.join(plotdata.outdir,'fort.track')) # Set afteraxes function def surge_afteraxes(cd): return surge.surge_afteraxes(cd, track, plot_direction=False) # Limits for plots dx = 0.5 dy = 0.5 regions = [{"name": "Full Domain", "limits": [[clawdata.lower[0], clawdata.upper[0]], [clawdata.lower[1], clawdata.upper[1]]]}, {"name": "New Orleans", "limits": [[-92.5, -87.5], [27.5, 31.5]]}, {"name": "Grand Isle", "limits": [[-89.41 - dx, -89.41 + dx], [29.26 - dx, 29.26 + dx]]}, {"name": "Pilots Station East", "limits": [[-89.41 - dx, -89.41 + dx], [28.93 - dy, 28.93 + dy]]}, {"name": "Dauphin Island", "limits": [[-88.08 - dx, -88.08 + dx], [30.25 - dy, 30.25 + dy]]}] # Color limits surface_limits = [physics.sea_level - 5.0, physics.sea_level + 5.0] surface_ticks = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] surface_labels = [str(value) for value in surface_ticks] speed_limits = [0.0, 3.0] speed_ticks = [0, 1, 2, 3] speed_labels = [str(value) for value in speed_ticks] wind_limits = [15, 40] pressure_limits = [966,1013] friction_bounds = [0.01,0.04] # Plot specifications # Loop over region specifications ploting both surface and speeds for region in regions: name = region['name'] xlimits = region['limits'][0] ylimits = region['limits'][1] # Surface Elevations plotfigure = plotdata.new_plotfigure(name='Surface - %s' % name) plotfigure.show = True # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes() plotaxes.title = 'Surface' plotaxes.scaled = True plotaxes.xlimits = xlimits plotaxes.ylimits = ylimits plotaxes.afteraxes = surge_afteraxes surge.<API key>(plotaxes, bounds=surface_limits) plotaxes.plotitem_dict['surface'].amr_patchedges_show = [0] * 10 surge.add_land(plotaxes) plotaxes.plotitem_dict['land'].amr_patchedges_show = [0] * 10 # Water Speed plotfigure = plotdata.new_plotfigure(name='Currents - %s' % name) plotfigure.show = True # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes() plotaxes.title = 'Currents' plotaxes.scaled = True plotaxes.xlimits = xlimits plotaxes.ylimits = ylimits plotaxes.afteraxes = surge_afteraxes surge.add_speed(plotaxes, bounds=speed_limits) plotaxes.plotitem_dict['speed'].amr_patchedges_show = [0] * 10 surge.add_land(plotaxes) plotaxes.plotitem_dict['land'].amr_patchedges_show = [0] * 10 # Wind Field plotfigure = plotdata.new_plotfigure(name='Wind Speed - %s' % name) plotfigure.show = surge_data.wind_forcing plotaxes = plotfigure.new_plotaxes() plotaxes.title = "Wind Field" plotaxes.scaled = True plotaxes.xlimits = xlimits plotaxes.ylimits = ylimits plotaxes.afteraxes = surge_afteraxes surge.add_wind(plotaxes, bounds=wind_limits) plotaxes.plotitem_dict['wind'].amr_patchedges_show = [0] * 10 surge.add_land(plotaxes) plotaxes.plotitem_dict['land'].amr_patchedges_show = [0] * 10 # Hurricane forcing # Friction field plotfigure = plotdata.new_plotfigure(name='Friction - %s' % name) plotfigure.show = friction_data.variable_friction plotaxes = plotfigure.new_plotaxes() plotaxes.title = "Manning's N Coefficients" plotaxes.scaled = True plotaxes.xlimits = xlimits plotaxes.ylimits = ylimits plotaxes.afteraxes = surge_afteraxes surge.add_friction(plotaxes, bounds=friction_bounds) # Pressure field plotfigure = plotdata.new_plotfigure(name='Pressure - %s' % name) plotfigure.show = surge_data.pressure_forcing plotaxes = plotfigure.new_plotaxes() plotaxes.title = "Pressure Field" plotaxes.scaled = True plotaxes.xlimits = xlimits plotaxes.ylimits = ylimits plotaxes.afteraxes = surge_afteraxes surge.add_pressure(plotaxes, bounds=pressure_limits) plotaxes.plotitem_dict['pressure'].amr_patchedges_show = [0] * 10 surge.add_land(plotaxes) plotaxes.plotitem_dict['land'].amr_patchedges_show = [0] * 10 # Figures for gauges plotfigure = plotdata.new_plotfigure(name='Surface & Topo', figno=300, \ type='each_gauge') plotfigure.show = True plotfigure.clf_each_gauge = True stations = [('8761724', 'Grand Isle, LA'), ('8760922', 'Pilots Station East, SW Pass, LA'), ('8735180', 'Dauphin Island, AL')] landfall_time = np.datetime64('2005-08-29T11:10') begin_date = datetime.datetime(2005, 8, 26) end_date = datetime.datetime(2005, 8, 31) def <API key>(station_id): # Fetch water levels and tide predictions for given station date_time, water_level, tide = <API key>(station_id, begin_date, end_date) # Calculate times relative to landfall secs_rel_landfall = (date_time - landfall_time) / np.timedelta64(1, 's') # Subtract tide predictions from measured water levels water_level -= tide return secs_rel_landfall, water_level def gauge_afteraxes(cd): station_id, station_name = stations[cd.gaugeno - 1] secs_rel_landfall, actual_level = <API key>(station_id) axes = plt.gca() axes.plot(secs_rel_landfall, actual_level, 'g') # Fix up plot - in particular fix time labels axes.set_title(station_name) axes.set_xlabel('Days relative to landfall') axes.set_ylabel('Surface (m)') axes.set_xlim(np.array([-3, 1]) * 86400) axes.set_ylim([-0.5, 2.5]) axes.set_xticks(np.linspace(-3, 1, 5) * 86400) axes.set_xticklabels([r"$-3$", r"$-2$", r"$-1$", r"$0$", r"$1$"]) axes.grid(True) # Plot wind speed using second scale wind_speed = np.linalg.norm(cd.gaugesoln.q[8:10, :], axis=0) axes2 = axes.twinx() axes2.plot(cd.gaugesoln.t, wind_speed, 'r.', markersize=0.3) axes2.set_ylabel('Wind Speed (m/s)') axes2.set_ylim([-2.5, 52.5]) # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes() plotaxes.afteraxes = gauge_afteraxes # Plot surface as blue curve: plotitem = plotaxes.new_plotitem(plot_type='1d_plot') plotitem.plot_var = 3 plotitem.plotstyle = 'b-' # Gauge Location Plot def <API key>(cd): plt.subplots_adjust(left=0.12, bottom=0.06, right=0.97, top=0.97) surge_afteraxes(cd) gaugetools.<API key>(cd.plotdata, gaugenos='all', format_string='ko', add_labels=True) plotfigure = plotdata.new_plotfigure(name="Gauge Locations") plotfigure.show = True # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes() plotaxes.title = 'Gauge Locations' plotaxes.scaled = True plotaxes.xlimits = [-91.5, -87.5] plotaxes.ylimits = [28.0, 31.0] plotaxes.afteraxes = <API key> surge.<API key>(plotaxes, bounds=surface_limits) plotaxes.plotitem_dict['surface'].amr_patchedges_show = [0] * 10 surge.add_land(plotaxes) plotaxes.plotitem_dict['land'].amr_patchedges_show = [0] * 10 # Parameters used only when creating html and/or latex hardcopy # e.g., via pyclaw.plotters.frametools.printframes: plotdata.printfigs = True # print figures plotdata.print_format = 'png' # file format plotdata.print_framenos = 'all' # list of frames to print plotdata.print_gaugenos = 'all' # list of gauges to print plotdata.print_fignos = 'all' # list of figures to print plotdata.html = True # create html files of plots? plotdata.html_homelink = '../README.html' # pointer for top of index plotdata.latex = True # create latex file of plots? plotdata.latex_figsperline = 2 # layout of plots plotdata.latex_framesperline = 1 # layout of plots plotdata.latex_makepdf = False # also run pdflatex? return plotdata
<!DOCTYPE html> <html class="no-js"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta charset="utf-8"> <meta content="IE=edge" http-equiv="X-UA-Compatible"> <meta name="keywords"> <meta name="description"> <!--base(href="#{dir}")--> <title>Citizens Advice style guide- Stop junk mail </title> <!-- Mobile Specific Metas--> <meta content="width=device-width, initial-scale=1, maximum-scale=2.0" name="viewport"> <meta content="<API key>" name="cab-guid"> <meta content="EWS" name="cab-extent"> <meta content="../../static/images/apple-touch-icon.png"> <meta content="<API key>" name="msvalidate.01"> <!-- Stylesheets--> <link href="../../css/guide.css" rel="stylesheet"> <link href="../../images/favicon/32.png" rel="shortcut icon"> <link href="../../images/favicon/228.png" rel="apple-touch-icon"> <script>/** * @fileoverview * * Scripts to go directly into the <head> element * These should be very small and therefore they should not be included as a file, but as inline JS * * This script needs minfiying before being added to the <head> */ ( function (document, window ) { /** * Update the no-js class to js */ var html = document.documentElement; html.className = html.className.replace(/\bno-js\b/, 'js'); /** * Creates a dummy version of $ * Any functions add will be queued to run after jQuery is built and ready */ window.$ = function (fn) { var q = window.$.q = window.$.q || []; q.push(fn); if (typeof fn !== 'function') { throw new Error('jQuery not yet loaded'); } }; /** * Cookie banner */ if (/\beprivacy=3(;|$)/i.test(document.cookie)) { html.className += ' hide-cookie-monster'; } /** * Are (session) cookies accepted */ document.cookie = 'z=1; path=/'; if (/(?:^| )z=1(?:;|$)/.test(document.cookie)) { document.cookie = 'z=; expires=' + new Date(0).toUTCString() + '; path=/'; } else { html.className = html.className += ' no-cookies'; } }( document, window )); </script> </head> <body><!--[if IE 8]><div class="ie8"><![endif]--> <div class="skip-nav"><a class="screenreader <API key>">Skip to content</a><a class="screenreader <API key>">Skip to footer</a></div> <header class="main-header"> <div class="<API key>"><a href="index.html" title="Citizens Advice home" class="main-header__logo"><img onerror="this.onerror=null;this.src='../../images/logos/ca-logo_100px.svg.png';" alt="Citizens Advice" src="../../images/ca-logo_100px.svg" height="80"><img onerror="this.onerror=null;this.src='../../images/logos/<API key>.svg.png';" alt="Citizens Advice" src="../../images/<API key>.svg" class="<API key> no-print wide"></a> <div data-track-zone="top-bar" class="main-header__links"><a href="" class="<API key> js-toggle-menu"><i class="icon-menu"></i>Menu</a> <nav class="<API key>"><a href="#">Cymraeg</a></a><a href="" class="hide-offline main-header__login"><i class="icon-key"></i>Sign-in</a></nav> <form action="" class="main-header__search hide-offline"> <label for="<API key>" class="screenreader">Search</label> <input id="<API key>" name="q" placeholder="" type="search" class="<API key>"> <button title="Search" type="submit" class="<API key>"><i class="icon-search icon--no-text"></i><span class="screenreader">Search</span></button> </form> </div> </div> </header> <nav data-track-zone="main-nav" style="overflow: visible;" class="main-nav"> <ul class="nav-list-primary"> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Benefits</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Work</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Debt and money</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Consumer</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Relationships</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Housing</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Law and rights</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Discrimination</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Tax</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Healthcare</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">Education</a></li> <li style="display: list-item;" class="top-item js-mega-menu"><a href="#">More from us</a></li> <li style="display: none;" class="<API key> js-more-menu"><a href="#">More<i class="icon-down"></i></a></li> </ul> </nav> <div class="main-container"> <nav class="main-breadcrumb"> <div class="<API key>"><span class="breadcrumb__item"><a href="../../index.html" title="Home">Home</a><i class="<API key>"></i></span><span class="breadcrumb__item"><a href="../../index.html#templates" title="Templates">Templates</a><i class="<API key>"></i></span><span class="breadcrumb__item">Content</span> </div> </nav> <div class="main-content"> <div id="main" role="main" class="main-content__right"> <div class="title"> <h1 class="title__heading js-ref"><span class="title__title">Stop junk mail</span></h1> </div> <div class="articleContent"> <div> <h2>Confirm your details</h2> <p>Please confirm your details are correct, you can go back to edit them.</p> <p>Your name<br>1 Road name<br>Townname<br>A1A1 A1A<br>email@address.com</p><a href="post-tool-2.html" class="btn-light left-button-icon">Edit details</a><a href="post-tool-4.html" class="btn right-button-icon">Confirm</a> </div> </div> </div> </div> </div> <div class="footer-feedback"> <h2 class="screenreader">Feedback</h2> <div class="<API key>"> <p>Is there anything wrong with this page? <a href="#">Let us know</a>.</p> </div> </div> <div id="footer" data-track-zone="footer" class="main-footer"> <div class="<API key> flex-row js-equal-height"> <div class="main-footer__box col-md-3 col-sm-6"> <h2>Advice</h2> <ul class="li--arrow"> <li><a href="#">Benefits</a></li> <li><a href="#">Work</a></li> <li><a href="#">Debt and money</a></li> <li><a href="#">Consumer</a></li> <li><a href="#">Relationships</a></li> <li><a href="#">Housing</a></li> <li><a href="#">Law and rights</a></li> <li><a href="#">Discrimination</a></li> <li><a href="#">Tax</a></li> <li><a href="#">Healthcare</a></li> <li><a href="#">Education</a></li> <li><a href="#">A to Z of advice</a></li> </ul> </div> <div class="main-footer__box col-md-3 col-sm-6"> <h2>Resources and tools</h2> <ul class="li--arrow"> <li><a href="#">Budgeting tool</a></li> <li><a href="#">Advice fact sheets</a></li> <li><a href="#">Advice online, by phone and in person</a></li> </ul> </div> <div class="main-footer__box col-md-3 col-sm-6"> <h2>More from us</h2> <ul class="li--arrow"> <li><a href="#">About us</a></li> <li><a href="#">Annual reports</a></li> <li><a href="#">Contact us</a></li> <li><a href="#">Complaints</a></li> <li><a href="#">Blogs</a></li> <li><a href="#">Campaigns</a></li> <li><a href="#">Media</a></li> <li><a href="#">Policy research</a></li> <li><a href="#">Support us</a></li> <li><a href="#">Volunteering</a></li> <li><a href="#">Jobs</a></li> </ul> </div> <div class="main-footer__box col-md-3 col-sm-6"> <h2>About Citizens Advice</h2> <ul class="li--arrow"> <li><a href="#">How we provide advice</a></li> <li><a href="#">The difference we make</a></li> <li><a href="#">Support us</a></li> <li><a href="#">How Citizens Advice works</a></li> <li><a href="#">Accessibility</a></li> <li><a href=" <li><a href="#">Privacy and cookies</a></li> </ul> </div> <div class="main-footer__box <API key>"> <div> <p><img alt="" height="100" src="../../images/ca-logo_100px.svg" width="100">Copyright © 2016 Citizens Advice. All rights reserved.<br>Citizens Advice is an operating name of the National Association of Citizens Advice Bureaux. Registered charity number 279057<br>VAT number 726 0202 76 Company limited by guarantee. Registered number 1436945 England<br>Registered office: Citizens Advice, 3rd Floor North, 200 Aldersgate, London, EC1A 4HD</p> </div> </div> </div> </div> <!-- Code changed, not using here as implimented through cms--> <!--.notice .notice__content p We no longer support Internet Explorer 8. To avoid problems viewing this website, please consider <a href="http://browsehappy.com/" class="a-external-link">upgrading your browser</a>. --><!--[if IE 8]></div><![endif]--> <script src="../../js/vendor/jquery-1.11.3.min.js"></script> <script src="../../js/translate.js"></script> <script src="../../js/jquery.fn.cssSlide.js"></script> <script src="../../js/revealable.js"></script> <script src="../../js/prism.js"></script> <script src="../../js/smooth.js"></script> <script src="../../js/jquery.fn.top-sticky.js"></script> <!--script(src="#{dir}js/advisor.js")--> <script src="../../js/sidebar.js"></script> <!--script(src="#{dir}js/core.js")--> <script src="../../js/clipboard.min.js"></script> <script> var clipboard = new Clipboard( '.a-social-copy', { text: function(trigger) { return window.location.href; } }); clipboard.on('success', function(e) { $( '.copied' ).fadeIn( 'fast' ); $( '.copied' ).delay(400).queue(function(){ $( this ).fadeOut( 'fast' ); $( this ).stop(); }); }); var filename = document.location.pathname.match(/[^\/]+$/)[0]; $(document).ready(function() { $('.section-nav a[href*="' + filename + '"]').addClass('active'); // Connect up LinkedIn buttons $('.a-social-linkedin').attr('href', "http: }); </script> <!-- GA script--> <script> (function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https: ga('create', 'UA-8734782-29', 'auto'); ga('send', 'pageview'); </script> </body> </html>
import fixtures from '../__fixtures__/ValidateSlug'; import { loadFixtures, unloadFixtures } from 'util/fixtures'; import gql from 'util/GraphQL'; import { assertSlugIsValid } from '../ValidateSlug'; import { errors } from 'graphql/models/SlugErrorEnum'; describe('assertSlugIsValid', () => { beforeAll(() => loadFixtures(fixtures)); afterAll(() => unloadFixtures(fixtures)); it('returns for valid slugs', async () => { await expect(assertSlugIsValid('valid', 'other-user')).resolves.toEqual( undefined ); await expect(assertSlugIsValid('space ok', 'other-user')).resolves.toEqual( undefined ); await expect(assertSlugIsValid('', 'other-user')).resolves.toEqual( undefined ); await expect(assertSlugIsValid('', 'other-user')).resolves.toEqual( undefined ); }); it('does not throw error if the slug is taken by the user themselves', async () => { await expect(assertSlugIsValid('taken', 'test-user')).resolves.toEqual( undefined ); }); it('throws slug error', async () => { await expect(assertSlugIsValid(' ', 'other-user')).rejects.toEqual( errors.EMPTY ); await expect( assertSlugIsValid(' leading space', 'other-user') ).rejects.toEqual(errors.NOT_TRIMMED); await expect( assertSlugIsValid('trailing space ', 'other-user') ).rejects.toEqual(errors.NOT_TRIMMED); await expect(assertSlugIsValid(':3', 'other-user')).rejects.toEqual( errors.HAS_URI_COMPONENT ); await expect(assertSlugIsValid('#_#', 'other-user')).rejects.toEqual( errors.HAS_URI_COMPONENT ); // await expect(assertSlugIsValid('1/2', 'other-user')).rejects.toEqual( errors.HAS_URI_COMPONENT ); await expect(assertSlugIsValid('taken', 'other-user')).rejects.toEqual( errors.TAKEN ); }); }); describe('ValidateSlug', () => { beforeAll(() => loadFixtures(fixtures)); afterAll(() => unloadFixtures(fixtures)); it('rejects anonymous user', async () => { await expect( gql` { ValidateSlug(slug: "foo") { success error } } `( {}, { appId: 'some-app', } ) ).resolves.<API key>(` Object { "data": Object { "ValidateSlug": null, }, "errors": Array [ [GraphQLError: userId is not set via query string.], ], } `); }); it('returns error for invalid slug', async () => { await expect( gql` { ValidateSlug(slug: "taken") { success error } } `( {}, { userId: 'other-user', appId: 'some-app', } ) ).resolves.<API key>(` Object { "data": Object { "ValidateSlug": Object { "error": "TAKEN", "success": false, }, }, } `); }); it('returns success for valid slug', async () => { await expect( gql` { ValidateSlug(slug: "valid") { success error } } `( {}, { userId: 'other-user', appId: 'some-app', } ) ).resolves.<API key>(` Object { "data": Object { "ValidateSlug": Object { "error": null, "success": true, }, }, } `); }); });
var path = require('path'); module.exports = { cache: true, entry: './src/scripts/main.js', output: { path: path.join(__dirname, 'dist', 'scripts'), publicPath: 'scripts/', filename: 'bundle.js' }, module: { loaders: [ { test: /\.css$/, loader: 'style!css' }, { test: /\.scss$/, loader: 'style!sass' }, { test: /\.js/, loader: 'jsx' }, { test: /\.jsx/, loader: 'jsx' } ] }, plugins: [] };
package com.veridu.endpoint; import org.json.simple.JSONObject; import com.veridu.exceptions.APIError; import com.veridu.exceptions.EmptyResponse; import com.veridu.exceptions.EmptySession; import com.veridu.exceptions.EmptyUsername; import com.veridu.exceptions.InvalidFormat; import com.veridu.exceptions.InvalidResponse; import com.veridu.exceptions.InvalidUsername; import com.veridu.exceptions.RequestFailed; import com.veridu.storage.Storage; public class State extends AbstractEndpoint { public State(String key, String version, String secret, Storage storage) { super(key, version, secret, storage); } public String retrieve() throws EmptyUsername, EmptyResponse, InvalidFormat, InvalidResponse, APIError, RequestFailed, EmptySession, InvalidUsername { if (this.storage.isUsernameEmpty()) throw new EmptyUsername(); return retrieve(this.storage.getUsername()); } public String retrieve(String username) throws InvalidUsername, EmptySession, EmptyUsername, EmptyResponse, InvalidFormat, InvalidResponse, APIError, RequestFailed { if (this.storage.isSessionEmpty()) throw new EmptySession(); if (!State.validateUsername(username)) throw new InvalidUsername(); JSONObject json = this.fetch("GET", String.format("state/%s", username)); return json.get("state").toString(); } }
#ifndef <API key> #define <API key> #include <set> #include <map> #include <boost/noncopyable.hpp> #include <boost/thread.hpp> #include "connection.h" #include "net.h" <API key> // TCP class ConnectionManager : private boost::noncopyable { public: Add the specified connection to the manager and start it. void start(ConnectionPtr c); Stop the specified connection. void stop(ConnectionPtr c); void stop(uint32 id); Stop all connections. void stop_all(); template <typename ProtoT> void sendTo(uint32 id, const ProtoT& proto) { boost::mutex::scoped_lock slock(connections_lock_); ConnectionMap::iterator it = connections_.find(id); if (it != connections_.end()) { it->second->send(proto); } } template <typename ProtoT> void broadcastTo(uint32 type, const ProtoT& proto) { boost::mutex::scoped_lock slock(connections_lock_); for (ConnectionMap::iterator it = connections_.begin(); it != connections_.end(); ++ it) if (it->second->type() == type) it->second->send(proto); } template <typename ProtoT> void broadcastToAll(const ProtoT& proto) { boost::mutex::scoped_lock slock(connections_lock_); for (ConnectionMap::iterator it = connections_.begin(); it != connections_.end(); ++ it) it->second->send(proto); } size_t size() { return connections_.size(); } private: typedef std::map<uint32, ConnectionPtr> ConnectionMap; The managed connections. ConnectionMap connections_; boost::mutex connections_lock_; }; <API key> #endif // <API key>
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // 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: // in all copies or substantial portions of the Software. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // 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 "<API key>.h" <API key>::<API key>() { } <API key>::~<API key>() { } CIMInstance <API key>::constructInstance( const CIMName &className, const CIMNamespaceName &nameSpace, const <API key> &_p) { CIMProperty p; CIMInstance inst(className); // Set path inst.setPath(CIMObjectPath(String(""), // hostname nameSpace, CIMName("<API key>"), <API key>(_p))); //CIM_ManagedElement Properties if (_p.getInstanceID(p)) inst.addProperty(p); if (_p.getCaption(p)) inst.addProperty(p); if (_p.getDescription(p)) inst.addProperty(p); if (_p.getElementName(p)) inst.addProperty(p); //CIM_StatisticalData Properties if (_p.<API key>(p)) inst.addProperty(p); if (_p.getStatisticTime(p)) inst.addProperty(p); if (_p.getSampleInterval(p)) inst.addProperty(p); //<API key> Properties if (_p.getBytesTransmitted(p)) inst.addProperty(p); if (_p.getBytesReceived(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.getPacketsReceived(p)) inst.addProperty(p); //<API key> Properties if (_p.getLIPCount(p)) inst.addProperty(p); if (_p.getNOSCount(p)) inst.addProperty(p); if (_p.getErrorFrames(p)) inst.addProperty(p); if (_p.getDumpedFrames(p)) inst.addProperty(p); if (_p.getLinkFailures(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.getCRCErrors(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.getFramesTooShort(p)) inst.addProperty(p); if (_p.getFramesTooLong(p)) inst.addProperty(p); if (_p.getAddressErrors(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.getDelimiterErrors(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.getFBSYFrames(p)) inst.addProperty(p); if (_p.getPBSYFrames(p)) inst.addProperty(p); if (_p.getFRJTFrames(p)) inst.addProperty(p); if (_p.getPRJTFrames(p)) inst.addProperty(p); if (_p.getRXClass1Frames(p)) inst.addProperty(p); if (_p.getTXClass1Frames(p)) inst.addProperty(p); if (_p.getClass1FBSY(p)) inst.addProperty(p); if (_p.getClass1PBSY(p)) inst.addProperty(p); if (_p.getClass1FRJT(p)) inst.addProperty(p); if (_p.getClass1PRJT(p)) inst.addProperty(p); if (_p.getRXClass2Frames(p)) inst.addProperty(p); if (_p.getTXClass2Frames(p)) inst.addProperty(p); if (_p.getClass2FBSY(p)) inst.addProperty(p); if (_p.getClass2PBSY(p)) inst.addProperty(p); if (_p.getClass2FRJT(p)) inst.addProperty(p); if (_p.getClass2PRJT(p)) inst.addProperty(p); if (_p.getRXClass3Frames(p)) inst.addProperty(p); if (_p.getTXClass3Frames(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); if (_p.<API key>(p)) inst.addProperty(p); return inst; } Array<CIMKeyBinding> <API key>::<API key>(const <API key>& _p) { Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding( <API key>, _p.getInstanceID(), CIMKeyBinding::STRING)); return keys; } #define UNIX_PROVIDER <API key> #define UNIX_PROVIDER_NAME "<API key>" #define <API key> <API key> #define <API key> "<API key>" #define BASE_CLASS_NAME "<API key>" #define <API key> 0 #include "UNIXProviderBase.hpp"
WarriorJS Core extracts the mechanics of the original WarriorJS game, allowing you to build and share your own WarriorJS universes (known as *towers*) with custom abilities, effects, units and levels. [![Build Status](https: [![Codecov](https: [![styled with prettier](https: Installation bash $ yarn add warriorjs-core Documentation *Coming soon.* Logo You can find the official WarriorJS logo in all its flavors [here](logo). License MIT
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Brython documentation</title> <link rel="stylesheet" href="../doc_brython.css"> <script src="/src/brython.js"></script> <script type="text/python3"> from browser import window, document, html import highlight import header header.show('../../', 'es') def run(ev): # run the code in the elt after the button ix = ev.target.parent.children.index(ev.target) elt = ev.target.parent.children[ix+1] exec(elt.text, {}) elt.focus() target = 'content' for elt in document[target].get(selector='.exec'): # Python code executed when user clicks on a button elt.contentEditable = True src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h elt.focus() btn = html.BUTTON('') btn.bind('click', run) elt.parent.insertBefore(btn, elt) for elt in document[target].get(selector='.exec_on_load'): # Python code executed on page load src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h exec(src, {}) for elt in document[target].get(selector='.python'): src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() </script> </head> <body onLoad="brython(1)"> <scripts> <table id=banner cellpadding=0 cellspacing=0> <tr id=banner_row > <td class="logo"><a href="../../index.html"><img src="/brython.png" class="logo"></a></td> </tr> </table> <table width="100%"> <tr> <td style="width:20%;vertical-align:top;"> <h4><a class="navig" href="intro.html">Introducción</a></h4> <h4><a class="navig" href="faq.html">Preguntas frecuentes (faq)</a></h4> <h4><a class="navig" href="syntax.html">Sintaxis, palabras clave y funciones integradas</a></h4> <h4><a class="navig" href="import.html">Implementación del <tt>import</tt></a></h4> <h4>Interfaz del navegador</h4> <div style="padding-left:10px;"> <a class="navig" href="dom_api.html">Introducción - DOM API</a> <br><a class="navig" href="create.html">Creando un documento</a> <br><a class="navig" href="access.html">Accediendo a los elementos</a> <br><a class="navig" href="attributes.html">Atributos y métodos</a> <br> <br><a class="navig" href="events.html">Eventos</a> <br><a class="navig" href="mouse_events.html">Eventos del ratón</a> <br><a class="navig" href="keyboard_events.html">Eventos del teclado</a> <br><a class="navig" href="focus_events.html">Eventos de foco</a> <br><a class="navig" href="drag_events.html">Eventos de arrastre</a> <br> <br><a class="navig" href="query.html">Query string</a> <br><a class="navig" href="jsobjects.html">Usando objetos y librerías Javascript</a> </div> <h4>Módulos específicos de Brython</h4> <div style="padding-left:10px;"> <a class="navig" href="browser.html">El módulo integrado `browser`</a> <br><a class="navig" href="ajax.html">browser.ajax</a> <br><a class="navig" href="html.html">browser.html</a> <br><a class="navig" href="local_storage.html">browser.local_storage</a> <br><a class="navig" href="markdown.html">browser.markdown</a> <br><a class="navig" href="object_storage.html">browser.object_storage</a> <br><a class="navig" href="local_storage.html">browser.session_storage</a> <br><a class="navig" href="svg.html">browser.svg</a> <br><a class="navig" href="timer.html">browser.timer</a> <br><a class="navig" href="websockets.html">browser.websocket</a> <br> <br><a class="navig" href="javascript.html">javascript</a> </div> <h4>Trabajando con Brython</h4> <div style="padding-left:10px;"> <a class="navig" href="options.html">Opciones de la función <code>brython()</code></a> <br><a class="navig" href="dev_env.html">Instalando el entorno de desarrollo</a> <br><a class="navig" href="test.html">Testing y depuración</a> <br><a class="navig" href="deploy.html">Desplegando una aplicación</a></div> <h4>Brython para Firefox OS</h4> <div style="padding-left:10px;"> <a class="navig" href="firefox_os_intro.html">Introducción</a> <br><a class="navig" href="firefox_os_tuto1.html">WebApps : diseño</a> <br><a class="navig" href="firefox_os_tuto2.html">WebApps : aplicación</a> </div> <h4>Cookbook</h4> <div style="padding-left:10px;"> <a class="navig" href="cookbook/hello_world.html">Hola Mundo !</a> <br><a class="navig" href="cookbook/content_in_div.html">Insertar contenido en un elemento</a> <br><a class="navig" href="cookbook/basic_markup.html">Marcado HTML (bold,italic...)</a> <br><a class="navig" href="cookbook/table.html">Tabla HTML</a> <br><a class="navig" href="cookbook/select_checkbox.html">Handle options in a SELECT</a> <br><a class="navig" href="cookbook/drag_drop.html">Arrastrar y soltar</a> <br><a class="navig" href="cookbook/get_content.html">Obtener el contenido de un elemento</a> <br><a class="navig" href="cookbook/read_file.html">Leer el contenido de un fichero</a> <br><a class="navig" href="cookbook/local_storage.html">Almnacenar objetos localmente</a> <br><a class="navig" href="cookbook/<API key>.html">Ejemplo de onmouseover</a> </div> </td> <td id="content" style="vertical-align:top;"> &nbsp;<p><H2>Query string</H2> <p></p> <STRONG>browser</STRONG>.<code>document</code> soporta el atributo <code>query</code>, que devuelve la cadena pedida como un objeto con los siguientes atributos y métodos : <p></p> <ul> <li> <code>document.query[<i>key</i>]</code> : devuelve el valor asociado con <I><code>key</code></I>. Si una clave tiene m&aacute;s de un valor (caso, por ejemplo, de etiquetas SELECT con el atributo MULTIPLE o para etiquetas <code>&lt;INPUT type="checkbox"&gt;</code>), devuelve una lista de los valores. Se obtendr&aacute; un <code>KeyError</code> si no hay valor asociado con la clave <p></p> <li> <code>document.query.getfirst(<i>key[,default]</i>)</code> : devuelve el primer valor para <I><code>key</code></I>. Si no existe un valor asociado con la clave, devolver&aacute; <I><code>default</code></I> si se le proporciona, en otros casos devolver&aacute; <code>None</code> <p></p> <li> <code>document.query.getlist(<i>key</i>)</code> : devuelve la lista de valores asociados con <I><code>key</code></I> (devolver&aacute; una lista vacia en el caso de que no haya valor asociado a la clave) <p></p> <li> <code>document.query.getvalue(<i>key[,default]</i>)</code> : mismo comportamiento que <code>doc.query[key]</code>, pero devuelve <I><code>default</code></I> o <code>None</code> si no hay valor asociado a la clave <p></p> <p></p> </ul></p> </td> </tr> </table> </html>
var val = invContext.keyToWatch; var argumentsVal = args.cmdArguments; var argsArr = argumentsVal.split(","); var argsToCmd = {}; for (i = 0; i < argsArr.length ; i++) { var keyval = argsArr[i].split("="); if (keyval.length == 2) { argsToCmd[keyval[0].trim()] = keyval[1]; } } var entry = executeCommand(args.cmdToRun, argsToCmd); if(!entry[0].EntryContext[args.keyToWatch]){ return entry; } else{ throw args.keyToWatch + ' in context is not empty'; }
#include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/prctl.h> #include <unistd.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/hci_lib.h> #include "utility.h" int lastSignal = 0; static void signalHandler(int signal) { lastSignal = signal; } int main(int argc, const char* argv[]) { char *hciDeviceIdOverride = NULL; int hciDeviceId = 0; int hciSocket; struct hci_dev_info hciDevInfo; struct hci_filter oldHciFilter; struct hci_filter newHciFilter; socklen_t oldHciFilterLen; int <API key> = -1; int currentAdapterState; const char* adapterState = NULL; fd_set rfds; struct timeval tv; int selectRetval; unsigned char hciEventBuf[HCI_MAX_EVENT_SIZE]; int hciEventLen; evt_le_meta_event *leMetaEvent; le_advertising_info *leAdvertisingInfo; char btAddress[18]; int i; int scanning = 0; int8_t rssi; memset(&hciDevInfo, 0x00, sizeof(hciDevInfo)); // setup signal handlers signal(SIGINT, signalHandler); signal(SIGKILL, signalHandler); signal(SIGUSR1, signalHandler); signal(SIGUSR2, signalHandler); signal(SIGHUP, signalHandler); prctl(PR_SET_PDEATHSIG, SIGKILL); // remove buffering setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); hciDeviceIdOverride = getenv("NOBLE_HCI_DEVICE_ID"); if (hciDeviceIdOverride != NULL) { hciDeviceId = atoi(hciDeviceIdOverride); } else { // if no env variable given, use the first available device hciDeviceId = hci_get_route(NULL); } if (hciDeviceId < 0) { hciDeviceId = 0; // use device 0, if device id is invalid } // setup HCI socket hciSocket = hci_open_dev(hciDeviceId); if (hciSocket == -1) { printf("adapterState unsupported\n"); return -1; } hciDevInfo.dev_id = hciDeviceId; // get old HCI filter oldHciFilterLen = sizeof(oldHciFilter); getsockopt(hciSocket, SOL_HCI, HCI_FILTER, &oldHciFilter, &oldHciFilterLen); // setup new HCI filter hci_filter_clear(&newHciFilter); <API key>(HCI_EVENT_PKT, &newHciFilter); <API key>(EVT_LE_META_EVENT, &newHciFilter); setsockopt(hciSocket, SOL_HCI, HCI_FILTER, &newHciFilter, sizeof(newHciFilter)); // disable scanning, it may have been left on, if so <API key> will fail without this <API key>(hciSocket, 0x00, 0, 1000); while(1) { FD_ZERO(&rfds); FD_SET(hciSocket, &rfds); tv.tv_sec = 1; tv.tv_usec = 0; // get HCI dev info for adapter state ioctl(hciSocket, HCIGETDEVINFO, (void *)&hciDevInfo); currentAdapterState = hci_test_bit(HCI_UP, &hciDevInfo.flags); if (<API key> != currentAdapterState) { <API key> = currentAdapterState; if (!currentAdapterState) { adapterState = "poweredOff"; } else if (<API key>(hciSocket, 0x01, htobs(0x0010), htobs(0x0010), 0x00, 0, 1000) < 0) { if (EPERM == errno) { adapterState = "unauthorized"; } else if (EIO == errno) { adapterState = "unsupported"; } else { adapterState = "unknown"; } } else { adapterState = "poweredOn"; } printf("adapterState %s\n", adapterState); } selectRetval = select(hciSocket + 1, &rfds, NULL, NULL, &tv); if (-1 == selectRetval) { if (SIGINT == lastSignal || SIGKILL == lastSignal) { // done break; } else if (SIGUSR1 == lastSignal) { // start scan, filter scanning = 1; <API key>(hciSocket, 0x00, 1, 1000); <API key>(hciSocket, 0x01, 1, 1000); } else if (SIGUSR2 == lastSignal) { // start scan, no filter scanning = 1; <API key>(hciSocket, 0x00, 0, 1000); <API key>(hciSocket, 0x01, 0, 1000); } else if (SIGHUP == lastSignal) { // stop scan scanning = 0; <API key>(hciSocket, 0x00, 0, 1000); } } else if (selectRetval) { // read event hciEventLen = read(hciSocket, hciEventBuf, sizeof(hciEventBuf)); leMetaEvent = (evt_le_meta_event *)(hciEventBuf + (1 + HCI_EVENT_HDR_SIZE)); hciEventLen -= (1 + HCI_EVENT_HDR_SIZE); if (!scanning) { // ignore, not scanning continue; } if (leMetaEvent->subevent != 0x02) { continue; } leAdvertisingInfo = (le_advertising_info *)(leMetaEvent->data + 1); ba2str(&leAdvertisingInfo->bdaddr, btAddress); printf("event %s,%s,", btAddress, (leAdvertisingInfo->bdaddr_type == LE_PUBLIC_ADDRESS) ? "public" : "random"); for (i = 0; i < leAdvertisingInfo->length; i++) { printf("%02x", leAdvertisingInfo->data[i]); } rssi = *(leAdvertisingInfo->data + leAdvertisingInfo->length); printf(",%d\n", rssi); } } // restore original filter setsockopt(hciSocket, SOL_HCI, HCI_FILTER, &oldHciFilter, sizeof(oldHciFilter)); // disable LE scan <API key>(hciSocket, 0x00, 0, 1000); close(hciSocket); return 0; }
<!DOCTYPE html><html><head><link rel="canonical" href="http:
#include "shell/common/gin_converters/image_converter.h" #include "shell/common/api/<API key>.h" #include "shell/common/gin_converters/file_path_converter.h" #include "ui/gfx/image/image_skia.h" namespace gin { bool Converter<gfx::ImageSkia>::FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, gfx::ImageSkia* out) { gfx::Image image; if (!ConvertFromV8(isolate, val, &image)) return false; *out = image.AsImageSkia(); return true; } bool Converter<gfx::Image>::FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, gfx::Image* out) { if (val->IsNull()) return true; // First see if the user has passed a path. electron::api::NativeImage* native_image = nullptr; base::FilePath icon_path; if (gin::ConvertFromV8(isolate, val, &icon_path)) { native_image = electron::api::NativeImage::CreateFromPath(isolate, icon_path).get(); if (native_image->image().IsEmpty()) return false; } else { // Try a normal nativeImage if that fails. if (!gin::ConvertFromV8(isolate, val, &native_image)) return false; } *out = native_image->image(); return true; } v8::Local<v8::Value> Converter<gfx::Image>::ToV8(v8::Isolate* isolate, const gfx::Image& val) { return gin::ConvertToV8(isolate, electron::api::NativeImage::Create(isolate, val)); } } // namespace gin
html, body { margin: 0; padding: 0; font-family: Arial,serif; font-size: 12px; color: grey; font-weight: normal; } h1 { font-family: Arial; font-size: 16px; }
<?php namespace Oro\Bundle\EmailBundle\Tests\Functional; use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase; /** * @dbIsolation */ class EmailControllerTest extends WebTestCase { protected function setUp() { $this->initClient(array(), $this-><API key>()); $this->loadFixtures(['Oro\Bundle\EmailBundle\Tests\Functional\DataFixtures\LoadEmailData']); } public function testView() { $url = $this->getUrl('oro_email_view', ['id' => $this->getReference('email_1')->getId()]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); $content = $result->getContent(); $this->assertContains('My Web Store Introduction', $content); $this->assertContains('Thank you for signing up to My Web Store!', $content); } public function testItems() { $ids = implode(',', [ $this->getReference('email_1')->getId(), $this->getReference('email_2')->getId(), $this->getReference('email_3')->getId() ]); $url = $this->getUrl('<API key>', ['ids' => $ids]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); } public function testItemsBlank() { $url = $this->getUrl('<API key>'); $this->client->request('GET', $url); $result = $this->client->getResponse(); $content = $result->getContent(); $this->assertEquals("", $content); $this-><API key>($result, 200); } public function testCreateViewForm() { $url = $this->getUrl('<API key>', [ '_widgetContainer' => 'dialog' ]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); $content = $result->getContent(); $this->assertContains('From', $content); } public function testBody() { $url = $this->getUrl('oro_email_body', ['id' => $this->getReference('emailBody_1')->getId()]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); $content = $result->getContent(); $this->assertContains('Thank you for signing up to My Web Store!', $content); } public function testActivity() { $this->markTestIncomplete('Skipped. Need activity fixture'); $url = $this->getUrl('<API key>', [ 'entityClass' => 'test', 'entityId' => 1 ]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); } public function testAttachment() { $this->markTestIncomplete('Skipped. Need attachment fixture'); $url = $this->getUrl('<API key>', [ 'id' => 1 ]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); } public function testEmails() { $url = $this->getUrl('<API key>', ['_widgetContainer' => 'dialog']); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); } public function testBaseEmails() { $url = $this->getUrl('<API key>', ['_widgetContainer' => 'dialog']); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); } public function testUserEmails() { $url = $this->getUrl('<API key>', ['_widgetContainer' => 'dialog']); $this->client->request('GET', $url); $result = $this->client->getResponse(); $this-><API key>($result, 200); } public function testEmailToggleSeen() { $url = $this->getUrl('<API key>', ['id' => $this->getReference('emailUser_1')->getId()]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $data = json_decode($result->getContent(), true); $this->assertTrue($data['successful']); } public function testEmailMarkSeen() { $emailId = $this->getReference('emailUser_1')->getEmail()->getId(); $url = $this->getUrl('oro_email_mark_seen', ['id' => $emailId, 'status' => 1]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $data = json_decode($result->getContent(), true); $this->assertTrue($data['successful']); $url = $this->getUrl('oro_email_mark_seen', ['id' => $emailId, 'status' => 0, 'checkThread' => 0]); $this->client->request('GET', $url); $result = $this->client->getResponse(); $data = json_decode($result->getContent(), true); $this->assertTrue($data['successful']); } public function <API key>() { $url = $this->getUrl('<API key>'); $this->client->request('GET', $url); $result = $this->client->getResponse(); $data = json_decode($result->getContent(), true); $this->assertTrue($data['successful']); } public function testMarkReadMass() { $url = $this->getUrl( '<API key>', [ 'gridName' => 'user-email-grid', 'actionName' => 'emailmarkread', 'user-email-grid[userId]' => $this->getReference('simple_user')->getId(), 'inset' => 1, 'values' => $this->getReference('<API key>')->getId() ] ); $this->client->request('GET', $url); $result = $this->client->getResponse(); $data = json_decode($result->getContent(), true); $this->assertTrue($data['successful'] === true); $this->assertTrue($data['count'] === 1); } public function testMarkUnreadMass() { $url = $this->getUrl( '<API key>', [ 'gridName' => 'user-email-grid', 'actionName' => 'emailmarkunread', 'user-email-grid[userId]' => $this->getReference('simple_user')->getId(), 'inset' => 1, 'values' => $this->getReference('<API key>')->getId() ] ); $this->client->request('GET', $url); $result = $this->client->getResponse(); $data = json_decode($result->getContent(), true); $this->assertTrue($data['successful'] === true); $this->assertTrue($data['count'] === 1); } public function testReply() { $email = $this->getReference('email_1'); $id = $email->getId(); $url = $this->getUrl('<API key>', ['id' => $id, '_widgetContainer' => 'dialog']); $this->client->request('GET', $url); $response = $this->client->getResponse(); $this-><API key>($response, 200); $crawler = $this->client->getCrawler(); $this->assertEquals(1, $crawler->filter('div.widget-content input[name=\'oro_email_email[cc]\']')->count()); $this->assertEquals( 1, $crawler->filter('div.widget-content input[value=\'' . $email->getFromName() . '\']')->count() ); $cc = $email->getCc()->first()->getEmailAddress()->getEmail(); $this->assertEquals( 0, $crawler->filter('div.widget-content input[value=\'' . $cc . '\']')->count() ); $bcc = $email->getBcc()->first()->getEmailAddress()->getEmail(); $this->assertEquals( 0, $crawler->filter('div.widget-content input[value=\'' . $bcc . '\']')->count() ); } public function testReplyAll() { $email = $this->getReference('email_1'); $id = $email->getId(); $url = $this->getUrl('<API key>', ['id' => $id, '_widgetContainer' => 'dialog']); $this->client->request('GET', $url); $response = $this->client->getResponse(); $this-><API key>($response, 200); $crawler = $this->client->getCrawler(); $this->assertEquals(1, $crawler->filter('div.widget-content input[name=\'oro_email_email[cc]\']')->count()); $this->assertEquals( 1, $crawler->filter('div.widget-content input[value=\'' . $email->getFromName() . '\']')->count() ); $cc = $email->getCc()->first()->getEmailAddress()->getEmail(); $this->assertEquals( 1, $crawler->filter('div.widget-content input[value=\'' . $cc . '\']')->count() ); $bcc = $email->getBcc()->first()->getEmailAddress()->getEmail(); $this->assertEquals( 0, $crawler->filter('div.widget-content input[value=\'' . $bcc . '\']')->count() ); } public function testGetLastEmail() { $url = $this->getUrl('oro_email_last'); $this->client->request('GET', $url); $response = $this-><API key>($this->client->getResponse(), 200); $this->assertEquals(1, $response['count']); $this->assertCount(1, $response['emails']); } }
// UIView+BUKDynamicPopView.h // Pods #import <UIKit/UIKit.h> #import "BUKDynamicBehavior.h" #import "<API key>.h" #import "<API key>.h" /** * Notification support for view transition. */ extern NSString * <API key>; extern NSString * <API key>; extern NSString * <API key>; extern NSString * <API key>; @interface UIView (BUKDynamicPopView) /** * Behavior for dynamic show animation. If behavior is nil, `<API key>` will be * used. * * @see <API key> */ @property (nonatomic, strong) id<BUKDynamicBehavior> <API key> <API key>; /** * Behavior for dynamic hide animation. If behavior is nil, `<API key>` will be * used. * * @see <API key> */ @property (nonatomic, strong) id<BUKDynamicBehavior> <API key> <API key>; /** * Style used to decide the position of self before show, when showing, and after hide. If style * is nil, `<API key>` from outer top to outer bottom will be used. * * @see <API key> */ @property (nonatomic, strong) id<<API key>> buk_animationStyle <API key>; /** * Background inserted below self. If background is nil, a black translucent view will be used. */ @property (nonatomic, strong) UIView *<API key> <API key>; /** * You can tap background to dynamic hide self by default. If you don't want this feature, you * can set this property to NO to disable it. * * @warning This flag only disable the tap gesture, but the background is still showing. You can * directly set the <API key> to hidden if you want. */ @property (nonatomic, assign) BOOL <API key> <API key>; /** * Flag for you to known whether the pop view is animating for push or pop. */ @property (nonatomic, assign, readonly) BOOL <API key>; /** * Dynamic show hide event delegate. */ @property (nonatomic, weak) id<<API key>> <API key>; /** * Add self to superView, and dynamic show self using `<API key>`. Behavior will * be used to animate self's center from `[self.buk_animationStyle <API key>]` * to `[self.buk_animationStyle <API key>]`. * * @see <API key> * @see buk_animationStyle */ - (void)<API key>:(UIView *)superView; /** * Insert self into superView below otherView, and then do things same as `- <API key>`. * * @see - (void)<API key>:(UIView *)superView; */ - (void)<API key>:(UIView *)superView belowView:(UIView *)otherView; /** * Insert self into superView above otherView, and then do things same as `- <API key>`. * * @see - (void)<API key>:(UIView *)superView; */ - (void)<API key>:(UIView *)superView aboveView:(UIView *)otherView; /** * Dynamic hide self useing `<API key>`. Behavior will be used to animate self's * center from current value to `[self.buk_animationStyle <API key>]`. * * @see <API key> * @see buk_animationStyle */ - (void)buk_dynamicHide; @end
#include "FP_miniIMU.h" #include "FP_Math.h" #include "FP_Matrix.h" #include "FastMath.h" //S16.16 //precision 1 / 2^16 = 0.0000152587890625 //all parameters below need to be tune #define FP_EKF_PQ_INITIAL 66//0.001 #define FP_EKF_QQ_INITIAL 66//0.001 #define FP_EKF_RA_INITIAL 1638//0.025 #if FP_EKF_STATE_DIM == 7 #define FP_EKF_PWB_INITIAL 66//0.001f #define FP_EKF_QWB_INITIAL 7//0.0001f #endif static Q16 I[FP_EKF_STATE_DIM * FP_EKF_STATE_DIM] = { #if EKF_STATE_DIM == 4 Q16_One, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, Q16_One, #else //EKF_STATE_DIM == 7 Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, #endif }; static Q16 P[FP_EKF_STATE_DIM * FP_EKF_STATE_DIM] = { #if FP_EKF_STATE_DIM == 4 FP_EKF_PQ_INITIAL, 0, 0, 0, 0, FP_EKF_PQ_INITIAL, 0, 0, 0, 0, FP_EKF_PQ_INITIAL, 0, 0, 0, 0, FP_EKF_PQ_INITIAL, #else //FP_EKF_STATE_DIM == 7 FP_EKF_PQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_PQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_PQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_PQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_PWB_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_PWB_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_PWB_INITIAL, #endif }; static Q16 Q[FP_EKF_STATE_DIM * FP_EKF_STATE_DIM] = { #if FP_EKF_STATE_DIM == 4 FP_EKF_QQ_INITIAL, 0, 0, 0, 0, FP_EKF_QQ_INITIAL, 0, 0, 0, 0, FP_EKF_QQ_INITIAL, 0, 0, 0, 0, FP_EKF_QQ_INITIAL, #else //FP_EKF_STATE_DIM == 7 FP_EKF_QQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_QQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_QQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_QQ_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_QWB_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_QWB_INITIAL, 0, 0, 0, 0, 0, 0, 0, FP_EKF_QWB_INITIAL, #endif }; static Q16 R[<API key> * <API key>] = { FP_EKF_RA_INITIAL, 0, 0, 0, FP_EKF_RA_INITIAL, 0, 0, 0, FP_EKF_RA_INITIAL, }; static Q16 F[FP_EKF_STATE_DIM * FP_EKF_STATE_DIM] = { #if FP_EKF_STATE_DIM == 4 Q16_One, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, Q16_One, #else //FP_EKF_STATE_DIM == 7 Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, 0, 0, 0, 0, 0, 0, 0, Q16_One, #endif }; static Q16 H[<API key> * FP_EKF_STATE_DIM] = { #if FP_EKF_STATE_DIM == 4 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #else //FP_EKF_STATE_DIM == 7 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #endif }; //state static Q16 X[FP_EKF_STATE_DIM]; static Q16 KY[FP_EKF_STATE_DIM]; //measurement static Q16 Y[<API key>]; static Q16 CBn[9]; static Q16 PX[FP_EKF_STATE_DIM * FP_EKF_STATE_DIM]; static Q16 PXX[FP_EKF_STATE_DIM * FP_EKF_STATE_DIM]; static Q16 PHT[FP_EKF_STATE_DIM * <API key>]; static Q16 K[FP_EKF_STATE_DIM * <API key>]; static Q16 S[<API key> * <API key>]; void FP_EKF_IMUInit(float *accel, float *gyro) { //NED coordinate system unit vector float nedVector[3] = {0, 0 , -1.0f}; float accelVector[3] = {0, 0 , 0}; float norm; float crossVector[3]; float sinwi, cosw, sinhalfw, coshalfw; float q[4]; //unit accel norm = FastSqrtI(accel[0] * accel[0] + accel[1] * accel[1] + accel[2] * accel[2]); accelVector[0] = accel[0] * norm; accelVector[1] = accel[1] * norm; accelVector[2] = accel[2] * norm; //cross product between accel and reference crossVector[0] = accelVector[1] * nedVector[2] - accelVector[2] * nedVector[1]; crossVector[1] = accelVector[2] * nedVector[0] - accelVector[0] * nedVector[2]; crossVector[2] = accelVector[0] * nedVector[1] - accelVector[1] * nedVector[0]; sinwi = FastSqrtI(crossVector[0] * crossVector[0] + crossVector[1] * crossVector[1] + crossVector[2] * crossVector[2]); crossVector[0] *= sinwi; crossVector[1] *= sinwi; crossVector[2] *= sinwi; //the angle between accel and reference is the dot product of the two vectors cosw = accelVector[0] * nedVector[0] + accelVector[1] * nedVector[1] + accelVector[2] * nedVector[2]; coshalfw = FastSqrt(0.5f + 0.5f * cosw); sinhalfw = FastSqrt(0.5f - 0.5f * cosw); q[0] = coshalfw; q[1] = crossVector[0] * sinhalfw; q[2] = crossVector[1] * sinhalfw; q[3] = crossVector[2] * sinhalfw; X[0] = FT_Q16(q[0]); X[1] = FT_Q16(q[1]); X[2] = FT_Q16(q[2]); X[3] = FT_Q16(q[3]); } void FP_EKF_IMUUpdate(float *gyro, float *accel, float dt) { Q16 halfdx, halfdy, halfdz; Q16 neghalfdx, neghalfdy, neghalfdz; #if FP_EKF_STATE_DIM == 7 Q16 halfdtq0, neghalfdtq0, halfdtq1, neghalfdtq1, halfdtq2, neghalfdtq2, halfdtq3, neghalfdtq3; #endif Q16 halfdt = FP_SMUL(32768, FT_Q16(dt)); Q16 _2q0,_2q1,_2q2,_2q3; Q16 q0, q1, q2, q3; Q16 SI[<API key> * <API key>] = {0}; int __al, __ah; Q16 gx = FT_Q16(gyro[0]); Q16 gy = FT_Q16(gyro[1]); Q16 gz = FT_Q16(gyro[2]); float norm; Q16 qNorm; #if FP_EKF_STATE_DIM == 4 halfdx = FP_SMUL(halfdt, gx); halfdy = FP_SMUL(halfdt, gy); halfdz = FP_SMUL(halfdt, gz); #else //EKF_STATE_DIM == 7 halfdx = FP_SMUL(halfdt, FP_SUBS(gx, X[4])); halfdy = FP_SMUL(halfdt, FP_SUBS(gy, X[5])); halfdz = FP_SMUL(halfdt, FP_SUBS(gz, X[6])); #endif neghalfdx = -halfdx; neghalfdy = -halfdy; neghalfdz = -halfdz; q0 = X[0]; q1 = X[1]; q2 = X[2]; q3 = X[3]; #if FP_EKF_STATE_DIM == 4 /* F[0] = Q16_One; */ F[1] = neghalfdx; F[2] = neghalfdy; F[3] = neghalfdz; F[4] = halfdx; /* F[5] = Q16_One; */ F[6] = neghalfdz; F[7] = halfdy; F[8] = halfdy; F[9] = halfdz; /* F[10] = Q16_One; */ F[11] = neghalfdx; F[12] = halfdz; F[13] = neghalfdy; F[14] = halfdx; /* F[15] = Q16_One; */ #else halfdtq0 = FP_SMUL(halfdt, q0); neghalfdtq0 = -halfdtq0; halfdtq1 = FP_SMUL(halfdt, q1); neghalfdtq1 = -halfdtq1; halfdtq2 = FP_SMUL(halfdt, q2); neghalfdtq2 = -halfdtq2; halfdtq3 = FP_SMUL(halfdt, q3); neghalfdtq3 = -halfdtq3; /* F[0] = Q16_One; */ F[1] = neghalfdx; F[2] = neghalfdy; F[3] = neghalfdz; F[4] = halfdtq1; F[5] = halfdtq2; F[6] = halfdtq3; F[7] = halfdx; /* F[8] = Q16_One; */ F[9] = halfdz; F[10] = neghalfdy; F[11] = neghalfdtq0; F[12] = halfdtq3; F[13] = neghalfdtq2; F[14] = halfdy; F[15] = neghalfdz; /* F[16] = Q16_One; */ F[17] = halfdx; F[18] = neghalfdtq3; F[19] = neghalfdtq0; F[20] = halfdtq1; F[21] = halfdz; F[22] = halfdy; F[23] = neghalfdx; /* F[24] = Q16_One; */ F[25] = halfdtq2; F[26] = neghalfdtq1; F[27] = neghalfdtq0; #endif //Extended Kalman Filter: Prediction Step //state time propagation //Update Quaternion with the new gyroscope measurements //X[0] = q0 - halfdx * q1 - halfdy * q2 - halfdz * q3; //X[1] = q1 + halfdx * q0 - halfdy * q3 + halfdz * q2; //X[2] = q2 + halfdx * q3 + halfdy * q0 - halfdz * q1; //X[3] = q3 - halfdx * q2 + halfdy * q1 + halfdz * q0; //cortex-m3's instruction assembly optimization __asm{ smull __al, __ah, neghalfdx, q1; smlal __al, __ah, neghalfdy, q2; smlal __al, __ah, neghalfdz, q3; lsls __ah, __ah, orr X[0], __ah, __al, lsr adds X[0], q0, X[0]; smull __al, __ah, halfdx, q0; smlal __al, __ah, neghalfdy, q3; smlal __al, __ah, halfdz, q2; lsls __ah, __ah, orr X[1], __ah, __al, lsr adds X[1], q1, X[1]; smull __al, __ah, halfdx, q3; smlal __al, __ah, halfdy, q0; smlal __al, __ah, neghalfdz, q1; lsls __ah, __ah, orr X[2], __ah, __al, lsr adds X[2], q2, X[2]; smull __al, __ah, neghalfdx, q2; smlal __al, __ah, halfdy, q1; smlal __al, __ah, halfdz, q0; lsls __ah, __ah, orr X[3], __ah, __al, lsr adds X[3], q3, X[3]; } //covariance time propagation //P = F*P*F' + Q; FP_Matrix_Multiply(F, FP_EKF_STATE_DIM, FP_EKF_STATE_DIM, P, FP_EKF_STATE_DIM, PX); <API key>(PX, FP_EKF_STATE_DIM, FP_EKF_STATE_DIM, F, FP_EKF_STATE_DIM, P); FP_Maxtrix_Add(P, FP_EKF_STATE_DIM, FP_EKF_STATE_DIM, Q, P); //measurement update //kalman gain calculation //K = P * H' / (R + H * P * H') _2q0 = X[0] << 1; _2q1 = X[1] << 1; _2q2 = X[2] << 1; _2q3 = X[3] << 1; #if FP_EKF_STATE_DIM == 4 H[0] = _2q2; H[1] = -_2q3; H[2] = _2q0; H[3] = -_2q1; H[4] = -_2q1; H[5] = -_2q0; H[6] = -_2q3; H[7] = -_2q2; H[8] = -_2q0; H[9] = _2q1; H[10] = _2q2; H[11] = -_2q3; #else //FP_EKF_STATE_DIM == 7 H[0] = _2q2; H[1] = -_2q3; H[2] = _2q0; H[3] = -_2q1; H[8] = -_2q1; H[9] = -_2q0; H[10] = -_2q3; H[11] = -_2q2; H[14] = -_2q0; H[15] = _2q1; H[16] = _2q2; H[17] = -_2q3; #endif <API key>(P, FP_EKF_STATE_DIM, FP_EKF_STATE_DIM, H, <API key>, PHT); FP_Matrix_Multiply(H, <API key>, FP_EKF_STATE_DIM, PHT, <API key>, S); FP_Maxtrix_Add(S, <API key>, <API key>, R, S); FP_Matrix_Inverse(S, <API key>, SI); FP_Matrix_Multiply(PHT, FP_EKF_STATE_DIM, <API key>, SI, <API key>, K); //state measurement update //X = X + K * Y; //Y[0] = -2.0f * (X[1] * X[3] - X[0] * X[2]); //Y[1] = -2.0f * (X[2] * X[3] + X[0] * X[1]); //Y[2] = 1.0f - 2.0f * (X[0] * X[0] + X[3] * X[3]); Y[0] = FP_SUBS(FP_SMUL(X[0], X[2]), FP_SMUL(X[1], X[3])) << 1; Y[1] = FP_ADDS(FP_SMUL(-X[2], X[3]), FP_SMUL(-X[0], X[1])) << 1; Y[2] = FP_SUBS(Q16_One, FP_ADDS(FP_SMUL(X[0], X[0]), FP_SMUL(X[3], X[3])) << 1); //normalize accel norm = FastSqrtI(accel[0] * accel[0] + accel[1] * accel[1] + accel[2] * accel[2]); accel[0] *= norm; accel[1] *= norm; accel[2] *= norm; Y[0] = FP_SUBS(FT_Q16(accel[0]), Y[0]); Y[1] = FP_SUBS(FT_Q16(accel[1]), Y[1]); Y[2] = FP_SUBS(FT_Q16(accel[2]), Y[2]); FP_Matrix_Multiply(K, FP_EKF_STATE_DIM, <API key>, Y, 1, KY); FP_Maxtrix_Add(X, FP_EKF_STATE_DIM, 1, X, KY); //normalize quaternion //norm = FastSqrtI(X[0] * X[0] + X[1] * X[1] + X[2] * X[2] + X[3] * X[3]); //X[0] *= norm; //X[1] *= norm; //X[2] *= norm; //X[3] *= norm; //cortex-m3's instruction assembly optimization __asm{ smull __al, __ah, X[0], X[0]; smlal __al, __ah, X[1], X[1]; smlal __al, __ah, X[2], X[2]; smlal __al, __ah, X[3], X[3]; lsls __ah, __ah, orr qNorm, __ah, __al, lsr } qNorm = FP_SqrtI(qNorm, PRECISION); X[0] = FP_SMUL(X[0], qNorm); X[1] = FP_SMUL(X[1], qNorm); X[2] = FP_SMUL(X[2], qNorm); X[3] = FP_SMUL(X[3], qNorm); //covariance measurement update //P = (I - K * H) * P FP_Matrix_Multiply(K, FP_EKF_STATE_DIM, <API key>, H, FP_EKF_STATE_DIM, PX); FP_Maxtrix_Sub(I, FP_EKF_STATE_DIM, FP_EKF_STATE_DIM, PX, PX); FP_Matrix_Multiply(PX, FP_EKF_STATE_DIM, FP_EKF_STATE_DIM, P, FP_EKF_STATE_DIM, PXX); FP_Matrix_Copy(PXX, FP_EKF_STATE_DIM, FP_EKF_STATE_DIM, P); } void FP_EKF_IMUGetAngle(float* rpy) { Q16 q0q0 = FP_SMUL(X[0], X[0]); Q16 fpRPY[3]; CBn[0] = FP_SUBS(((q0q0 + FP_SMUL(X[1], X[1])) << 1), Q16_One); CBn[1] = (FP_SMUL(X[1], X[2]) + FP_SMUL(X[0], X[3])) << 1; CBn[2] = (FP_SMUL(X[1], X[3]) - FP_SMUL(X[0], X[2])) << 1; //CBn[3] = 2.0f * (X[1] * X[2] - X[0] * X[3]); //CBn[4] = 2.0f * (q0q0 + X[2] * X[2]) - 1.0f; CBn[5] = (FP_SMUL(X[2], X[3]) + FP_SMUL(X[0], X[1])) << 1; //CBn[6] = 2.0f * (X[1] * X[3] + X[0] * X[2]); //CBn[7] = 2.0f * (X[2] * X[3] - X[0] * X[1]); CBn[8] = FP_SUBS(((q0q0 + FP_SMUL(X[3], X[3])) << 1), Q16_One); //roll fpRPY[0] = FP_FastAtan2(CBn[5], CBn[8]); if(fpRPY[0] == Q16_PI){ fpRPY[0] = -Q16_PI; } //pitch if (CBn[2] >= Q16_One){ fpRPY[1] = -Q16_HALFPI; } else if (fpRPY[2] <= -Q16_One){ fpRPY[1] = Q16_HALFPI; } else{ fpRPY[1] = FP_FastAsin(-CBn[2]); } //yaw fpRPY[2] = FP_FastAtan2(CBn[1], CBn[0]); if (fpRPY[2] < 0){ fpRPY[2] = FP_ADDS(fpRPY[2], Q16_TWOPI); } if (fpRPY[2] >= Q16_TWOPI){ fpRPY[2] = 0; } rpy[0] = TO_FLOAT_DEGREE(fpRPY[0]); rpy[1] = TO_FLOAT_DEGREE(fpRPY[1]); rpy[2] = TO_FLOAT_DEGREE(fpRPY[2]); }
<?php namespace Colmenapp\PlataformaBundle\Entity; use Colmenapp\PlataformaBundle\Entity\Colmena; use Colmenapp\PlataformaBundle\Entity\Inspeccion; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\ORM\Mapping as ORM; /** * ColmenaInspeccion * * @ORM\Table(name="colmena_inspeccion") * @ORM\Entity(repositoryClass="Colmenapp\PlataformaBundle\Repository\<API key>") */ class ColmenaInspeccion { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="Colmena") * @assert\NotBlank() */ private $colmena; /** * @var \DateTime * * @ORM\Column(name="fecha", type="datetime") */ private $fecha; /** * @ORM\ManyToOne(targetEntity="Inspeccion") */ private $inspeccionApiario; /** * @var string * * @ORM\Column(name="tareaRealizada", type="text") */ private $tareaRealizada; /** * @var string * * @ORM\Column(name="observacion", type="text", nullable=true) */ private $observacion; /** * @var int * * @ORM\Column(name="estado", type="integer", nullable=true) */ private $estado; /** * @var \DateTime * * @ORM\Column(name="created", type="datetime") */ private $created; /** * @var \DateTime * * @ORM\Column(name="updated", type="datetime", nullable=true) */ private $updated; /** * @var \DateTime * * @ORM\Column(name="deleted", type="datetime", nullable=true) */ private $deleted; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set fecha * * @param \DateTime $fecha * @return ColmenaInspeccion */ public function setFecha($fecha) { $this->fecha = $fecha; return $this; } /** * Get fecha * * @return \DateTime */ public function getFecha() { return $this->fecha; } /** * Set inspeccionApiario * * @param integer $inspeccionApiario * @return ColmenaInspeccion */ public function <API key>($inspeccionApiario) { $this->inspeccionApiario = $inspeccionApiario; return $this; } /** * Get inspeccionApiario * * @return integer */ public function <API key>() { return $this->inspeccionApiario; } /** * Set tareaRealizada * * @param string $tareaRealizada * @return ColmenaInspeccion */ public function setTareaRealizada($tareaRealizada) { $this->tareaRealizada = $tareaRealizada; return $this; } /** * Get tareaRealizada * * @return string */ public function getTareaRealizada() { return $this->tareaRealizada; } /** * Set observacion * * @param string $observacion * @return ColmenaInspeccion */ public function setObservacion($observacion) { $this->observacion = $observacion; return $this; } /** * Get observacion * * @return string */ public function getObservacion() { return $this->observacion; } /** * Set estado * * @param integer $estado * @return ColmenaInspeccion */ public function setEstado($estado) { $this->estado = $estado; return $this; } /** * Get estado * * @return integer */ public function getEstado() { return $this->estado; } /** * Set created * * @param \DateTime $created * @return ColmenaInspeccion */ public function setCreated($created) { $this->created = $created; return $this; } /** * Get created * * @return \DateTime */ public function getCreated() { return $this->created; } /** * Set updated * * @param \DateTime $updated * @return ColmenaInspeccion */ public function setUpdated($updated) { $this->updated = $updated; return $this; } /** * Get updated * * @return \DateTime */ public function getUpdated() { return $this->updated; } /** * Set deleted * * @param \DateTime $deleted * @return ColmenaInspeccion */ public function setDeleted($deleted) { $this->deleted = $deleted; return $this; } /** * Get deleted * * @return \DateTime */ public function getDeleted() { return $this->deleted; } /** * @return mixed */ public function getColmena() { return $this->colmena; } /** * @param mixed $colmena */ public function setColmena($colmena) { $this->colmena = $colmena; } }
<?php // ADS-B RECEIVER PORTAL // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // copies or substantial portions of the Software. // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // 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. // require_once($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."classes".DIRECTORY_SEPARATOR."common.class.php"); $common = new common(); // The most current stable release. $thisVersion = "2.7.2"; // Begin the upgrade process if this release is newer than what is installed. if ($common->getSetting("version") == $thisVersion) { header ("Location: /"); } $success = TRUE; // UPGRADE TO V2.0.1 if ($common->getSetting("version") == "2.0.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.0.1.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.0.1"; } // UPGRADE TO V2.0.2 if ($common->getSetting("version") == "2.0.1" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.0.2.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.0.2"; } // UPGRADE RO V2.0.3 if ($common->getSetting("version") == "2.0.2" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.0.3.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.0.3"; } // UPGRADE TO V2.1.0 if ($common->getSetting("version") == "2.0.3" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.1.0.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.1.0"; } // UPGRADE TO V2.2.0 if ($common->getSetting("version") == "2.1.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.2.0.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.2.0"; } // UPGRADE TO V2.3.0 if ($common->getSetting("version") == "2.2.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.3.0.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.3.0"; } // UPGRADE TO V2.4.0 if ($common->getSetting("version") == "2.3.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.4.0.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.4.0"; } // UPGRADE TO V2.5.0 if ($common->getSetting("version") == "2.4.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.5.0.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.5.0"; } // UPGRADE TO V2.6.0 if ($common->getSetting("version") == "2.5.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.6.0.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.6.0"; } // UPGRADE TO V2.6.1 if ($common->getSetting("version") == "2.6.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.6.1.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.6.1"; } // UPGRADE TO V2.6.2 if ($common->getSetting("version") == "2.6.1" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.6.2.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.6.2"; } // UPGRADE TO V2.6.3 if ($common->getSetting("version") == "2.6.2" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.6.3.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.6.3"; } // UPGRADE TO V2.7.0 if ($common->getSetting("version") == "2.6.3" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.7.0.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.7.0"; } // UPGRADE TO V2.7.1 if ($common->getSetting("version") == "2.7.0" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.7.1.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.7.1"; } // UPGRADE TO V2.7.2 if ($common->getSetting("version") == "2.7.1" && $success) { $json = file_get_contents("http://localhost/install/upgrade-v2.7.2.php"); $results = json_decode($json, TRUE); $success = $results['success']; $message = $results['message']; $version = "2.7.2"; } require_once($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."admin".DIRECTORY_SEPARATOR."includes".DIRECTORY_SEPARATOR."header.inc.php"); // Display the instalation wizard. if ($success) { ?> <h1>ADS-B Receiver Portal Updated</h1> <p>Your portal has been upgraded to v<?php echo $version; ?>.</p> <?php } else { ?> <h1>Error Encountered Upgrading Your ADS-B Receiver Portal</h1> <p>There was an error encountered when upgrading your portal to v<?php echo $version; ?>.</p> <?php echo $message; ?> <?php } require_once($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."admin".DIRECTORY_SEPARATOR."includes".DIRECTORY_SEPARATOR."footer.inc.php"); ?>
(() => { 'use strict'; var dom; var types; var PropertyHelper; var ArrayHelper; define([ './helpers/dom-helper', './helpers/type-helper', './helpers/property-helper', './helpers/array-helper' ], main); function main( $dom, $types, $PropertyHelper, $ArrayHelper ) { dom = $dom; types = $types; PropertyHelper = $PropertyHelper; ArrayHelper = $ArrayHelper; return DessertElement; } class DessertElement { constructor(element) { PropertyHelper.<API key>(this, [{ name: 'element', value: DessertElement.factory(element) }]); } static factory(html) { if (types.isString(html)) { return new DessertElement(dom.createDocFrag(html)); } return html; } static find(selector, context = document) { return new DessertElement(context.querySelector(selector)); } static findAll(selector, context = document) { let matches = context.querySelectorAll(selector); let arrayLike = makeArray(matches); return arrayLike.map(toDessertElement); } attr(name, value = '') { if (name && value !== '') { //set this.element.setAttribute(name, value); } else { return this.element.getAttribute(name); } } replaceWith(element) { if (element) { this.element.parentNode.replaceChild(element, this.element); } } clone() { return this.element.cloneNode(true); } empty() { dom.emptyElement(this.element); } data(name, value) { var elem = this.element; if (name && value !== undefined) { elem.dataset[name] = value; return this; } return elem.dataset[name]; } find(selector) { return new DessertElement(this.element.querySelector(selector)); } findAll(selector) { let matches = this.element.querySelectorAll(selector); let arrayLike = makeArray(matches); return arrayLike.map(toDessertElement); } append(child) { this.element.appendChild(child); } on(event, handler) { this.element.addEventListener(event, handler); } value(value) { if (value) { this.element.value = value; return this; } return this.element.value; } } function makeArray(nodeList) { return ArrayHelper.castArray(nodeList); } function toDessertElement(elem) { return new DessertElement(elem); } })();
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Tue Oct 01 11:25:16 BST 2013 --> <title>StatusBar</title> <meta name="date" content="2013-10-01"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="StatusBar"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>JPedal 5.06b01 </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/jpedal/io/ObjectStore.html" title="class in org.jpedal.io"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/jpedal/io/StatusBar.html" target="_top">Frames</a></li> <li><a href="StatusBar.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <div class="subTitle">org.jpedal.io</div> <h2 title="Class StatusBar" class="title">Class StatusBar</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.jpedal.io.StatusBar</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">StatusBar</span> extends java.lang.Object</pre> <div class="block">encapsulates a status bar to display progess of a page decode and messages for a GUI client and methods to access it - See org.examples.jpedal.viewer.Viewer for example of usage</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field_summary"> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>float</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#percentageDone">percentageDone</a></strong></code> <div class="block">amount done on decode</div> </td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#StatusBar()">StatusBar</a></strong>()</code> <div class="block">initialises statusbar using default colors</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#StatusBar(java.awt.Color)">StatusBar</a></strong>(java.awt.Color&nbsp;newColor)</code> <div class="block">initialises statusbar using specified color</div> </td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_summary"> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.awt.Component</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#getStatusObject()">getStatusObject</a></strong>()</code> <div class="block">return handle on status bar so it can be displayed</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#initialiseStatus(java.lang.String)">initialiseStatus</a></strong>(java.lang.String&nbsp;current)</code> <div class="block">initiate status bar</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#isDone()">isDone</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#isEnabled()">isEnabled</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#isVisible()">isVisible</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#resetStatus(java.lang.String)">resetStatus</a></strong>(java.lang.String&nbsp;current)</code> <div class="block">reset status bar</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#setClientDisplay()">setClientDisplay</a></strong>()</code> <div class="block">set client flag to display</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#setEnabled(boolean)">setEnabled</a></strong>(boolean&nbsp;enable)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#setProgress(int)">setProgress</a></strong>(int&nbsp;size)</code> <div class="block">set progress value (called internally as page decoded)</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#setProgress(java.lang.String, int)">setProgress</a></strong>(java.lang.String&nbsp;message, int&nbsp;size)</code> <div class="block">set progress value (called internally as page decoded)</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#setVisible(boolean)">setVisible</a></strong>(boolean&nbsp;visible)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../org/jpedal/io/StatusBar.html#updateStatus(java.lang.String, int)">updateStatus</a></strong>(java.lang.String&nbsp;progress_bar, int&nbsp;debug_level_to_use)</code> <div class="block">update status if client being used also writes to log (called internally as file decoded)</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="<API key>.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field_detail"> </a> <h3>Field Detail</h3> <a name="percentageDone"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>percentageDone</h4> <pre>public&nbsp;float percentageDone</pre> <div class="block">amount done on decode</div> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> </a> <h3>Constructor Detail</h3> <a name="StatusBar()"> </a> <ul class="blockList"> <li class="blockList"> <h4>StatusBar</h4> <pre>public&nbsp;StatusBar()</pre> <div class="block">initialises statusbar using default colors</div> </li> </ul> <a name="StatusBar(java.awt.Color)"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>StatusBar</h4> <pre>public&nbsp;StatusBar(java.awt.Color&nbsp;newColor)</pre> <div class="block">initialises statusbar using specified color</div> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_detail"> </a> <h3>Method Detail</h3> <a name="initialiseStatus(java.lang.String)"> </a> <ul class="blockList"> <li class="blockList"> <h4>initialiseStatus</h4> <pre>public final&nbsp;void&nbsp;initialiseStatus(java.lang.String&nbsp;current)</pre> <div class="block">initiate status bar</div> </li> </ul> <a name="updateStatus(java.lang.String, int)"> </a> <ul class="blockList"> <li class="blockList"> <h4>updateStatus</h4> <pre>public final&nbsp;void&nbsp;updateStatus(java.lang.String&nbsp;progress_bar, int&nbsp;debug_level_to_use)</pre> <div class="block">update status if client being used also writes to log (called internally as file decoded)</div> </li> </ul> <a name="getStatusObject()"> </a> <ul class="blockList"> <li class="blockList"> <h4>getStatusObject</h4> <pre>public final&nbsp;java.awt.Component&nbsp;getStatusObject()</pre> <div class="block">return handle on status bar so it can be displayed</div> </li> </ul> <a name="setProgress(int)"> </a> <ul class="blockList"> <li class="blockList"> <h4>setProgress</h4> <pre>public final&nbsp;void&nbsp;setProgress(int&nbsp;size)</pre> <div class="block">set progress value (called internally as page decoded)</div> </li> </ul> <a name="setProgress(java.lang.String, int)"> </a> <ul class="blockList"> <li class="blockList"> <h4>setProgress</h4> <pre>public final&nbsp;void&nbsp;setProgress(java.lang.String&nbsp;message, int&nbsp;size)</pre> <div class="block">set progress value (called internally as page decoded)</div> </li> </ul> <a name="resetStatus(java.lang.String)"> </a> <ul class="blockList"> <li class="blockList"> <h4>resetStatus</h4> <pre>public final&nbsp;void&nbsp;resetStatus(java.lang.String&nbsp;current)</pre> <div class="block">reset status bar</div> </li> </ul> <a name="setClientDisplay()"> </a> <ul class="blockList"> <li class="blockList"> <h4>setClientDisplay</h4> <pre>public final&nbsp;void&nbsp;setClientDisplay()</pre> <div class="block">set client flag to display</div> </li> </ul> <a name="setVisible(boolean)"> </a> <ul class="blockList"> <li class="blockList"> <h4>setVisible</h4> <pre>public&nbsp;void&nbsp;setVisible(boolean&nbsp;visible)</pre> </li> </ul> <a name="setEnabled(boolean)"> </a> <ul class="blockList"> <li class="blockList"> <h4>setEnabled</h4> <pre>public&nbsp;void&nbsp;setEnabled(boolean&nbsp;enable)</pre> </li> </ul> <a name="isVisible()"> </a> <ul class="blockList"> <li class="blockList"> <h4>isVisible</h4> <pre>public&nbsp;boolean&nbsp;isVisible()</pre> </li> </ul> <a name="isEnabled()"> </a> <ul class="blockList"> <li class="blockList"> <h4>isEnabled</h4> <pre>public&nbsp;boolean&nbsp;isEnabled()</pre> </li> </ul> <a name="isDone()"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>isDone</h4> <pre>public&nbsp;boolean&nbsp;isDone()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>JPedal 5.06b01 ACCCCA</em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/jpedal/io/ObjectStore.html" title="class in org.jpedal.io"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/jpedal/io/StatusBar.html" target="_top">Frames</a></li> <li><a href="StatusBar.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small>JPedal 5.06b01 ACCCCA</small></p> </body> </html>
#pragma once #include <QString> #include <vector> class PollTypeItem { public: QString m_name; QString m_description; int m_min_duration_days; }; class PollTypes : public std::vector<PollTypeItem> { public: enum PollType { PollTypeUnknown, PollTypeProject, PollTypeDevelopment, PollTypeGovernance, PollTypeMarketing, PollTypeOutreach, PollTypeCommunity, PollTypeSurvey, }; PollTypes(); };
package org.shipkit.internal.util; import java.util.*; /** * Basic multi-map that contains multiple values per key */ public class MultiMap<K, V> { private final Map<K, Collection<V>> data = new LinkedHashMap<>(); /** * If the key does not exist, null is returned */ public Collection<V> get(K key) { return data.get(key); } public void put(K key, V value) { Collection<V> elements = get(key); if (elements == null) { elements = new LinkedHashSet<>(); } elements.add(value); data.put(key, elements); } public Set<K> keySet() { return data.keySet(); } public int size() { return data.size(); } }
// NSObject+Runtime.h // RuntimeDictToModel #import <Foundation/Foundation.h> @interface NSObject (Runtime) + (instancetype)sr_objWithDict:(NSDictionary *)dict; + (NSArray *)sr_objProperties; @end