code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); int N; cin >> N; int sum = 0; int arr[N]; for (int i = 0; i < N; i++) { cin >> arr[i]; sum += arr[i]; } int average = ((double) sum / N - (int) sum / N) >= 0.5 ? sum / N + 1 : sum / N; sum = 0; for (int i = 0; i < N; i++) sum += pow(arr[i] - average, 2); cout << sum; return 0; }
billchow98/billchow98-projects
OnlineJudgeSolutions/AtCoder/abc043c.cpp
C++
agpl-3.0
439
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../img/clover.ico" /> <link rel="stylesheet" href="../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../style.css'); @import url('../../../tree.css'); </style> <script src="../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../clover-tree.js" type="text/javascript"></script> <script src="../../../clover.js" type="text/javascript"></script> <script src="../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../cloud.js" type="text/javascript"></script> <title>rapidminer-studio-core 转换结果 </title> </head> <body onload="onLoad('rapidminer-studio-core 转换结果 : com.rapidminer.repository.RepositoryTools.java')"> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://www.atlassian.com/clover" title="Open Atlassian Clover home page"><span class="aui-header-logo-device">Clover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online Clover documentation" target="_blank" href="https://confluence.atlassian.com/display/CLOVER/Clover+Documentation+Home"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </div> <div class="aui-page-header-main" > <h1> rapidminer-studio-core 转换结果 </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../" data-package-name="com.rapidminer.repository"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../dashboard.html">Project Clover database 星期二 九月 5 2017 16:40:29 CST</a></li> <li><a href="pkg-summary.html"> Package com.rapidminer.repository</a></li> </ol> <h1 class="aui-h2-clover"> File RepositoryTools.java </h1> <div class="aui-message aui-message-warning"> <p class="title"> <strong>Evaluation License</strong> </p> <p> This report was generated with an evaluation server license. <a href="http://www.atlassian.com/software/clover">Purchase Clover</a> or <a href="http://confluence.atlassian.com/x/JAgQCQ">configure your license.</a> </p> </div> <div class="aui-tabs horizontal-tabs" id="tabs-file"> <div class="tabs-pane aui-tabs-pane-100-pcnt active-pane" id="tabs-file-source"> <div>&#160;</div> <div style="display: table; width: 100%"> <div style="display: table-cell; "> <div class="dashboard-widget"> <header class="dashboard-widget-header"> <h3>Code metrics</h3> </header> <div class="dashboard-widget-content"> <div id="td-header-stats" class="aui-item" style="display: "> <div style="display: table"> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of branches in this file">Branches:</label></div> <div class="stats-box-value">0</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of statements in this file">Statements:</label></div> <div class="stats-box-value">0</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of methods in this file">Methods:</label></div> <div class="stats-box-value">0</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of classes in this file">Classes:</label></div> <div class="stats-box-value">1</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of lines of code in this file">LOC:</label></div> <div class="stats-box-value">179</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of non-comment lines of code in this file">NCLOC:</label></div> <div class="stats-box-value">80</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Cyclomatic complexity is the number of paths in this file">Total complexity:</label></div> <div class="stats-box-value">0</div> </div> <div class="stats-box"> <div class="stats-box-label"> <label title="Complexity density is the complexity divided by the number of statements in this file">Complexity density:</label> </div> <div class="stats-box-value">-</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Number of statements per method.">Statements/Method:</label></div> <div class="stats-box-value">-</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Number of methods per class.">Methods/Class:</label></div> <div class="stats-box-value">0</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Complexity divided by the number of methods in this file">Average method complexity:</label></div> <div class="stats-box-value">-</div> </div> </div> <div class="subtle"> <small><strong>100%</strong> of code in this file is excluded from these metrics.</small> <label class="aui-button aui-button-subtle" onclick="toggleStats('td-header-stats', 'td-filtered-header-stats');" title="Include or exclude filtered elements from these statistics.">Remove Filter</label> </div> </div> <div id="td-filtered-header-stats" class="aui-item" style="display: none"> <div style="display: table"> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of branches in this file">Branches:</label></div> <div class="stats-box-value">28</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of statements in this file">Statements:</label></div> <div class="stats-box-value">37</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of methods in this file">Methods:</label></div> <div class="stats-box-value">5</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of classes in this file">Classes:</label></div> <div class="stats-box-value">1</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of lines of code in this file">LOC:</label></div> <div class="stats-box-value">179</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Total number of non-comment lines of code in this file">NCLOC:</label></div> <div class="stats-box-value">80</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Cyclomatic complexity is the number of paths in this file">Total complexity:</label></div> <div class="stats-box-value">35</div> </div> <div class="stats-box"> <div class="stats-box-label"> <label title="Complexity density is the complexity divided by the number of statements in this file">Complexity density:</label> </div> <div class="stats-box-value">0.95</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Number of statements per method.">Statements/Method:</label></div> <div class="stats-box-value">7.4</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Number of methods per class.">Methods/Class:</label></div> <div class="stats-box-value">5</div> </div> <div class="stats-box"> <div class="stats-box-label"><label title="Complexity divided by the number of methods in this file">Average method complexity:</label></div> <div class="stats-box-value">7</div> </div> </div> <div class="subtle"> <small>These metrics include <strong class='bold'>100%</strong> of code marked as filtered.</small> <label class="aui-button aui-button-subtle" onclick="toggleStats('td-filtered-header-stats', 'td-header-stats');" title="Include or exclude filtered elements from these statistics.">Apply Filter</label> </div> </div> </div> </div> </div> </div> <h2>Classes</h2> <table class="aui aui-table-sortable"> <thead> <tr> <th>Class</th> <th>Line #</th> <th class=""> <label title="The total number of statements.">Total Statements</label> </th> <th class=""> <label title="Cyclomatic complexity is a measure of the number of paths in your code.">Complexity</label> </th> <th class=""> <label title="The amount of code that was hit at least once during testing.">TOTAL Coverage</label> </th> <th>Actions</th> </tr> </thead> <tbody> <tr> <td id="RepositoryTools"> <span><a href="#36" title="RepositoryTools" onclick="closeDialogAndScrollTo('dialog-RepositoryTools', '36');">RepositoryTools</a></span> </td> <td>36<a name="sl-36"></a></td> <td class="">0</td> <td class="">0</td> <td class=""><div style="display: table; width: 100%"> <div class="barGraphValue"><span class="sortValue">-1.0</span> - </div><div style="display: table-cell"> <div title="Empty" class="barEmpty" style="min-width:200px;"></div></div></div></td> <td><button data-dialog-id="dialog-RepositoryTools" class="aui-button aui-button-link dialog-show-button">Show methods</button></td> </tr> </tbody> </table> <section role="dialog" id="dialog-RepositoryTools" class="aui-layer aui-dialog2 aui-dialog2-xlarge" aria-hidden="true"> <header class="aui-dialog2-header"> <h1 class="aui-dialog2-header-main">Class RepositoryTools</h1> <div class="aui-dialog2-header-secondary"> <input id="dialog-RepositoryTools-method-filter" class="test-filter text" type="text" name="method-filter" placeholder="Type to filter methods..." autocomplete="off" onkeyup="filterMethods('dialog-RepositoryTools-methods-body', 'dialog-RepositoryTools-method-filter');"/> </div> </header> <div class="aui-dialog2-content"> <table class="aui aui-table-sortable"> <thead> <tr> <th id="RepositoryTools"> Class<br/> <span><a href="#36" title="RepositoryTools" onclick="closeDialogAndScrollTo('dialog-RepositoryTools', '36');">RepositoryTools</a></span> </th> <th>Line #<br/>36<a name="sl-36"></a></th> <th class=""><label title="The total number of statements.">Total Statements</label><br/>0</th> <th class=""><label title="Cyclomatic complexity is a measure of the number of paths in your code.">Complexity</label><br/>0</th> <th class=""><label title="The amount of code that was hit at least once during testing.">TOTAL Coverage</label><br/><div style="display: table; width: 100%"> <div class="barGraphValue"><span class="sortValue">-1.0</span> - </div><div style="display: table-cell"> <div title="Empty" class="barEmpty" style="min-width:200px;"></div></div></div></th> </tr> </thead> <tbody id="dialog-RepositoryTools-methods-body"> <tr id="RepositoryTools-1"> <td id="summary-44-2"> <span class="sortValue">RepositoryTools()</span> &#160;&#160;<a href="?line=29#44" title="RepositoryTools()" name="sl-44" onclick="closeDialogAndScrollTo('dialog-RepositoryTools', '44');">RepositoryTools()</a> </td> <td align="right"><span class="sortValue">44</span>44</td> <td class="" align="right"><span class="sortValue">0.0</span>0</td> <td class="" align="right"><span class="sortValue">1.0</span>1</td> <td class="" align="right"><span class="sortValue">-1.0</span><div style="display: table; width: 100%"> <div class="barGraphValue"><span class="sortValue">-1.0</span> - </div><div style="display: table-cell"> <div title="Empty" class="barEmpty" style="min-width:200px;"></div></div></div></td> </tr> <tr id="RepositoryTools-2"> <td id="summary-64-3"> <span class="sortValue">compare(Entry,Entry)&#160;:&#160;int</span> &#160;&#160;<a href="?line=29#64" title="compare(Entry,Entry)&#160;:&#160;int" name="sl-64" onclick="closeDialogAndScrollTo('dialog-RepositoryTools', '64');">compare(Entry,Entry)&#160;:&#160;int</a> </td> <td align="right"><span class="sortValue">64</span>64</td> <td class="" align="right"><span class="sortValue">0.0</span>0</td> <td class="" align="right"><span class="sortValue">1.0</span>1</td> <td class="" align="right"><span class="sortValue">-1.0</span><div style="display: table; width: 100%"> <div class="barGraphValue"><span class="sortValue">-1.0</span> - </div><div style="display: table-cell"> <div title="Empty" class="barEmpty" style="min-width:200px;"></div></div></div></td> </tr> <tr id="RepositoryTools-3"> <td id="summary-92-3"> <span class="sortValue">compare(Entry,Entry)&#160;:&#160;int</span> &#160;&#160;<a href="?line=29#92" title="compare(Entry,Entry)&#160;:&#160;int" name="sl-92" onclick="closeDialogAndScrollTo('dialog-RepositoryTools', '92');">compare(Entry,Entry)&#160;:&#160;int</a> </td> <td align="right"><span class="sortValue">92</span>92</td> <td class="" align="right"><span class="sortValue">0.0</span>0</td> <td class="" align="right"><span class="sortValue">1.0</span>1</td> <td class="" align="right"><span class="sortValue">-1.0</span><div style="display: table; width: 100%"> <div class="barGraphValue"><span class="sortValue">-1.0</span> - </div><div style="display: table-cell"> <div title="Empty" class="barEmpty" style="min-width:200px;"></div></div></div></td> </tr> <tr id="RepositoryTools-4"> <td id="summary-121-3"> <span class="sortValue">compare(Entry,Entry)&#160;:&#160;int</span> &#160;&#160;<a href="?line=29#121" title="compare(Entry,Entry)&#160;:&#160;int" name="sl-121" onclick="closeDialogAndScrollTo('dialog-RepositoryTools', '121');">compare(Entry,Entry)&#160;:&#160;int</a> </td> <td align="right"><span class="sortValue">121</span>121</td> <td class="" align="right"><span class="sortValue">0.0</span>0</td> <td class="" align="right"><span class="sortValue">1.0</span>1</td> <td class="" align="right"><span class="sortValue">-1.0</span><div style="display: table; width: 100%"> <div class="barGraphValue"><span class="sortValue">-1.0</span> - </div><div style="display: table-cell"> <div title="Empty" class="barEmpty" style="min-width:200px;"></div></div></div></td> </tr> <tr id="RepositoryTools-5"> <td id="summary-160-3"> <span class="sortValue">compare(Repository,Repository)&#160;:&#160;int</span> &#160;&#160;<a href="?line=29#160" title="compare(Repository,Repository)&#160;:&#160;int" name="sl-160" onclick="closeDialogAndScrollTo('dialog-RepositoryTools', '160');">compare(Repository,Repository)&#160;:&#160;int</a> </td> <td align="right"><span class="sortValue">160</span>160</td> <td class="" align="right"><span class="sortValue">0.0</span>0</td> <td class="" align="right"><span class="sortValue">1.0</span>1</td> <td class="" align="right"><span class="sortValue">-1.0</span><div style="display: table; width: 100%"> <div class="barGraphValue"><span class="sortValue">-1.0</span> - </div><div style="display: table-cell"> <div title="Empty" class="barEmpty" style="min-width:200px;"></div></div></div></td> </tr> </tbody> </table> <div>&#160;</div> </div> <footer class="aui-dialog2-footer"> <div class="aui-dialog2-footer-actions"> <button class="aui-button aui-button-primary dialog-close-button" data-dialog-id="dialog-RepositoryTools">Close</button> </div> <div class="aui-dialog2-footer-hint">Click on a class or a method name to jump to source.</div> </footer> </section> <div>&#160;</div> <h2>Contributing tests</h2> <div class="aui-message"> <p>No tests hitting this source file were found.</p> </div> <h2>Source view</h2> <div style="display: table; width: 100%;"> <div style="display: table-cell"> <button class="aui-button aui-button-link" title="Toggles all methods in the source to be either expanded or collapsed." onclick="toggleAllInlineMethods(this); return false;" id="method-expander"> Collapse all methods </button> </div> <div style="display: table-cell"> <div style="text-align: right; margin-bottom: 10px"> <button class="aui-button aui-button-subtle" id="popupHelp"> <span class="aui-icon aui-icon-small aui-iconfont-help"></span>&#160;Show legend </button> <script> AJS.InlineDialog(AJS.$("#popupHelp"), "helpDialog", function(content, trigger, showPopup) { content.css({"padding":"20px"}).html(SRC_FILE_LEGEND_TEXT); showPopup(); return false; }, { width: 700, hideDelay: 60000 } ); </script> </div> </div> </div> <table cellspacing="0" cellpadding="0" class="srcView" width="100%"> <tbody> <tr id="l1"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=1#src-1">1</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-1" class="srcLine"><span class="comment">/**</span></span></td> </tr> <tr id="l2"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=2#src-2">2</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-2" class="srcLine"><span class="comment"> * Copyright (C) 2001-2017 by RapidMiner and the contributors</span></span></td> </tr> <tr id="l3"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=3#src-3">3</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-3" class="srcLine"><span class="comment"> * </span></span></td> </tr> <tr id="l4"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=4#src-4">4</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-4" class="srcLine"><span class="comment"> * Complete list of developers available at our web site:</span></span></td> </tr> <tr id="l5"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=5#src-5">5</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-5" class="srcLine"><span class="comment"> * </span></span></td> </tr> <tr id="l6"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=6#src-6">6</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-6" class="srcLine"><span class="comment"> * http://rapidminer.com</span></span></td> </tr> <tr id="l7"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=7#src-7">7</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-7" class="srcLine"><span class="comment"> * </span></span></td> </tr> <tr id="l8"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=8#src-8">8</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-8" class="srcLine"><span class="comment"> * This program is free software: you can redistribute it and/or modify it under the terms of the</span></span></td> </tr> <tr id="l9"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=9#src-9">9</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-9" class="srcLine"><span class="comment"> * GNU Affero General Public License as published by the Free Software Foundation, either version 3</span></span></td> </tr> <tr id="l10"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=10#src-10">10</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-10" class="srcLine"><span class="comment"> * of the License, or (at your option) any later version.</span></span></td> </tr> <tr id="l11"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=11#src-11">11</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-11" class="srcLine"><span class="comment"> * </span></span></td> </tr> <tr id="l12"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=12#src-12">12</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-12" class="srcLine"><span class="comment"> * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without</span></span></td> </tr> <tr id="l13"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=13#src-13">13</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-13" class="srcLine"><span class="comment"> * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU</span></span></td> </tr> <tr id="l14"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=14#src-14">14</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-14" class="srcLine"><span class="comment"> * Affero General Public License for more details.</span></span></td> </tr> <tr id="l15"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=15#src-15">15</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-15" class="srcLine"><span class="comment"> * </span></span></td> </tr> <tr id="l16"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=16#src-16">16</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-16" class="srcLine"><span class="comment"> * You should have received a copy of the GNU Affero General Public License along with this program.</span></span></td> </tr> <tr id="l17"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=17#src-17">17</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-17" class="srcLine"><span class="comment"> * If not, see http://www.gnu.org/licenses/.</span></span></td> </tr> <tr id="l18"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=18#src-18">18</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-18" class="srcLine"><span class="comment">*/</span></span></td> </tr> <tr id="l19"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=19#src-19">19</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-19" class="srcLine"><span class="keyword">package</span> com.<a href="../../rapidminer/pkg-summary.html">rapidminer</a>.<a href="../repository/pkg-summary.html">repository</a>;</span></td> </tr> <tr id="l20"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=20#src-20">20</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-20" class="srcLine"></span></td> </tr> <tr id="l21"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=21#src-21">21</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-21" class="srcLine"><span class="keyword">import</span> java.util.Comparator;</span></td> </tr> <tr id="l22"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=22#src-22">22</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-22" class="srcLine"></span></td> </tr> <tr id="l23"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=23#src-23">23</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-23" class="srcLine"><span class="keyword">import</span> com.<a href="../../rapidminer/pkg-summary.html">rapidminer</a>.external.alphanum.AlphanumComparator;</span></td> </tr> <tr id="l24"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=24#src-24">24</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-24" class="srcLine"><span class="keyword">import</span> com.<a href="../../rapidminer/pkg-summary.html">rapidminer</a>.external.alphanum.AlphanumComparator.AlphanumCaseSensitivity;</span></td> </tr> <tr id="l25"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=25#src-25">25</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-25" class="srcLine"><span class="keyword">import</span> com.<a href="../../rapidminer/pkg-summary.html">rapidminer</a>.<a href="../repository/pkg-summary.html">repository</a>.<a href="../../../com/rapidminer/repository/RepositoryManager.html#RepositoryManager">RepositoryManager</a>.<a href="../../../com/rapidminer/repository/RepositoryManager.html#RepositoryManager.RepositoryType">RepositoryType</a>;</span></td> </tr> <tr id="l26"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=26#src-26">26</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-26" class="srcLine"></span></td> </tr> <tr id="l27"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=27#src-27">27</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-27" class="srcLine"></span></td> </tr> <tr id="l28"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=28#src-28">28</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-28" class="srcLine"><span class="comment">/**</span></span></td> </tr> <tr id="l29"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=29#src-29">29</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-29" class="srcLine"><span class="comment"> * This class contains utility methods to compare {</span><span class="javadoc">@link</span><span class="comment"> Repository}s, {</span><span class="javadoc">@link</span><span class="comment"> Entry}s and</span></span></td> </tr> <tr id="l30"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=30#src-30">30</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-30" class="srcLine"><span class="comment"> * {</span><span class="javadoc">@link</span><span class="comment"> Folder}s.</span></span></td> </tr> <tr id="l31"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=31#src-31">31</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-31" class="srcLine"><span class="comment"> *</span></span></td> </tr> <tr id="l32"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=32#src-32">32</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-32" class="srcLine"><span class="comment"> * </span><span class="javadoc">@author</span><span class="comment"> Denis Schernov, Marcel Seifert</span></span></td> </tr> <tr id="l33"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=33#src-33">33</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-33" class="srcLine"><span class="comment"> *</span></span></td> </tr> <tr id="l34"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=34#src-34">34</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-34" class="srcLine"><span class="comment"> * </span><span class="javadoc">@since</span><span class="comment"> 7.3</span></span></td> </tr> <tr id="l35"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=35#src-35">35</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-35" class="srcLine"><span class="comment"> */</span></span></td> </tr> <tr class="inlineStatsRow" align="right" valign="middle"> <td class="coverageCount"><a name="36" class="nolink">&#160;</a></td> <td class="coverageCount aui-icon aui-icon-small aui-iconfont-arrows-right" id='inlineStatsToggle-36' onclick="toggleInlineStats(this, 'inlinestats-36');"/> <td align="center" valign="middle"> <table id="inlinestats-36" style="display:none;" class="inlineStats" width="100%" cellspacing="1px" cellpadding="1px"> <tr onclick="toggleInlineStats(document.getElementById('inlineStatsToggle-36'), 'inlinestats-36');return true;"> <td><div> <div title="Empty" class="barEmpty" style="min-width:40px;"></div> </div></td><td> - </td> <td class="inlineStat">Uncovered Elements: 0 (0)</td> <td class="inlineStat">Complexity: 0</td> <td class="inlineStat">Complexity Density: -</td> </tr> </table> </td> </tr> <tr id="l36"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=36#src-36">36</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" id="id-36"><span class="spacer"></span><span id="src-36" class="srcLine"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <a href="../../../com/rapidminer/repository/RepositoryTools.html#RepositoryTools">RepositoryTools</a> {</span></td> </tr> <tr id="l37"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=37#src-37">37</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-37" class="srcLine"></span></td> </tr> <tr id="l38"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=38#src-38">38</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-38" class="srcLine"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> AlphanumComparator ALPHANUMERIC_COMPARATOR = <span class="keyword">new</span> AlphanumComparator(</span></td> </tr> <tr id="l39"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=39#src-39">39</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-39" class="srcLine"> AlphanumCaseSensitivity.INSENSITIVE);</span></td> </tr> <tr id="l40"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=40#src-40">40</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-40" class="srcLine"></span></td> </tr> <tr id="l41"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=41#src-41">41</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-41" class="srcLine"> <span class="comment">/**</span></span></td> </tr> <tr id="l42"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=42#src-42">42</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-42" class="srcLine"><span class="comment"> * Private constructor which throws if called.</span></span></td> </tr> <tr id="l43"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=43#src-43">43</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-43" class="srcLine"><span class="comment"> */</span></span></td> </tr> <tr class="inlineStatsRow" align="right" valign="middle"> <td class="coverageCount"><a name="44" class="nolink">&#160;</a></td> <td class="coverageCount aui-icon aui-icon-small aui-iconfont-arrows-right" id='inlineStatsToggle-44' onclick="toggleInlineStats(this, 'inlinestats-44');"/> <td align="center" valign="middle"> <table id="inlinestats-44" style="display:none;" class="inlineStats" width="100%" cellspacing="1px" cellpadding="1px"> <tr onclick="toggleInlineStats(document.getElementById('inlineStatsToggle-44'), 'inlinestats-44');return true;"> <td><div> <div title="Empty" class="barEmpty" style="min-width:40px;"></div> </div></td><td> - </td> <td class="inlineStat">Uncovered Elements: 0 (0)</td> <td class="inlineStat">Complexity: 1</td> <td class="inlineStat">Complexity Density: -</td> </tr> </table> </td> </tr> <tr id="l44"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=44#src-44">44</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" methodStart srcCell" id="id-44"><img title="Method Statistics" onclick="toggleSrcRowVis(this, 44,46);" id="img-44" src="../../../img/collapse.gif" alt="toggle" class="icon"/><span id="src-44" class="srcLineFiltered"><span class="nolink" title="Filtered by: constructor,&#160;private"> <span class="keyword">private</span> <a href="../../../com/rapidminer/repository/RepositoryTools.html#RepositoryTools">RepositoryTools</a>() {</span><span class="foldControl" onclick="toggleSrcRowVis(document.getElementById('img-44'), 44,46);" id="e44" style="display:none;border:none;">...</span></span></td> </tr> <tr id="l45"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=45#src-45">45</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-45" class="srcLineFiltered"><span class="nolink" title="Filtered by: constructor,&#160;private"> <span class="keyword">throw</span> <span class="keyword">new</span> AssertionError(<span class="string">&quot;Utility class must not be instatiated!&quot;</span>);</span></span></td> </tr> <tr id="l46"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=46#src-46">46</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-46" class="srcLine"> }</span></td> </tr> <tr id="l47"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=47#src-47">47</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-47" class="srcLine"></span></td> </tr> <tr id="l48"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=48#src-48">48</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-48" class="srcLine"> <span class="comment">/**</span></span></td> </tr> <tr id="l49"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=49#src-49">49</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-49" class="srcLine"><span class="comment"> * Compares an {</span><span class="javadoc">@link</span><span class="comment"> Entry} or {</span><span class="javadoc">@link</span><span class="comment"> Folder} to another by comparing their names as</span></span></td> </tr> <tr id="l50"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=50#src-50">50</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-50" class="srcLine"><span class="comment"> * {</span><span class="javadoc">@link</span><span class="comment"> String} using simple java comparison.</span></span></td> </tr> <tr id="l51"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=51#src-51">51</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-51" class="srcLine"><span class="comment"> *</span></span></td> </tr> <tr id="l52"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=52#src-52">52</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-52" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> entry1</span></span></td> </tr> <tr id="l53"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=53#src-53">53</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-53" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Entry} or {</span><span class="javadoc">@link</span><span class="comment"> Folder} which should be compared to the second</span></span></td> </tr> <tr id="l54"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=54#src-54">54</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-54" class="srcLine"><span class="comment"> * {</span><span class="javadoc">@link</span><span class="comment"> Entry} or {</span><span class="javadoc">@link</span><span class="comment"> Folder}.</span></span></td> </tr> <tr id="l55"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=55#src-55">55</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-55" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> entry2</span></span></td> </tr> <tr id="l56"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=56#src-56">56</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-56" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Entry} or {</span><span class="javadoc">@link</span><span class="comment"> Folder} which should be compared to the first</span></span></td> </tr> <tr id="l57"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=57#src-57">57</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-57" class="srcLine"><span class="comment"> * {</span><span class="javadoc">@link</span><span class="comment"> Entry} or {</span><span class="javadoc">@link</span><span class="comment"> Folder}.</span></span></td> </tr> <tr id="l58"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=58#src-58">58</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-58" class="srcLine"><span class="comment"> * </span><span class="javadoc">@return</span><span class="comment"> one of -1, 0, or 1 according to whether first {</span><span class="javadoc">@link</span><span class="comment"> Entry}s or {</span><span class="javadoc">@link</span><span class="comment"> Folder}s name</span></span></td> </tr> <tr id="l59"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=59#src-59">59</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-59" class="srcLine"><span class="comment"> * as a {</span><span class="javadoc">@link</span><span class="comment"> String} is less, equal or higher than the second {</span><span class="javadoc">@link</span><span class="comment"> Entry}s or</span></span></td> </tr> <tr id="l60"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=60#src-60">60</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-60" class="srcLine"><span class="comment"> * {</span><span class="javadoc">@link</span><span class="comment"> Folder}s name.</span></span></td> </tr> <tr id="l61"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=61#src-61">61</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-61" class="srcLine"><span class="comment"> */</span></span></td> </tr> <tr id="l62"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=62#src-62">62</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-62" class="srcLine"> <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a>&gt; SIMPLE_NAME_COMPARATOR = <span class="keyword">new</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a>&gt;() {</span></td> </tr> <tr id="l63"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=63#src-63">63</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-63" class="srcLine"></span></td> </tr> <tr class="inlineStatsRow" align="right" valign="middle"> <td class="coverageCount"><a name="64" class="nolink">&#160;</a></td> <td class="coverageCount aui-icon aui-icon-small aui-iconfont-arrows-right" id='inlineStatsToggle-64' onclick="toggleInlineStats(this, 'inlinestats-64');"/> <td align="center" valign="middle"> <table id="inlinestats-64" style="display:none;" class="inlineStats" width="100%" cellspacing="1px" cellpadding="1px"> <tr onclick="toggleInlineStats(document.getElementById('inlineStatsToggle-64'), 'inlinestats-64');return true;"> <td><div> <div title="Empty" class="barEmpty" style="min-width:40px;"></div> </div></td><td> - </td> <td class="inlineStat">Uncovered Elements: 0 (0)</td> <td class="inlineStat">Complexity: 1</td> <td class="inlineStat">Complexity Density: -</td> </tr> </table> </td> </tr> <tr id="l64"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=64#src-64">64</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" methodStart srcCell" id="id-64"><img title="Method Statistics" onclick="toggleSrcRowVis(this, 64,75);" id="img-64" src="../../../img/collapse.gif" alt="toggle" class="icon"/><span id="src-64" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> @Override</span><span class="foldControl" onclick="toggleSrcRowVis(document.getElementById('img-64'), 64,75);" id="e64" style="display:none;border:none;">...</span></span></td> </tr> <tr id="l65"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=65#src-65">65</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-65" class="srcLine"> <span class="keyword">public</span> <span class="keyword">int</span> compare(<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a> entry1, <a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a> entry2) {</span></td> </tr> <tr id="l66"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=66#src-66">66</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-66" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">if</span> ((entry1 == <span class="keyword">null</span> || entry1.getName() == <span class="keyword">null</span>) &amp;&amp; (entry2 == <span class="keyword">null</span> || entry2.getName() == <span class="keyword">null</span>)) {</span></span></td> </tr> <tr id="l67"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=67#src-67">67</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-67" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if"> <span class="keyword">return</span> 0;</span></span></td> </tr> <tr id="l68"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=68#src-68">68</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-68" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (entry1 == <span class="keyword">null</span> || entry1.getName() == <span class="keyword">null</span>) {</span></span></td> </tr> <tr id="l69"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=69#src-69">69</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-69" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> -1;</span></span></td> </tr> <tr id="l70"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=70#src-70">70</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-70" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (entry2 == <span class="keyword">null</span> || entry2.getName() == <span class="keyword">null</span>) {</span></span></td> </tr> <tr id="l71"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=71#src-71">71</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-71" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> 1;</span></span></td> </tr> <tr id="l72"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=72#src-72">72</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-72" class="srcLine"> } <span class="keyword">else</span> {</span></td> </tr> <tr id="l73"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=73#src-73">73</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-73" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">return</span> entry1.getName().compareTo(entry2.getName());</span></span></td> </tr> <tr id="l74"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=74#src-74">74</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-74" class="srcLine"> }</span></td> </tr> <tr id="l75"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=75#src-75">75</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-75" class="srcLine"> }</span></td> </tr> <tr id="l76"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=76#src-76">76</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-76" class="srcLine"></span></td> </tr> <tr id="l77"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=77#src-77">77</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-77" class="srcLine"> };</span></td> </tr> <tr id="l78"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=78#src-78">78</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-78" class="srcLine"></span></td> </tr> <tr id="l79"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=79#src-79">79</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-79" class="srcLine"> <span class="comment">/**</span></span></td> </tr> <tr id="l80"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=80#src-80">80</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-80" class="srcLine"><span class="comment"> * Compares an {</span><span class="javadoc">@link</span><span class="comment"> Entry} to another by comparing their names as {</span><span class="javadoc">@link</span><span class="comment"> String} using</span></span></td> </tr> <tr id="l81"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=81#src-81">81</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-81" class="srcLine"><span class="comment"> * alphanumeric comparison.</span></span></td> </tr> <tr id="l82"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=82#src-82">82</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-82" class="srcLine"><span class="comment"> *</span></span></td> </tr> <tr id="l83"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=83#src-83">83</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-83" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> entry1</span></span></td> </tr> <tr id="l84"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=84#src-84">84</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-84" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Entry} which should be compared to the second {</span><span class="javadoc">@link</span><span class="comment"> Entry}.</span></span></td> </tr> <tr id="l85"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=85#src-85">85</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-85" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> entry2</span></span></td> </tr> <tr id="l86"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=86#src-86">86</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-86" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Entry} which should be compared to the first {</span><span class="javadoc">@link</span><span class="comment"> Entry}.</span></span></td> </tr> <tr id="l87"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=87#src-87">87</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-87" class="srcLine"><span class="comment"> * </span><span class="javadoc">@return</span><span class="comment"> one of -1, 0, or 1 according to whether {</span><span class="javadoc">@link</span><span class="comment"> Entry}1s name as a {</span><span class="javadoc">@link</span><span class="comment"> String} is</span></span></td> </tr> <tr id="l88"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=88#src-88">88</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-88" class="srcLine"><span class="comment"> * less, equal or higher than {</span><span class="javadoc">@link</span><span class="comment"> Entry}2s name.</span></span></td> </tr> <tr id="l89"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=89#src-89">89</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-89" class="srcLine"><span class="comment"> */</span></span></td> </tr> <tr id="l90"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=90#src-90">90</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-90" class="srcLine"> <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a>&gt; ENTRY_COMPARATOR = <span class="keyword">new</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a>&gt;() {</span></td> </tr> <tr id="l91"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=91#src-91">91</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-91" class="srcLine"></span></td> </tr> <tr class="inlineStatsRow" align="right" valign="middle"> <td class="coverageCount"><a name="92" class="nolink">&#160;</a></td> <td class="coverageCount aui-icon aui-icon-small aui-iconfont-arrows-right" id='inlineStatsToggle-92' onclick="toggleInlineStats(this, 'inlinestats-92');"/> <td align="center" valign="middle"> <table id="inlinestats-92" style="display:none;" class="inlineStats" width="100%" cellspacing="1px" cellpadding="1px"> <tr onclick="toggleInlineStats(document.getElementById('inlineStatsToggle-92'), 'inlinestats-92');return true;"> <td><div> <div title="Empty" class="barEmpty" style="min-width:40px;"></div> </div></td><td> - </td> <td class="inlineStat">Uncovered Elements: 0 (0)</td> <td class="inlineStat">Complexity: 1</td> <td class="inlineStat">Complexity Density: -</td> </tr> </table> </td> </tr> <tr id="l92"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=92#src-92">92</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" methodStart srcCell" id="id-92"><img title="Method Statistics" onclick="toggleSrcRowVis(this, 92,103);" id="img-92" src="../../../img/collapse.gif" alt="toggle" class="icon"/><span id="src-92" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> @Override</span><span class="foldControl" onclick="toggleSrcRowVis(document.getElementById('img-92'), 92,103);" id="e92" style="display:none;border:none;">...</span></span></td> </tr> <tr id="l93"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=93#src-93">93</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-93" class="srcLine"> <span class="keyword">public</span> <span class="keyword">int</span> compare(<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a> entry1, <a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a> entry2) {</span></td> </tr> <tr id="l94"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=94#src-94">94</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-94" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">if</span> ((entry1 == <span class="keyword">null</span> || entry1.getName() == <span class="keyword">null</span>) &amp;&amp; (entry2 == <span class="keyword">null</span> || entry2.getName() == <span class="keyword">null</span>)) {</span></span></td> </tr> <tr id="l95"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=95#src-95">95</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-95" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if"> <span class="keyword">return</span> 0;</span></span></td> </tr> <tr id="l96"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=96#src-96">96</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-96" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (entry1 == <span class="keyword">null</span> || entry1.getName() == <span class="keyword">null</span>) {</span></span></td> </tr> <tr id="l97"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=97#src-97">97</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-97" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> -1;</span></span></td> </tr> <tr id="l98"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=98#src-98">98</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-98" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (entry2 == <span class="keyword">null</span> || entry2.getName() == <span class="keyword">null</span>) {</span></span></td> </tr> <tr id="l99"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=99#src-99">99</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-99" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> 1;</span></span></td> </tr> <tr id="l100"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=100#src-100">100</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-100" class="srcLine"> } <span class="keyword">else</span> {</span></td> </tr> <tr id="l101"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=101#src-101">101</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-101" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">return</span> ALPHANUMERIC_COMPARATOR.compare(entry1.getName(), entry2.getName());</span></span></td> </tr> <tr id="l102"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=102#src-102">102</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-102" class="srcLine"> }</span></td> </tr> <tr id="l103"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=103#src-103">103</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-103" class="srcLine"> }</span></td> </tr> <tr id="l104"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=104#src-104">104</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-104" class="srcLine"></span></td> </tr> <tr id="l105"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=105#src-105">105</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-105" class="srcLine"> };</span></td> </tr> <tr id="l106"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=106#src-106">106</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-106" class="srcLine"></span></td> </tr> <tr id="l107"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=107#src-107">107</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-107" class="srcLine"> <span class="comment">/**</span></span></td> </tr> <tr id="l108"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=108#src-108">108</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-108" class="srcLine"><span class="comment"> * Compares an {</span><span class="javadoc">@link</span><span class="comment"> Entry} to another by comparing their last modified dates {</span><span class="javadoc">@link</span><span class="comment"> String}</span></span></td> </tr> <tr id="l109"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=109#src-109">109</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-109" class="srcLine"><span class="comment"> * descending from new to old.</span></span></td> </tr> <tr id="l110"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=110#src-110">110</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-110" class="srcLine"><span class="comment"> *</span></span></td> </tr> <tr id="l111"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=111#src-111">111</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-111" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> entry1</span></span></td> </tr> <tr id="l112"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=112#src-112">112</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-112" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Entry} which should be compared to the second {</span><span class="javadoc">@link</span><span class="comment"> Entry}.</span></span></td> </tr> <tr id="l113"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=113#src-113">113</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-113" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> entry2</span></span></td> </tr> <tr id="l114"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=114#src-114">114</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-114" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Entry} which should be compared to the first {</span><span class="javadoc">@link</span><span class="comment"> Entry}.</span></span></td> </tr> <tr id="l115"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=115#src-115">115</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-115" class="srcLine"><span class="comment"> * </span><span class="javadoc">@return</span><span class="comment"> one of -1, 0, or 1 according to whether {</span><span class="javadoc">@link</span><span class="comment"> Entry}1s date as a {</span><span class="javadoc">@link</span><span class="comment"> String} is</span></span></td> </tr> <tr id="l116"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=116#src-116">116</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-116" class="srcLine"><span class="comment"> * less, equal or higher than {</span><span class="javadoc">@link</span><span class="comment"> Entry}2s date.</span></span></td> </tr> <tr id="l117"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=117#src-117">117</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-117" class="srcLine"><span class="comment"> * </span><span class="javadoc">@since</span><span class="comment"> 7.4</span></span></td> </tr> <tr id="l118"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=118#src-118">118</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-118" class="srcLine"><span class="comment"> */</span></span></td> </tr> <tr id="l119"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=119#src-119">119</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-119" class="srcLine"> <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a>&gt; ENTRY_COMPARATOR_LAST_MODIFIED = <span class="keyword">new</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a>&gt;() {</span></td> </tr> <tr id="l120"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=120#src-120">120</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-120" class="srcLine"></span></td> </tr> <tr class="inlineStatsRow" align="right" valign="middle"> <td class="coverageCount"><a name="121" class="nolink">&#160;</a></td> <td class="coverageCount aui-icon aui-icon-small aui-iconfont-arrows-right" id='inlineStatsToggle-121' onclick="toggleInlineStats(this, 'inlinestats-121');"/> <td align="center" valign="middle"> <table id="inlinestats-121" style="display:none;" class="inlineStats" width="100%" cellspacing="1px" cellpadding="1px"> <tr onclick="toggleInlineStats(document.getElementById('inlineStatsToggle-121'), 'inlinestats-121');return true;"> <td><div> <div title="Empty" class="barEmpty" style="min-width:40px;"></div> </div></td><td> - </td> <td class="inlineStat">Uncovered Elements: 0 (0)</td> <td class="inlineStat">Complexity: 1</td> <td class="inlineStat">Complexity Density: -</td> </tr> </table> </td> </tr> <tr id="l121"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=121#src-121">121</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" methodStart srcCell" id="id-121"><img title="Method Statistics" onclick="toggleSrcRowVis(this, 121,138);" id="img-121" src="../../../img/collapse.gif" alt="toggle" class="icon"/><span id="src-121" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> @Override</span><span class="foldControl" onclick="toggleSrcRowVis(document.getElementById('img-121'), 121,138);" id="e121" style="display:none;border:none;">...</span></span></td> </tr> <tr id="l122"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=122#src-122">122</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-122" class="srcLine"> <span class="keyword">public</span> <span class="keyword">int</span> compare(<a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a> entry1, <a href="../../../com/rapidminer/repository/Entry.html#Entry">Entry</a> entry2) {</span></td> </tr> <tr id="l123"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=123#src-123">123</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-123" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">if</span> (!(entry1 <span class="keyword">instanceof</span> <a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a>) &amp;&amp; !(entry2 <span class="keyword">instanceof</span> <a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a>)) {</span></span></td> </tr> <tr id="l124"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=124#src-124">124</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-124" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if"> <span class="keyword">return</span> ALPHANUMERIC_COMPARATOR.compare(entry1.getName(), entry2.getName());</span></span></td> </tr> <tr id="l125"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=125#src-125">125</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-125" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (!(entry1 <span class="keyword">instanceof</span> <a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a>)) {</span></span></td> </tr> <tr id="l126"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=126#src-126">126</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-126" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> -1;</span></span></td> </tr> <tr id="l127"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=127#src-127">127</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-127" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (!(entry2 <span class="keyword">instanceof</span> <a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a>)) {</span></span></td> </tr> <tr id="l128"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=128#src-128">128</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-128" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> 1;</span></span></td> </tr> <tr id="l129"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=129#src-129">129</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-129" class="srcLine"> }</span></td> </tr> <tr id="l130"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=130#src-130">130</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-130" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> <a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a> dataEntry1 = (<a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a>) entry1;</span></span></td> </tr> <tr id="l131"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=131#src-131">131</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-131" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> <a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a> dataEntry2 = (<a href="../../../com/rapidminer/repository/DateEntry.html#DateEntry">DateEntry</a>) entry2;</span></span></td> </tr> <tr id="l132"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=132#src-132">132</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-132" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> <span class="keyword">int</span> compareValue = Long.compare(dataEntry2.getDate(), dataEntry1.getDate());</span></span></td> </tr> <tr id="l133"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=133#src-133">133</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-133" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">if</span> (compareValue == 0) { <span class="comment">// same date</span></span></span></td> </tr> <tr id="l134"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=134#src-134">134</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-134" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if"> <span class="keyword">return</span> ALPHANUMERIC_COMPARATOR.compare(dataEntry1.getName(), dataEntry2.getName());</span></span></td> </tr> <tr id="l135"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=135#src-135">135</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-135" class="srcLine"> } <span class="keyword">else</span> {</span></td> </tr> <tr id="l136"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=136#src-136">136</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-136" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">return</span> compareValue;</span></span></td> </tr> <tr id="l137"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=137#src-137">137</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-137" class="srcLine"> }</span></td> </tr> <tr id="l138"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=138#src-138">138</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-138" class="srcLine"> }</span></td> </tr> <tr id="l139"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=139#src-139">139</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-139" class="srcLine"></span></td> </tr> <tr id="l140"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=140#src-140">140</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-140" class="srcLine"> };</span></td> </tr> <tr id="l141"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=141#src-141">141</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-141" class="srcLine"></span></td> </tr> <tr id="l142"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=142#src-142">142</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-142" class="srcLine"> <span class="comment">/**</span></span></td> </tr> <tr id="l143"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=143#src-143">143</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-143" class="srcLine"><span class="comment"> * Compares two repositories, ordered by {</span><span class="javadoc">@link</span><span class="comment"> RepositoryType} (Samples, DB, Local</span></span></td> </tr> <tr id="l144"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=144#src-144">144</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-144" class="srcLine"><span class="comment"> * Repositories, Remote Repositories, Others). If the {</span><span class="javadoc">@link</span><span class="comment"> RepositoryType} of the</span></span></td> </tr> <tr id="l145"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=145#src-145">145</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-145" class="srcLine"><span class="comment"> * {</span><span class="javadoc">@link</span><span class="comment"> Repository}s is identical then their names as {</span><span class="javadoc">@link</span><span class="comment"> String} will be compared by</span></span></td> </tr> <tr id="l146"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=146#src-146">146</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-146" class="srcLine"><span class="comment"> * alphanumeric comparison.</span></span></td> </tr> <tr id="l147"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=147#src-147">147</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-147" class="srcLine"><span class="comment"> *</span></span></td> </tr> <tr id="l148"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=148#src-148">148</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-148" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> repository1</span></span></td> </tr> <tr id="l149"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=149#src-149">149</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-149" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Repository} which should be compared to the second {</span><span class="javadoc">@link</span><span class="comment"> Repository}.</span></span></td> </tr> <tr id="l150"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=150#src-150">150</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-150" class="srcLine"><span class="comment"> * </span><span class="javadoc">@param</span><span class="comment"> repository2</span></span></td> </tr> <tr id="l151"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=151#src-151">151</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-151" class="srcLine"><span class="comment"> * The {</span><span class="javadoc">@link</span><span class="comment"> Repository} which should be compared to the first {</span><span class="javadoc">@link</span><span class="comment"> Repository}.</span></span></td> </tr> <tr id="l152"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=152#src-152">152</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-152" class="srcLine"><span class="comment"> * </span><span class="javadoc">@return</span><span class="comment"> one of -1, 0, or 1 according to whether {</span><span class="javadoc">@link</span><span class="comment"> Repository}1 {</span><span class="javadoc">@link</span><span class="comment"> RepositoryType} is</span></span></td> </tr> <tr id="l153"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=153#src-153">153</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-153" class="srcLine"><span class="comment"> * higher prioritized than the {</span><span class="javadoc">@link</span><span class="comment"> RepositoryType} of {</span><span class="javadoc">@link</span><span class="comment"> Repository}2. If both</span></span></td> </tr> <tr id="l154"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=154#src-154">154</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-154" class="srcLine"><span class="comment"> * have the same {</span><span class="javadoc">@link</span><span class="comment"> RepositoryType} it will return an {</span><span class="javadoc">@link</span><span class="comment"> Integer} depending to</span></span></td> </tr> <tr id="l155"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=155#src-155">155</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-155" class="srcLine"><span class="comment"> * whether {</span><span class="javadoc">@link</span><span class="comment"> Repository}1 name as a {</span><span class="javadoc">@link</span><span class="comment"> String} is less, equal or higher than</span></span></td> </tr> <tr id="l156"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=156#src-156">156</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-156" class="srcLine"><span class="comment"> * {</span><span class="javadoc">@link</span><span class="comment"> Repository}2 name.</span></span></td> </tr> <tr id="l157"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=157#src-157">157</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-157" class="srcLine"><span class="comment"> */</span></span></td> </tr> <tr id="l158"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=158#src-158">158</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-158" class="srcLine"> <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Repository.html#Repository">Repository</a>&gt; REPOSITORY_COMPARATOR = <span class="keyword">new</span> Comparator&lt;<a href="../../../com/rapidminer/repository/Repository.html#Repository">Repository</a>&gt;() {</span></td> </tr> <tr id="l159"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=159#src-159">159</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-159" class="srcLine"></span></td> </tr> <tr class="inlineStatsRow" align="right" valign="middle"> <td class="coverageCount"><a name="160" class="nolink">&#160;</a></td> <td class="coverageCount aui-icon aui-icon-small aui-iconfont-arrows-right" id='inlineStatsToggle-160' onclick="toggleInlineStats(this, 'inlinestats-160');"/> <td align="center" valign="middle"> <table id="inlinestats-160" style="display:none;" class="inlineStats" width="100%" cellspacing="1px" cellpadding="1px"> <tr onclick="toggleInlineStats(document.getElementById('inlineStatsToggle-160'), 'inlinestats-160');return true;"> <td><div> <div title="Empty" class="barEmpty" style="min-width:40px;"></div> </div></td><td> - </td> <td class="inlineStat">Uncovered Elements: 0 (0)</td> <td class="inlineStat">Complexity: 1</td> <td class="inlineStat">Complexity Density: -</td> </tr> </table> </td> </tr> <tr id="l160"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=160#src-160">160</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" methodStart srcCell" id="id-160"><img title="Method Statistics" onclick="toggleSrcRowVis(this, 160,177);" id="img-160" src="../../../img/collapse.gif" alt="toggle" class="icon"/><span id="src-160" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> @Override</span><span class="foldControl" onclick="toggleSrcRowVis(document.getElementById('img-160'), 160,177);" id="e160" style="display:none;border:none;">...</span></span></td> </tr> <tr id="l161"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=161#src-161">161</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-161" class="srcLine"> <span class="keyword">public</span> <span class="keyword">int</span> compare(<a href="../../../com/rapidminer/repository/Repository.html#Repository">Repository</a> repository1, <a href="../../../com/rapidminer/repository/Repository.html#Repository">Repository</a> repository2) {</span></td> </tr> <tr id="l162"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=162#src-162">162</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-162" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">if</span> ((repository1 == <span class="keyword">null</span> || repository1.getName() == <span class="keyword">null</span>)</span></span></td> </tr> <tr id="l163"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=163#src-163">163</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-163" class="srcLine"> &amp;&amp; (repository2 == <span class="keyword">null</span> || repository2.getName() == <span class="keyword">null</span>)) {</span></td> </tr> <tr id="l164"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=164#src-164">164</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-164" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if"> <span class="keyword">return</span> 0;</span></span></td> </tr> <tr id="l165"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=165#src-165">165</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-165" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (repository1 == <span class="keyword">null</span> || repository1.getName() == <span class="keyword">null</span>) {</span></span></td> </tr> <tr id="l166"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=166#src-166">166</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-166" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> -1;</span></span></td> </tr> <tr id="l167"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=167#src-167">167</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-167" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> } <span class="keyword">else</span> <span class="keyword">if</span> (repository2 == <span class="keyword">null</span> || repository2.getName() == <span class="keyword">null</span>) {</span></span></td> </tr> <tr id="l168"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=168#src-168">168</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-168" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if,&#160;else"> <span class="keyword">return</span> 1;</span></span></td> </tr> <tr id="l169"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=169#src-169">169</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-169" class="srcLine"> }</span></td> </tr> <tr id="l170"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=170#src-170">170</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-170" class="srcLineFiltered"><span class="nolink" title="Filtered by: method"> <span class="keyword">int</span> compareValue = RepositoryType.getRepositoryType(repository1)</span></span></td> </tr> <tr id="l171"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=171#src-171">171</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-171" class="srcLine"> .compareTo(RepositoryType.getRepositoryType(repository2));</span></td> </tr> <tr id="l172"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=172#src-172">172</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-172" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">if</span> (compareValue == 0) { <span class="comment">// same repository type</span></span></span></td> </tr> <tr id="l173"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=173#src-173">173</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-173" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;if"> <span class="keyword">return</span> ALPHANUMERIC_COMPARATOR.compare(repository1.getName(), repository2.getName());</span></span></td> </tr> <tr id="l174"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=174#src-174">174</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-174" class="srcLine"> } <span class="keyword">else</span> {</span></td> </tr> <tr id="l175"> <td align="right" class="lineCount Filtered"><a class="lineNumHref" href="?line=175#src-175">175</a></td> <td align="right" class="coverageCount Filtered missedByTest" >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-175" class="srcLineFiltered"><span class="nolink" title="Filtered by: method,&#160;else"> <span class="keyword">return</span> compareValue;</span></span></td> </tr> <tr id="l176"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=176#src-176">176</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-176" class="srcLine"> }</span></td> </tr> <tr id="l177"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=177#src-177">177</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-177" class="srcLine"> }</span></td> </tr> <tr id="l178"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=178#src-178">178</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-178" class="srcLine"> };</span></td> </tr> <tr id="l179"> <td align="right" class="lineCount NoHilight"><a class="lineNumHref" href="?line=179#src-179">179</a></td> <td align="right" class="coverageCount NoHilight " >&#160;&#160;</td> <td class=" srcCell" ><span class="spacer"></span><span id="src-179" class="srcLine">}</span></td> </tr> </tbody></table> </div> </div><!-- .aui-tabs --> <script type="text/javascript"> var ol_bgclass = "overBG"; var ol_fgclass = "overFG"; var ol_cgclass = "overCaption"; var ol_captionfontclass= "overCaption"; var ol_closefontclass = "closeFont"; var ol_closeclick = 1; var ol_close = 'X'; var ol_wrap = 1; var rootRelPath = '../../../'; var testsPerFile = -1; </script> <script src="RepositoryTools.js" type="text/javascript"></script> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://www.atlassian.com/software/clover">Atlassian Clover</a> v 4.1.2 on 星期二 九月 5 2017 17:24:16 CST using coverage data from 星期四 一月 1 1970 08:00:00 CST. </li> </ul> <ul> <li>Clover Evaluation License registered to Clover Plugin. You have 29 day(s) before your license expires.</li> </ul> <div id="footer-logo"> <a target="_blank" href="http://www.atlassian.com/"> Atlassian </a> </div> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
cm-is-dog/rapidminer-studio-core
report/html/com/rapidminer/repository/RepositoryTools.html
HTML
agpl-3.0
107,414
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="text"]').focusin(function(ev){ if ($(this).attr('value')=="Location, latitude or longitude") { $(this).attr('value',''); } }); $('div.outer_map form input[type="text"]').focusout(function(ev){ if ($(this).attr('value')=="") { $(this).attr('value','Location, latitude or longitude'); } }); $('a#add_location_map').click(function(ev){ ev.preventDefault(); ev.stopPropagation(); markers_position = []; var position = $(this).offset(); $('div.map_window').css('top',position.top-310+'px'); $('div.map_window').css('left',position.left-140+'px'); $('div.map_window').fadeIn(function(){ var myOptions = { zoom: 1, center: new google.maps.LatLng(30, 0), disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map"),myOptions); var image = new google.maps.MarkerImage('/images/backoffice/projects/project_marker.png',new google.maps.Size(34, 42),new google.maps.Point(0,0), new google.maps.Point(17, 42)); google.maps.event.addListener(map,"click",function(event){ var marker = new google.maps.Marker({position: event.latLng, map:map, icon:image}); markers_position.push(event.latLng); }); $('#project_coordinates li input').each(function(){ var point = $(this).attr('value').replace(/\(/,'').replace(/\)/,'').split(', '); var position = new google.maps.LatLng(point[0],point[1]); var marker = new google.maps.Marker({position: position, map:map, icon:image}); markers_position.push(position); }); }); $(window).resize(function() { var position = $('a#add_location_map').position(); $('div.map_window').css('top',position.top+'px'); $('div.map_window').css('left',position.left+'px'); }); }); $('a.close').live('click', function(){ var li = $(this).closest('li') var point = li.children('input').attr('value'); li.remove(); for(var i=0;i<markers_position.length;i++){ if (point == markers_position[i]) { markers_position.splice(i); } } $(window).unbind('resize'); $('div.map_window').fadeOut(); return false; }); $('a.save').click(function(e){ $('#project_coordinates li').each(function(){ $(this).remove(); }); for(var i=0;i<markers_position.length;i++){ $('#project_coordinates').append('<li><p>'+markers_position[i]+'</p><input type="hidden" name="project[points][]" value="'+markers_position[i]+'" /><a href="javascript:void(null)" class="close"></a></li>'); } $(window).unbind('resize'); $('div.map_window').fadeOut(); }); }); function searchPlace() { var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); } }); }
InterActionNGO/NGO-admin
public/app/javascripts/backoffice/project_map.js
JavaScript
agpl-3.0
3,672
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link type="image/x-icon" href="../favicon.ico" rel="icon" /> <link href="../src/tamination.css" type="text/css" rel="stylesheet" /> <link href="../src/jquery-ui.css" rel="stylesheet" /> <script src="../ext/require.js" data-main="../src/config"></script> <title>Inlet</title> </head> <body><div class="definition"> <h2>Inlet</h2> <p>From parallel waves or applicable parallel 3-and-1 lines with only the left-end dancers facing out: The lead end and adjacent dancer (outer-actives) <a href="../ms/recycle.html">Recycle</a>, as the trailing end and the adjacent dancer (inner-actives) <a href="../c1/box-split_recycle.html">Split</a> or <a href="../a2/recycle.html"> Facing Couples Recycle</a>, adjusting to end in a center wave. Ends in a quarter tag formation. (Note: Applicable parallel 3-and-1 lines are those in which both ends are beaus and in which the out-facing beau and the adjacent dancer are in a miniwave.)</p> <p class="copyright">&copy; Copyright 1983, 1986-1988, 1995-2011 Bill Davis, John Sybalsky and CALLERLAB Inc., The International Association of Square Dance Callers. Permission to reprint, republish, and create derivative works without royalty is hereby granted, provided this notice appears. Publication on the Internet of derivative works without royalty is hereby granted provided this notice appears. Permission to quote parts or all of this document without royalty is hereby granted, provided this notice is included. Information contained herein shall not be changed nor revised in any derivation or publication. </p> </div></body> </html>
bradchristie/taminations
c2/inlet.html
HTML
agpl-3.0
1,737
```java package com.bio4j.blueprints.model.nodes; import com.bio4j.blueprints.model.Vertex; import com.bio4j.model.nodes.Consortium; /** * Models consortium entities that take part in publications. * @author Pablo Pareja Tobes <ppareja@era7.com> */ public final class ConsortiumNode extends Vertex implements Consortium{ public static final String NODE_TYPE = ConsortiumNode.class.getCanonicalName(); /** Consortium name **/ public static final String NAME_PROPERTY = "consortium_name"; public ConsortiumNode(com.tinkerpop.blueprints.Vertex v){ super(v, NODE_TYPE); } @Override public String getName(){ return String.valueOf(vertex.getProperty(NAME_PROPERTY));} @Override public void setName(String value){ vertex.setProperty(NAME_PROPERTY, value);} @Override public String toString(){ return "name = " + getName(); } } ``` ------ ### Index + src + main + java + com + bio4j + blueprints + model + [Edge.java][main/java/com/bio4j/blueprints/model/Edge.java] + nodes + [AlternativeProductNode.java][main/java/com/bio4j/blueprints/model/nodes/AlternativeProductNode.java] + citation + [ArticleNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/ArticleNode.java] + [BookNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/BookNode.java] + [DBNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/DBNode.java] + [JournalNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/JournalNode.java] + [OnlineArticleNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/OnlineArticleNode.java] + [OnlineJournalNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/OnlineJournalNode.java] + [PatentNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/PatentNode.java] + [PublisherNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/PublisherNode.java] + [SubmissionNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/SubmissionNode.java] + [ThesisNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/ThesisNode.java] + [UnpublishedObservationNode.java][main/java/com/bio4j/blueprints/model/nodes/citation/UnpublishedObservationNode.java] + [CityNode.java][main/java/com/bio4j/blueprints/model/nodes/CityNode.java] + [CommentTypeNode.java][main/java/com/bio4j/blueprints/model/nodes/CommentTypeNode.java] + [ConsortiumNode.java][main/java/com/bio4j/blueprints/model/nodes/ConsortiumNode.java] + [CountryNode.java][main/java/com/bio4j/blueprints/model/nodes/CountryNode.java] + [DatasetNode.java][main/java/com/bio4j/blueprints/model/nodes/DatasetNode.java] + [EnzymeNode.java][main/java/com/bio4j/blueprints/model/nodes/EnzymeNode.java] + [FeatureTypeNode.java][main/java/com/bio4j/blueprints/model/nodes/FeatureTypeNode.java] + [GoTermNode.java][main/java/com/bio4j/blueprints/model/nodes/GoTermNode.java] + [InstituteNode.java][main/java/com/bio4j/blueprints/model/nodes/InstituteNode.java] + [InterproNode.java][main/java/com/bio4j/blueprints/model/nodes/InterproNode.java] + [IsoformNode.java][main/java/com/bio4j/blueprints/model/nodes/IsoformNode.java] + [KeywordNode.java][main/java/com/bio4j/blueprints/model/nodes/KeywordNode.java] + ncbi + [NCBITaxonNode.java][main/java/com/bio4j/blueprints/model/nodes/ncbi/NCBITaxonNode.java] + [OrganismNode.java][main/java/com/bio4j/blueprints/model/nodes/OrganismNode.java] + [PersonNode.java][main/java/com/bio4j/blueprints/model/nodes/PersonNode.java] + [PfamNode.java][main/java/com/bio4j/blueprints/model/nodes/PfamNode.java] + [ProteinNode.java][main/java/com/bio4j/blueprints/model/nodes/ProteinNode.java] + reactome + [ReactomeTermNode.java][main/java/com/bio4j/blueprints/model/nodes/reactome/ReactomeTermNode.java] + refseq + [CDSNode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/CDSNode.java] + [GeneNode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/GeneNode.java] + [GenomeElementNode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/GenomeElementNode.java] + rna + [MiscRNANode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/rna/MiscRNANode.java] + [MRNANode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/rna/MRNANode.java] + [NcRNANode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/rna/NcRNANode.java] + [RNANode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/rna/RNANode.java] + [RRNANode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/rna/RRNANode.java] + [TmRNANode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/rna/TmRNANode.java] + [TRNANode.java][main/java/com/bio4j/blueprints/model/nodes/refseq/rna/TRNANode.java] + [SequenceCautionNode.java][main/java/com/bio4j/blueprints/model/nodes/SequenceCautionNode.java] + [SubcellularLocationNode.java][main/java/com/bio4j/blueprints/model/nodes/SubcellularLocationNode.java] + [TaxonNode.java][main/java/com/bio4j/blueprints/model/nodes/TaxonNode.java] + relationships + aproducts + [AlternativeProductInitiationRel.java][main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductInitiationRel.java] + [AlternativeProductPromoterRel.java][main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductPromoterRel.java] + [AlternativeProductRibosomalFrameshiftingRel.java][main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductRibosomalFrameshiftingRel.java] + [AlternativeProductSplicingRel.java][main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductSplicingRel.java] + citation + article + [ArticleAuthorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/article/ArticleAuthorRel.java] + [ArticleJournalRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/article/ArticleJournalRel.java] + [ArticleProteinCitationRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/article/ArticleProteinCitationRel.java] + book + [BookAuthorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/book/BookAuthorRel.java] + [BookCityRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/book/BookCityRel.java] + [BookEditorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/book/BookEditorRel.java] + [BookProteinCitationRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/book/BookProteinCitationRel.java] + [BookPublisherRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/book/BookPublisherRel.java] + onarticle + [OnlineArticleAuthorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/onarticle/OnlineArticleAuthorRel.java] + [OnlineArticleJournalRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/onarticle/OnlineArticleJournalRel.java] + [OnlineArticleProteinCitationRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/onarticle/OnlineArticleProteinCitationRel.java] + patent + [PatentAuthorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/patent/PatentAuthorRel.java] + [PatentProteinCitationRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/patent/PatentProteinCitationRel.java] + submission + [SubmissionAuthorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/submission/SubmissionAuthorRel.java] + [SubmissionDbRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/submission/SubmissionDbRel.java] + [SubmissionProteinCitationRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/submission/SubmissionProteinCitationRel.java] + thesis + [ThesisAuthorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/thesis/ThesisAuthorRel.java] + [ThesisInstituteRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/thesis/ThesisInstituteRel.java] + [ThesisProteinCitationRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/thesis/ThesisProteinCitationRel.java] + uo + [UnpublishedObservationAuthorRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/uo/UnpublishedObservationAuthorRel.java] + [UnpublishedObservationProteinCitationRel.java][main/java/com/bio4j/blueprints/model/relationships/citation/uo/UnpublishedObservationProteinCitationRel.java] + comment + [AllergenCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/AllergenCommentRel.java] + [BasicCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/BasicCommentRel.java] + [BioPhysicoChemicalPropertiesCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/BioPhysicoChemicalPropertiesCommentRel.java] + [BiotechnologyCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/BiotechnologyCommentRel.java] + [CatalyticActivityCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/CatalyticActivityCommentRel.java] + [CautionCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/CautionCommentRel.java] + [CofactorCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/CofactorCommentRel.java] + [DevelopmentalStageCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/DevelopmentalStageCommentRel.java] + [DiseaseCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/DiseaseCommentRel.java] + [DisruptionPhenotypeCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/DisruptionPhenotypeCommentRel.java] + [DomainCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/DomainCommentRel.java] + [EnzymeRegulationCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/EnzymeRegulationCommentRel.java] + [FunctionCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/FunctionCommentRel.java] + [InductionCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/InductionCommentRel.java] + [MassSpectrometryCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/MassSpectrometryCommentRel.java] + [MiscellaneousCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/MiscellaneousCommentRel.java] + [OnlineInformationCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/OnlineInformationCommentRel.java] + [PathwayCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/PathwayCommentRel.java] + [PharmaceuticalCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/PharmaceuticalCommentRel.java] + [PolymorphismCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/PolymorphismCommentRel.java] + [PostTranslationalModificationCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/PostTranslationalModificationCommentRel.java] + [RnaEditingCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/RnaEditingCommentRel.java] + [SimilarityCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/SimilarityCommentRel.java] + [SubunitCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/SubunitCommentRel.java] + [TissueSpecificityCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/TissueSpecificityCommentRel.java] + [ToxicDoseCommentRel.java][main/java/com/bio4j/blueprints/model/relationships/comment/ToxicDoseCommentRel.java] + features + [ActiveSiteFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/ActiveSiteFeatureRel.java] + [BasicFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/BasicFeatureRel.java] + [BindingSiteFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/BindingSiteFeatureRel.java] + [CalciumBindingRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/CalciumBindingRegionFeatureRel.java] + [ChainFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/ChainFeatureRel.java] + [CoiledCoilRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/CoiledCoilRegionFeatureRel.java] + [CompositionallyBiasedRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/CompositionallyBiasedRegionFeatureRel.java] + [CrossLinkFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/CrossLinkFeatureRel.java] + [DisulfideBondFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/DisulfideBondFeatureRel.java] + [DnaBindingRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/DnaBindingRegionFeatureRel.java] + [DomainFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/DomainFeatureRel.java] + [GlycosylationSiteFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/GlycosylationSiteFeatureRel.java] + [HelixFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/HelixFeatureRel.java] + [InitiatorMethionineFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/InitiatorMethionineFeatureRel.java] + [IntramembraneRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/IntramembraneRegionFeatureRel.java] + [LipidMoietyBindingRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/LipidMoietyBindingRegionFeatureRel.java] + [MetalIonBindingSiteFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/MetalIonBindingSiteFeatureRel.java] + [ModifiedResidueFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/ModifiedResidueFeatureRel.java] + [MutagenesisSiteFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/MutagenesisSiteFeatureRel.java] + [NonConsecutiveResiduesFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/NonConsecutiveResiduesFeatureRel.java] + [NonStandardAminoAcidFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/NonStandardAminoAcidFeatureRel.java] + [NonTerminalResidueFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/NonTerminalResidueFeatureRel.java] + [NucleotidePhosphateBindingRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/NucleotidePhosphateBindingRegionFeatureRel.java] + [PeptideFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/PeptideFeatureRel.java] + [PropeptideFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/PropeptideFeatureRel.java] + [RegionOfInterestFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/RegionOfInterestFeatureRel.java] + [RepeatFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/RepeatFeatureRel.java] + [SequenceConflictFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/SequenceConflictFeatureRel.java] + [SequenceVariantFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/SequenceVariantFeatureRel.java] + [ShortSequenceMotifFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/ShortSequenceMotifFeatureRel.java] + [SignalPeptideFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/SignalPeptideFeatureRel.java] + [SiteFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/SiteFeatureRel.java] + [SpliceVariantFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/SpliceVariantFeatureRel.java] + [StrandFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/StrandFeatureRel.java] + [TopologicalDomainFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/TopologicalDomainFeatureRel.java] + [TransitPeptideFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/TransitPeptideFeatureRel.java] + [TransmembraneRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/TransmembraneRegionFeatureRel.java] + [TurnFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/TurnFeatureRel.java] + [UnsureResidueFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/UnsureResidueFeatureRel.java] + [ZincFingerRegionFeatureRel.java][main/java/com/bio4j/blueprints/model/relationships/features/ZincFingerRegionFeatureRel.java] + go + [HasPartOfGoRel.java][main/java/com/bio4j/blueprints/model/relationships/go/HasPartOfGoRel.java] + [IsAGoRel.java][main/java/com/bio4j/blueprints/model/relationships/go/IsAGoRel.java] + [NegativelyRegulatesGoRel.java][main/java/com/bio4j/blueprints/model/relationships/go/NegativelyRegulatesGoRel.java] + [PartOfGoRel.java][main/java/com/bio4j/blueprints/model/relationships/go/PartOfGoRel.java] + [PositivelyRegulatesGoRel.java][main/java/com/bio4j/blueprints/model/relationships/go/PositivelyRegulatesGoRel.java] + [RegulatesGoRel.java][main/java/com/bio4j/blueprints/model/relationships/go/RegulatesGoRel.java] + [InstituteCountryRel.java][main/java/com/bio4j/blueprints/model/relationships/InstituteCountryRel.java] + [IsoformEventGeneratorRel.java][main/java/com/bio4j/blueprints/model/relationships/IsoformEventGeneratorRel.java] + ncbi + [NCBITaxonParentRel.java][main/java/com/bio4j/blueprints/model/relationships/ncbi/NCBITaxonParentRel.java] + [NCBITaxonRel.java][main/java/com/bio4j/blueprints/model/relationships/ncbi/NCBITaxonRel.java] + protein + [BasicProteinSequenceCautionRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/BasicProteinSequenceCautionRel.java] + [ProteinDatasetRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinDatasetRel.java] + [ProteinEnzymaticActivityRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinEnzymaticActivityRel.java] + [ProteinErroneousGeneModelPredictionRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousGeneModelPredictionRel.java] + [ProteinErroneousInitiationRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousInitiationRel.java] + [ProteinErroneousTerminationRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousTerminationRel.java] + [ProteinErroneousTranslationRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousTranslationRel.java] + [ProteinFrameshiftRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinFrameshiftRel.java] + [ProteinGenomeElementRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinGenomeElementRel.java] + [ProteinGoRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinGoRel.java] + [ProteinInterproRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinInterproRel.java] + [ProteinIsoformInteractionRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinIsoformInteractionRel.java] + [ProteinIsoformRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinIsoformRel.java] + [ProteinKeywordRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinKeywordRel.java] + [ProteinMiscellaneousDiscrepancyRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinMiscellaneousDiscrepancyRel.java] + [ProteinOrganismRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinOrganismRel.java] + [ProteinPfamRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinPfamRel.java] + [ProteinProteinInteractionRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinProteinInteractionRel.java] + [ProteinReactomeRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinReactomeRel.java] + [ProteinSubcellularLocationRel.java][main/java/com/bio4j/blueprints/model/relationships/protein/ProteinSubcellularLocationRel.java] + refseq + [GenomeElementCDSRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementCDSRel.java] + [GenomeElementGeneRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementGeneRel.java] + [GenomeElementMiscRnaRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementMiscRnaRel.java] + [GenomeElementMRnaRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementMRnaRel.java] + [GenomeElementNcRnaRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementNcRnaRel.java] + [GenomeElementRRnaRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementRRnaRel.java] + [GenomeElementTmRnaRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementTmRnaRel.java] + [GenomeElementTRnaRel.java][main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementTRnaRel.java] + sc + [ErroneousGeneModelPredictionRel.java][main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousGeneModelPredictionRel.java] + [ErroneousInitiationRel.java][main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousInitiationRel.java] + [ErroneousTerminationRel.java][main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousTerminationRel.java] + [ErroneousTranslationRel.java][main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousTranslationRel.java] + [FrameshiftRel.java][main/java/com/bio4j/blueprints/model/relationships/sc/FrameshiftRel.java] + [MiscellaneousDiscrepancyRel.java][main/java/com/bio4j/blueprints/model/relationships/sc/MiscellaneousDiscrepancyRel.java] + [SubcellularLocationParentRel.java][main/java/com/bio4j/blueprints/model/relationships/SubcellularLocationParentRel.java] + [TaxonParentRel.java][main/java/com/bio4j/blueprints/model/relationships/TaxonParentRel.java] + uniref + [UniRef100MemberRel.java][main/java/com/bio4j/blueprints/model/relationships/uniref/UniRef100MemberRel.java] + [UniRef50MemberRel.java][main/java/com/bio4j/blueprints/model/relationships/uniref/UniRef50MemberRel.java] + [UniRef90MemberRel.java][main/java/com/bio4j/blueprints/model/relationships/uniref/UniRef90MemberRel.java] + [Vertex.java][main/java/com/bio4j/blueprints/model/Vertex.java] + test + java + com + era7 + [bio4j-model.java][test/java/com/era7/bio4j-model.java] [main/java/com/bio4j/blueprints/model/Edge.java]: ../Edge.java.md [main/java/com/bio4j/blueprints/model/nodes/AlternativeProductNode.java]: AlternativeProductNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/ArticleNode.java]: citation/ArticleNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/BookNode.java]: citation/BookNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/DBNode.java]: citation/DBNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/JournalNode.java]: citation/JournalNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/OnlineArticleNode.java]: citation/OnlineArticleNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/OnlineJournalNode.java]: citation/OnlineJournalNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/PatentNode.java]: citation/PatentNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/PublisherNode.java]: citation/PublisherNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/SubmissionNode.java]: citation/SubmissionNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/ThesisNode.java]: citation/ThesisNode.java.md [main/java/com/bio4j/blueprints/model/nodes/citation/UnpublishedObservationNode.java]: citation/UnpublishedObservationNode.java.md [main/java/com/bio4j/blueprints/model/nodes/CityNode.java]: CityNode.java.md [main/java/com/bio4j/blueprints/model/nodes/CommentTypeNode.java]: CommentTypeNode.java.md [main/java/com/bio4j/blueprints/model/nodes/ConsortiumNode.java]: ConsortiumNode.java.md [main/java/com/bio4j/blueprints/model/nodes/CountryNode.java]: CountryNode.java.md [main/java/com/bio4j/blueprints/model/nodes/DatasetNode.java]: DatasetNode.java.md [main/java/com/bio4j/blueprints/model/nodes/EnzymeNode.java]: EnzymeNode.java.md [main/java/com/bio4j/blueprints/model/nodes/FeatureTypeNode.java]: FeatureTypeNode.java.md [main/java/com/bio4j/blueprints/model/nodes/GoTermNode.java]: GoTermNode.java.md [main/java/com/bio4j/blueprints/model/nodes/InstituteNode.java]: InstituteNode.java.md [main/java/com/bio4j/blueprints/model/nodes/InterproNode.java]: InterproNode.java.md [main/java/com/bio4j/blueprints/model/nodes/IsoformNode.java]: IsoformNode.java.md [main/java/com/bio4j/blueprints/model/nodes/KeywordNode.java]: KeywordNode.java.md [main/java/com/bio4j/blueprints/model/nodes/ncbi/NCBITaxonNode.java]: ncbi/NCBITaxonNode.java.md [main/java/com/bio4j/blueprints/model/nodes/OrganismNode.java]: OrganismNode.java.md [main/java/com/bio4j/blueprints/model/nodes/PersonNode.java]: PersonNode.java.md [main/java/com/bio4j/blueprints/model/nodes/PfamNode.java]: PfamNode.java.md [main/java/com/bio4j/blueprints/model/nodes/ProteinNode.java]: ProteinNode.java.md [main/java/com/bio4j/blueprints/model/nodes/reactome/ReactomeTermNode.java]: reactome/ReactomeTermNode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/CDSNode.java]: refseq/CDSNode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/GeneNode.java]: refseq/GeneNode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/GenomeElementNode.java]: refseq/GenomeElementNode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/rna/MiscRNANode.java]: refseq/rna/MiscRNANode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/rna/MRNANode.java]: refseq/rna/MRNANode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/rna/NcRNANode.java]: refseq/rna/NcRNANode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/rna/RNANode.java]: refseq/rna/RNANode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/rna/RRNANode.java]: refseq/rna/RRNANode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/rna/TmRNANode.java]: refseq/rna/TmRNANode.java.md [main/java/com/bio4j/blueprints/model/nodes/refseq/rna/TRNANode.java]: refseq/rna/TRNANode.java.md [main/java/com/bio4j/blueprints/model/nodes/SequenceCautionNode.java]: SequenceCautionNode.java.md [main/java/com/bio4j/blueprints/model/nodes/SubcellularLocationNode.java]: SubcellularLocationNode.java.md [main/java/com/bio4j/blueprints/model/nodes/TaxonNode.java]: TaxonNode.java.md [main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductInitiationRel.java]: ../relationships/aproducts/AlternativeProductInitiationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductPromoterRel.java]: ../relationships/aproducts/AlternativeProductPromoterRel.java.md [main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductRibosomalFrameshiftingRel.java]: ../relationships/aproducts/AlternativeProductRibosomalFrameshiftingRel.java.md [main/java/com/bio4j/blueprints/model/relationships/aproducts/AlternativeProductSplicingRel.java]: ../relationships/aproducts/AlternativeProductSplicingRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/article/ArticleAuthorRel.java]: ../relationships/citation/article/ArticleAuthorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/article/ArticleJournalRel.java]: ../relationships/citation/article/ArticleJournalRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/article/ArticleProteinCitationRel.java]: ../relationships/citation/article/ArticleProteinCitationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/book/BookAuthorRel.java]: ../relationships/citation/book/BookAuthorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/book/BookCityRel.java]: ../relationships/citation/book/BookCityRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/book/BookEditorRel.java]: ../relationships/citation/book/BookEditorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/book/BookProteinCitationRel.java]: ../relationships/citation/book/BookProteinCitationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/book/BookPublisherRel.java]: ../relationships/citation/book/BookPublisherRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/onarticle/OnlineArticleAuthorRel.java]: ../relationships/citation/onarticle/OnlineArticleAuthorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/onarticle/OnlineArticleJournalRel.java]: ../relationships/citation/onarticle/OnlineArticleJournalRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/onarticle/OnlineArticleProteinCitationRel.java]: ../relationships/citation/onarticle/OnlineArticleProteinCitationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/patent/PatentAuthorRel.java]: ../relationships/citation/patent/PatentAuthorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/patent/PatentProteinCitationRel.java]: ../relationships/citation/patent/PatentProteinCitationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/submission/SubmissionAuthorRel.java]: ../relationships/citation/submission/SubmissionAuthorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/submission/SubmissionDbRel.java]: ../relationships/citation/submission/SubmissionDbRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/submission/SubmissionProteinCitationRel.java]: ../relationships/citation/submission/SubmissionProteinCitationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/thesis/ThesisAuthorRel.java]: ../relationships/citation/thesis/ThesisAuthorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/thesis/ThesisInstituteRel.java]: ../relationships/citation/thesis/ThesisInstituteRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/thesis/ThesisProteinCitationRel.java]: ../relationships/citation/thesis/ThesisProteinCitationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/uo/UnpublishedObservationAuthorRel.java]: ../relationships/citation/uo/UnpublishedObservationAuthorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/citation/uo/UnpublishedObservationProteinCitationRel.java]: ../relationships/citation/uo/UnpublishedObservationProteinCitationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/AllergenCommentRel.java]: ../relationships/comment/AllergenCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/BasicCommentRel.java]: ../relationships/comment/BasicCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/BioPhysicoChemicalPropertiesCommentRel.java]: ../relationships/comment/BioPhysicoChemicalPropertiesCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/BiotechnologyCommentRel.java]: ../relationships/comment/BiotechnologyCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/CatalyticActivityCommentRel.java]: ../relationships/comment/CatalyticActivityCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/CautionCommentRel.java]: ../relationships/comment/CautionCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/CofactorCommentRel.java]: ../relationships/comment/CofactorCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/DevelopmentalStageCommentRel.java]: ../relationships/comment/DevelopmentalStageCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/DiseaseCommentRel.java]: ../relationships/comment/DiseaseCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/DisruptionPhenotypeCommentRel.java]: ../relationships/comment/DisruptionPhenotypeCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/DomainCommentRel.java]: ../relationships/comment/DomainCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/EnzymeRegulationCommentRel.java]: ../relationships/comment/EnzymeRegulationCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/FunctionCommentRel.java]: ../relationships/comment/FunctionCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/InductionCommentRel.java]: ../relationships/comment/InductionCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/MassSpectrometryCommentRel.java]: ../relationships/comment/MassSpectrometryCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/MiscellaneousCommentRel.java]: ../relationships/comment/MiscellaneousCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/OnlineInformationCommentRel.java]: ../relationships/comment/OnlineInformationCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/PathwayCommentRel.java]: ../relationships/comment/PathwayCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/PharmaceuticalCommentRel.java]: ../relationships/comment/PharmaceuticalCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/PolymorphismCommentRel.java]: ../relationships/comment/PolymorphismCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/PostTranslationalModificationCommentRel.java]: ../relationships/comment/PostTranslationalModificationCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/RnaEditingCommentRel.java]: ../relationships/comment/RnaEditingCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/SimilarityCommentRel.java]: ../relationships/comment/SimilarityCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/SubunitCommentRel.java]: ../relationships/comment/SubunitCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/TissueSpecificityCommentRel.java]: ../relationships/comment/TissueSpecificityCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/comment/ToxicDoseCommentRel.java]: ../relationships/comment/ToxicDoseCommentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/ActiveSiteFeatureRel.java]: ../relationships/features/ActiveSiteFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/BasicFeatureRel.java]: ../relationships/features/BasicFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/BindingSiteFeatureRel.java]: ../relationships/features/BindingSiteFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/CalciumBindingRegionFeatureRel.java]: ../relationships/features/CalciumBindingRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/ChainFeatureRel.java]: ../relationships/features/ChainFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/CoiledCoilRegionFeatureRel.java]: ../relationships/features/CoiledCoilRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/CompositionallyBiasedRegionFeatureRel.java]: ../relationships/features/CompositionallyBiasedRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/CrossLinkFeatureRel.java]: ../relationships/features/CrossLinkFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/DisulfideBondFeatureRel.java]: ../relationships/features/DisulfideBondFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/DnaBindingRegionFeatureRel.java]: ../relationships/features/DnaBindingRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/DomainFeatureRel.java]: ../relationships/features/DomainFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/GlycosylationSiteFeatureRel.java]: ../relationships/features/GlycosylationSiteFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/HelixFeatureRel.java]: ../relationships/features/HelixFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/InitiatorMethionineFeatureRel.java]: ../relationships/features/InitiatorMethionineFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/IntramembraneRegionFeatureRel.java]: ../relationships/features/IntramembraneRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/LipidMoietyBindingRegionFeatureRel.java]: ../relationships/features/LipidMoietyBindingRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/MetalIonBindingSiteFeatureRel.java]: ../relationships/features/MetalIonBindingSiteFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/ModifiedResidueFeatureRel.java]: ../relationships/features/ModifiedResidueFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/MutagenesisSiteFeatureRel.java]: ../relationships/features/MutagenesisSiteFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/NonConsecutiveResiduesFeatureRel.java]: ../relationships/features/NonConsecutiveResiduesFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/NonStandardAminoAcidFeatureRel.java]: ../relationships/features/NonStandardAminoAcidFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/NonTerminalResidueFeatureRel.java]: ../relationships/features/NonTerminalResidueFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/NucleotidePhosphateBindingRegionFeatureRel.java]: ../relationships/features/NucleotidePhosphateBindingRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/PeptideFeatureRel.java]: ../relationships/features/PeptideFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/PropeptideFeatureRel.java]: ../relationships/features/PropeptideFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/RegionOfInterestFeatureRel.java]: ../relationships/features/RegionOfInterestFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/RepeatFeatureRel.java]: ../relationships/features/RepeatFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/SequenceConflictFeatureRel.java]: ../relationships/features/SequenceConflictFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/SequenceVariantFeatureRel.java]: ../relationships/features/SequenceVariantFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/ShortSequenceMotifFeatureRel.java]: ../relationships/features/ShortSequenceMotifFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/SignalPeptideFeatureRel.java]: ../relationships/features/SignalPeptideFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/SiteFeatureRel.java]: ../relationships/features/SiteFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/SpliceVariantFeatureRel.java]: ../relationships/features/SpliceVariantFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/StrandFeatureRel.java]: ../relationships/features/StrandFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/TopologicalDomainFeatureRel.java]: ../relationships/features/TopologicalDomainFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/TransitPeptideFeatureRel.java]: ../relationships/features/TransitPeptideFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/TransmembraneRegionFeatureRel.java]: ../relationships/features/TransmembraneRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/TurnFeatureRel.java]: ../relationships/features/TurnFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/UnsureResidueFeatureRel.java]: ../relationships/features/UnsureResidueFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/features/ZincFingerRegionFeatureRel.java]: ../relationships/features/ZincFingerRegionFeatureRel.java.md [main/java/com/bio4j/blueprints/model/relationships/go/HasPartOfGoRel.java]: ../relationships/go/HasPartOfGoRel.java.md [main/java/com/bio4j/blueprints/model/relationships/go/IsAGoRel.java]: ../relationships/go/IsAGoRel.java.md [main/java/com/bio4j/blueprints/model/relationships/go/NegativelyRegulatesGoRel.java]: ../relationships/go/NegativelyRegulatesGoRel.java.md [main/java/com/bio4j/blueprints/model/relationships/go/PartOfGoRel.java]: ../relationships/go/PartOfGoRel.java.md [main/java/com/bio4j/blueprints/model/relationships/go/PositivelyRegulatesGoRel.java]: ../relationships/go/PositivelyRegulatesGoRel.java.md [main/java/com/bio4j/blueprints/model/relationships/go/RegulatesGoRel.java]: ../relationships/go/RegulatesGoRel.java.md [main/java/com/bio4j/blueprints/model/relationships/InstituteCountryRel.java]: ../relationships/InstituteCountryRel.java.md [main/java/com/bio4j/blueprints/model/relationships/IsoformEventGeneratorRel.java]: ../relationships/IsoformEventGeneratorRel.java.md [main/java/com/bio4j/blueprints/model/relationships/ncbi/NCBITaxonParentRel.java]: ../relationships/ncbi/NCBITaxonParentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/ncbi/NCBITaxonRel.java]: ../relationships/ncbi/NCBITaxonRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/BasicProteinSequenceCautionRel.java]: ../relationships/protein/BasicProteinSequenceCautionRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinDatasetRel.java]: ../relationships/protein/ProteinDatasetRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinEnzymaticActivityRel.java]: ../relationships/protein/ProteinEnzymaticActivityRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousGeneModelPredictionRel.java]: ../relationships/protein/ProteinErroneousGeneModelPredictionRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousInitiationRel.java]: ../relationships/protein/ProteinErroneousInitiationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousTerminationRel.java]: ../relationships/protein/ProteinErroneousTerminationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinErroneousTranslationRel.java]: ../relationships/protein/ProteinErroneousTranslationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinFrameshiftRel.java]: ../relationships/protein/ProteinFrameshiftRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinGenomeElementRel.java]: ../relationships/protein/ProteinGenomeElementRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinGoRel.java]: ../relationships/protein/ProteinGoRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinInterproRel.java]: ../relationships/protein/ProteinInterproRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinIsoformInteractionRel.java]: ../relationships/protein/ProteinIsoformInteractionRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinIsoformRel.java]: ../relationships/protein/ProteinIsoformRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinKeywordRel.java]: ../relationships/protein/ProteinKeywordRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinMiscellaneousDiscrepancyRel.java]: ../relationships/protein/ProteinMiscellaneousDiscrepancyRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinOrganismRel.java]: ../relationships/protein/ProteinOrganismRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinPfamRel.java]: ../relationships/protein/ProteinPfamRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinProteinInteractionRel.java]: ../relationships/protein/ProteinProteinInteractionRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinReactomeRel.java]: ../relationships/protein/ProteinReactomeRel.java.md [main/java/com/bio4j/blueprints/model/relationships/protein/ProteinSubcellularLocationRel.java]: ../relationships/protein/ProteinSubcellularLocationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementCDSRel.java]: ../relationships/refseq/GenomeElementCDSRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementGeneRel.java]: ../relationships/refseq/GenomeElementGeneRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementMiscRnaRel.java]: ../relationships/refseq/GenomeElementMiscRnaRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementMRnaRel.java]: ../relationships/refseq/GenomeElementMRnaRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementNcRnaRel.java]: ../relationships/refseq/GenomeElementNcRnaRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementRRnaRel.java]: ../relationships/refseq/GenomeElementRRnaRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementTmRnaRel.java]: ../relationships/refseq/GenomeElementTmRnaRel.java.md [main/java/com/bio4j/blueprints/model/relationships/refseq/GenomeElementTRnaRel.java]: ../relationships/refseq/GenomeElementTRnaRel.java.md [main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousGeneModelPredictionRel.java]: ../relationships/sc/ErroneousGeneModelPredictionRel.java.md [main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousInitiationRel.java]: ../relationships/sc/ErroneousInitiationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousTerminationRel.java]: ../relationships/sc/ErroneousTerminationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/sc/ErroneousTranslationRel.java]: ../relationships/sc/ErroneousTranslationRel.java.md [main/java/com/bio4j/blueprints/model/relationships/sc/FrameshiftRel.java]: ../relationships/sc/FrameshiftRel.java.md [main/java/com/bio4j/blueprints/model/relationships/sc/MiscellaneousDiscrepancyRel.java]: ../relationships/sc/MiscellaneousDiscrepancyRel.java.md [main/java/com/bio4j/blueprints/model/relationships/SubcellularLocationParentRel.java]: ../relationships/SubcellularLocationParentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/TaxonParentRel.java]: ../relationships/TaxonParentRel.java.md [main/java/com/bio4j/blueprints/model/relationships/uniref/UniRef100MemberRel.java]: ../relationships/uniref/UniRef100MemberRel.java.md [main/java/com/bio4j/blueprints/model/relationships/uniref/UniRef50MemberRel.java]: ../relationships/uniref/UniRef50MemberRel.java.md [main/java/com/bio4j/blueprints/model/relationships/uniref/UniRef90MemberRel.java]: ../relationships/uniref/UniRef90MemberRel.java.md [main/java/com/bio4j/blueprints/model/Vertex.java]: ../Vertex.java.md [test/java/com/era7/bio4j-model.java]: ../../../../../../../test/java/com/era7/bio4j-model.java.md
bio4j/blueprints
docs/src/main/java/com/bio4j/blueprints/model/nodes/ConsortiumNode.java.md
Markdown
agpl-3.0
51,314
/* * #%L * Cantharella :: Data * $Id: CantharellaStemmer.java 269 2014-05-07 08:14:00Z echatellier $ * $HeadURL: https://svn.codelutin.com/cantharella/trunk/cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/CantharellaStemmer.java $ * %% * Copyright (C) 2012 - 2013 IRD (Institut de Recherche pour le Developpement) and by respective authors (see below) * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ package nc.ird.cantharella.data.model.search; import static org.apache.lucene.analysis.util.StemmerUtil.*; /** * Light Stemmer for French. * <p> * This stemmer implements the "UniNE" algorithm in: <i>Light Stemming Approaches for the French, Portuguese, German and * Hungarian Languages</i> Jacques Savoy */ public class CantharellaStemmer { /** * Stem a char sequence. * * @param s char sequence to stem * @param len char sequence length * @return char sequence final length */ public int stem(char s[], int len) { if (len > 5 && s[len - 1] == 'x') { if (s[len - 3] == 'a' && s[len - 2] == 'u' && s[len - 4] != 'e') s[len - 2] = 'l'; len--; } if (len > 3 && s[len - 1] == 'x') len--; if (len > 3 && s[len - 1] == 's') len--; if (len > 9 && endsWith(s, len, "issement")) { len -= 6; s[len - 1] = 'r'; return norm(s, len); } if (len > 8 && endsWith(s, len, "issant")) { len -= 4; s[len - 1] = 'r'; return norm(s, len); } if (len > 6 && endsWith(s, len, "ement")) { len -= 4; if (len > 3 && endsWith(s, len, "ive")) { len--; s[len - 1] = 'f'; } return norm(s, len); } if (len > 11 && endsWith(s, len, "ficatrice")) { len -= 5; s[len - 2] = 'e'; s[len - 1] = 'r'; return norm(s, len); } if (len > 10 && endsWith(s, len, "ficateur")) { len -= 4; s[len - 2] = 'e'; s[len - 1] = 'r'; return norm(s, len); } if (len > 9 && endsWith(s, len, "catrice")) { len -= 3; s[len - 4] = 'q'; s[len - 3] = 'u'; s[len - 2] = 'e'; //s[len-1] = 'r' <-- unnecessary, already 'r'. return norm(s, len); } if (len > 8 && endsWith(s, len, "cateur")) { len -= 2; s[len - 4] = 'q'; s[len - 3] = 'u'; s[len - 2] = 'e'; s[len - 1] = 'r'; return norm(s, len); } if (len > 8 && endsWith(s, len, "atrice")) { len -= 4; s[len - 2] = 'e'; s[len - 1] = 'r'; return norm(s, len); } if (len > 7 && endsWith(s, len, "ateur")) { len -= 3; s[len - 2] = 'e'; s[len - 1] = 'r'; return norm(s, len); } if (len > 6 && endsWith(s, len, "trice")) { len--; s[len - 3] = 'e'; s[len - 2] = 'u'; s[len - 1] = 'r'; } if (len > 5 && endsWith(s, len, "ième")) return norm(s, len - 4); if (len > 7 && endsWith(s, len, "teuse")) { len -= 2; s[len - 1] = 'r'; return norm(s, len); } if (len > 6 && endsWith(s, len, "teur")) { len--; s[len - 1] = 'r'; return norm(s, len); } if (len > 5 && endsWith(s, len, "euse")) return norm(s, len - 2); if (len > 8 && endsWith(s, len, "ère")) { len--; s[len - 2] = 'e'; return norm(s, len); } if (len > 7 && endsWith(s, len, "ive")) { len--; s[len - 1] = 'f'; return norm(s, len); } if (len > 4 && (endsWith(s, len, "folle") || endsWith(s, len, "molle"))) { len -= 2; s[len - 1] = 'u'; return norm(s, len); } if (len > 9 && endsWith(s, len, "nnelle")) return norm(s, len - 5); if (len > 9 && endsWith(s, len, "nnel")) return norm(s, len - 3); if (len > 4 && endsWith(s, len, "ète")) { len--; s[len - 2] = 'e'; } if (len > 8 && endsWith(s, len, "ique")) len -= 4; if (len > 8 && endsWith(s, len, "esse")) return norm(s, len - 3); if (len > 7 && endsWith(s, len, "inage")) return norm(s, len - 3); if (len > 9 && endsWith(s, len, "isation")) { len -= 7; if (len > 5 && endsWith(s, len, "ual")) s[len - 2] = 'e'; return norm(s, len); } if (len > 9 && endsWith(s, len, "isateur")) return norm(s, len - 7); if (len > 8 && endsWith(s, len, "ation")) return norm(s, len - 5); if (len > 8 && endsWith(s, len, "ition")) return norm(s, len - 5); return norm(s, len); } private int norm(char s[], int len) { if (len > 4) { for (int i = 0; i < len; i++) switch (s[i]) { case 'à': case 'á': case 'â': s[i] = 'a'; break; case 'ô': s[i] = 'o'; break; case 'è': case 'é': case 'ê': s[i] = 'e'; break; case 'ù': case 'û': s[i] = 'u'; break; case 'î': s[i] = 'i'; break; case 'ç': s[i] = 'c'; break; } /* XXX chatellier 20130516 disabled for cantharella because duplicated characters are usefull in some refs identifiers char ch = s[0]; for (int i = 1; i < len; i++) { if (s[i] == ch) len = delete(s, i--, len); else ch = s[i]; }*/ } if (len > 4 && endsWith(s, len, "ie")) len -= 2; if (len > 4) { if (s[len - 1] == 'r') len--; if (s[len - 1] == 'e') len--; if (s[len - 1] == 'e') len--; /* XXX chatellier 20130516 disabled for cantharella because duplicated characters are usefull in some refs identifiers if (s[len - 1] == s[len - 2]) len--;*/ } return len; } }
acheype/cantharella
cantharella.data/src/main/java/nc/ird/cantharella/data/model/search/CantharellaStemmer.java
Java
agpl-3.0
7,537
// Copyright (c) 2014, Suryandaru Triandana <syndtr@gmail.com> // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package table import ( "bytes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "gx/ipfs/QmbBhyDKsY4mbY6xsKt3qu9Y7FPvMJ6qbD8AMjYYvPRw1g/goleveldb/leveldb/iterator" "gx/ipfs/QmbBhyDKsY4mbY6xsKt3qu9Y7FPvMJ6qbD8AMjYYvPRw1g/goleveldb/leveldb/opt" "gx/ipfs/QmbBhyDKsY4mbY6xsKt3qu9Y7FPvMJ6qbD8AMjYYvPRw1g/goleveldb/leveldb/storage" "gx/ipfs/QmbBhyDKsY4mbY6xsKt3qu9Y7FPvMJ6qbD8AMjYYvPRw1g/goleveldb/leveldb/testutil" "gx/ipfs/QmbBhyDKsY4mbY6xsKt3qu9Y7FPvMJ6qbD8AMjYYvPRw1g/goleveldb/leveldb/util" ) type tableWrapper struct { *Reader } func (t tableWrapper) TestFind(key []byte) (rkey, rvalue []byte, err error) { return t.Reader.Find(key, false, nil) } func (t tableWrapper) TestGet(key []byte) (value []byte, err error) { return t.Reader.Get(key, nil) } func (t tableWrapper) TestNewIterator(slice *util.Range) iterator.Iterator { return t.Reader.NewIterator(slice, nil) } var _ = testutil.Defer(func() { Describe("Table", func() { Describe("approximate offset test", func() { var ( buf = &bytes.Buffer{} o = &opt.Options{ BlockSize: 1024, Compression: opt.NoCompression, } ) // Building the table. tw := NewWriter(buf, o) tw.Append([]byte("k01"), []byte("hello")) tw.Append([]byte("k02"), []byte("hello2")) tw.Append([]byte("k03"), bytes.Repeat([]byte{'x'}, 10000)) tw.Append([]byte("k04"), bytes.Repeat([]byte{'x'}, 200000)) tw.Append([]byte("k05"), bytes.Repeat([]byte{'x'}, 300000)) tw.Append([]byte("k06"), []byte("hello3")) tw.Append([]byte("k07"), bytes.Repeat([]byte{'x'}, 100000)) err := tw.Close() It("Should be able to approximate offset of a key correctly", func() { Expect(err).ShouldNot(HaveOccurred()) tr, err := NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()), storage.FileDesc{}, nil, nil, o) Expect(err).ShouldNot(HaveOccurred()) CheckOffset := func(key string, expect, threshold int) { offset, err := tr.OffsetOf([]byte(key)) Expect(err).ShouldNot(HaveOccurred()) Expect(offset).Should(BeNumerically("~", expect, threshold), "Offset of key %q", key) } CheckOffset("k0", 0, 0) CheckOffset("k01a", 0, 0) CheckOffset("k02", 0, 0) CheckOffset("k03", 0, 0) CheckOffset("k04", 10000, 1000) CheckOffset("k04a", 210000, 1000) CheckOffset("k05", 210000, 1000) CheckOffset("k06", 510000, 1000) CheckOffset("k07", 510000, 1000) CheckOffset("xyz", 610000, 2000) }) }) Describe("read test", func() { Build := func(kv testutil.KeyValue) testutil.DB { o := &opt.Options{ BlockSize: 512, BlockRestartInterval: 3, } buf := &bytes.Buffer{} // Building the table. tw := NewWriter(buf, o) kv.Iterate(func(i int, key, value []byte) { tw.Append(key, value) }) tw.Close() // Opening the table. tr, _ := NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()), storage.FileDesc{}, nil, nil, o) return tableWrapper{tr} } Test := func(kv *testutil.KeyValue, body func(r *Reader)) func() { return func() { db := Build(*kv) if body != nil { body(db.(tableWrapper).Reader) } testutil.KeyValueTesting(nil, *kv, db, nil, nil) } } testutil.AllKeyValueTesting(nil, Build, nil, nil) Describe("with one key per block", Test(testutil.KeyValue_Generate(nil, 9, 1, 10, 512, 512), func(r *Reader) { It("should have correct blocks number", func() { indexBlock, err := r.readBlock(r.indexBH, true) Expect(err).To(BeNil()) Expect(indexBlock.restartsLen).Should(Equal(9)) }) })) }) }) })
disorganizer/brig
vendor/gx/ipfs/QmbBhyDKsY4mbY6xsKt3qu9Y7FPvMJ6qbD8AMjYYvPRw1g/goleveldb/leveldb/table/table_test.go
GO
agpl-3.0
3,798
/* document_medium / dokumentmedium */ INSERT INTO document_medium (pk_document_medium_id, system_id, code, description, deleted, version) VALUES (1, '48e067ae-d794-4216-8a9d-7cb0ef03472c', 'Fysisk medium', 'Bare fysiske dokumenter', FALSE, 0); INSERT INTO document_medium (pk_document_medium_id, system_id, code, description, deleted, version) VALUES (2, '1b617405-9dd6-4187-bee6-81ed4f4a0e1f', 'Elektronisk arkiv', 'Bare elektroniske dokumenter', FALSE, 0); INSERT INTO document_medium (pk_document_medium_id, system_id, code, description, deleted, version) VALUES (3, '00d21eea-c231-4542-8e3a-964f441fbbd3', 'Blandet fysisk og elektronisk arkiv', 'Blanding av fysiske og elektroniske dokumenter ', FALSE, 0); /* fonds_status / arkivstatus */ INSERT INTO fonds_status (pk_fonds_status_id, system_id, code, description, deleted, version) VALUES (1, '9ed3f5d3-9934-446d-85b8-b2ada9498aa7', 'Opprettet', NULL, FALSE, 0); INSERT INTO fonds_status (pk_fonds_status_id, system_id, code, description, deleted, version) VALUES (2, 'b94eb9cf-e71f-4d68-964b-b68c7f9962b6', 'Avsluttet', NULL, FALSE, 0); /* series_status / arkivdelstatus*/ INSERT INTO series_status (pk_series_status_id, system_id, code, description, deleted, version) VALUES (1, '21dca458-5715-455b-baef-6c81c6e1e73a', 'A', 'Aktiv periode', FALSE, 0); INSERT INTO series_status (pk_series_status_id, system_id, code, description, deleted, version) VALUES (2, '24ee7d87-4e5e-46d8-ba9a-d236609fdeeb', 'O', 'Overlappingsperiode', FALSE, 0); INSERT INTO series_status (pk_series_status_id, system_id, code, description, deleted, version) VALUES (3, 'a67ae905-a556-4cf6-bfa9-43ad15836f61', 'P', 'Avsluttet periode', FALSE, 0); INSERT INTO series_status (pk_series_status_id, system_id, code, description, deleted, version) VALUES (4, '30bec9da-7299-4f50-9233-8a556cc5708c', 'U', 'Uaktuelle mapper', FALSE, 0); /* sign_off_method / avskrivningsmaate */ INSERT INTO sign_off_method (pk_sign_off_method_id, system_id, code, description, deleted, version) VALUES (1, '5ccea231-c2cc-4507-8a72-709c9c54bcd5', 'BU', 'Besvart med brev', FALSE, 0); INSERT INTO sign_off_method (pk_sign_off_method_id, system_id, code, description, deleted, version) VALUES (2, '3ea3d7c2-2479-46a4-b56d-8cc0c31208a7', 'BE', 'Besvart med e-post', FALSE, 0); INSERT INTO sign_off_method (pk_sign_off_method_id, system_id, code, description, deleted, version) VALUES (3, 'e549d858-f6d6-4d86-b811-014ade0ca6c6', 'TLF', 'Besvart på telefon', FALSE, 0); INSERT INTO sign_off_method (pk_sign_off_method_id, system_id, code, description, deleted, version) VALUES (4, 'ec14aac1-df6d-495a-bcf5-caa9a0c18bb8', 'TE', 'Tatt til etterretning', FALSE, 0); INSERT INTO sign_off_method (pk_sign_off_method_id, system_id, code, description, deleted, version) VALUES (5, 'c62c80d9-7700-4243-b2e1-fd14af9a9559', 'TO', 'Tatt til orientering', FALSE, 0); /* document_status / dokumentstatus */ INSERT INTO document_status (pk_document_status_id, system_id, code, description, deleted, version) VALUES (1, '553287bc-4592-4107-8567-0402458fdc4e', 'B', 'Dokumentet er under redigering', FALSE, 0); INSERT INTO document_status (pk_document_status_id, system_id, code, description, deleted, version) VALUES (2, '29ad0b9a-fe52-4e4b-af9a-1a4841f6ad43', 'F', 'Dokumentet er ferdigstilt', FALSE, 0); INSERT INTO document_type (pk_document_type_id, system_id, code, description, deleted, version) VALUES (1, '26ef04f8-5efb-4f19-9cde-d99a40d8cb1b', 'B', 'Brev', FALSE, 0); INSERT INTO document_type (pk_document_type_id, system_id, code, description, deleted, version) VALUES (2, 'e12f0bf6-aac4-4bb0-8f23-9847f0b67453', 'R', 'Rundskriv', FALSE, 0); INSERT INTO document_type (pk_document_type_id, system_id, code, description, deleted, version) VALUES (3, '1f4ec7b5-a717-433d-a3dc-d357e6579de0', 'F', 'Faktura', FALSE, 0); INSERT INTO document_type (pk_document_type_id, system_id, code, description, deleted, version) VALUES (3, '99281649-0d0c-402f-9494-7df99b7d73f1', 'O', 'Ordrebekreftelse', FALSE, 0); /* electronic_signature_security_level / elektronsiksignatursikkerhetsnivaa */ INSERT INTO electronic_signature_security_level ( pk_electronic_signature_security_level_id, system_id, code, description, deleted, version) VALUES (1, 'dc55f30f-a549-40ed-86e3-b3104cb1f7f5', 'SK', 'Symmetrisk kryptert', FALSE, 0); INSERT INTO electronic_signature_security_level ( pk_electronic_signature_security_level_id, system_id, code, description, deleted, version) VALUES (2, 'e1872a1e-4233-4a6e-884d-d8bdb3c48754', 'V', 'Sendt med PKI/virksomhetssertifikat', FALSE, 0); INSERT INTO electronic_signature_security_level ( pk_electronic_signature_security_level_id, system_id, code, description, deleted, version) VALUES (3, '2aa9657b-8498-4d33-8e41-0acf649a8d6d', 'PS', 'Sendt med PKI/"personstandard"-sertifikat', FALSE, 0); INSERT INTO electronic_signature_security_level ( pk_electronic_signature_security_level_id, system_id, code, description, deleted, version) VALUES (4, '558401c6-b99e-4adf-9576-811da4c7e461', 'PH', 'Sendt med PKI/"person høy"-sertifikat', FALSE, 0); /* electronic_signature_verified / elektronsiksignaturverifisert */ INSERT INTO electronic_signature_verified ( pk_electronic_signature_verified_id, system_id, code, description, deleted, version) VALUES (1, 'e8ff13ad-dba4-450b-92b7-f41da771b300', 'I', 'Signatur påført, ikke verifisert', FALSE, 0); INSERT INTO electronic_signature_verified ( pk_electronic_signature_verified_id, system_id, code, description, deleted, version) VALUES (2, 'f2006c7b-44f4-4a84-8c62-bbcc7f9ee608', 'V', 'Signatur påført og verifisert', FALSE, 0); /* flow_Status flytstatus */ INSERT INTO flow_status (pk_flow_status_id, system_id, code, description, deleted, version) VALUES (1, 'd854743a-8c5a-4791-b56c-a10fd240e768', 'G', 'Godkjent', FALSE, 0); INSERT INTO flow_status (pk_flow_status_id, system_id, code, description, deleted, version) VALUES (2, '949ad9cf-59ff-492e-9ce5-8a3bdced9cc9', 'I', 'Ikke godkjent', FALSE, 0); INSERT INTO flow_status (pk_flow_status_id, system_id, code, description, deleted, version) VALUES (3, '8a802fc2-7d9c-43ae-babd-72cc19d47a46', 'S', 'Sendt tilbake til saksbehandler med kommentarer', FALSE, 0); /* format / format */ INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (1, '93ac2b0f-1729-4c78-a917-a0f494a035ca', 'RA-TEKST', 'Ren tekst', FALSE, 0); INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (2, 'ba4c8c2c-4072-4fa7-b194-8812ea38697f', 'RA-TIFF6', 'TIFF versjon 6', FALSE, 0); INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (3, 'eb53170a-14b1-48e2-a5c4-965fef380ca6', 'RA-PDF', 'PDF/A - ISO 19005-1:2005', FALSE, 0); INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (4, '3d2c0bad-c8e3-4f03-b52e-d99867d53230', 'RA-XML', 'XML', FALSE, 0); INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (5, '18468b06-b491-4029-9e6f-395ad1d27b03', 'RA-JPEG', 'JPEG', FALSE, 0); INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (6, 'd5063523-83a2-4e51-b8aa-925385849e33', 'RA-SOSI', 'SOSI', FALSE, 0); INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (7, '9ae48e86-3c9e-47fd-bbf2-4d9f67b7de85', 'RA-MPEG-2', 'MPEG-2', FALSE, 0); INSERT INTO format (pk_format_id, system_id, code, description, deleted, version) VALUES (8, '7412833e-ceaf-40fd-95b5-e634f4640f99', 'RA-MP3', 'MP3', FALSE, 0); /* correspondence_part_type korrespondanseparttype */ INSERT INTO correspondence_part_type ( pk_correspondence_part_type_id, system_id, code, description, deleted, version) VALUES (1, '5b4588a3-7e4d-43ae-a3a8-4033e52944c0', 'EA', 'Avsender', FALSE, 0); INSERT INTO correspondence_part_type ( pk_correspondence_part_type_id, system_id, code, description, deleted, version) VALUES (2, 'c4a2097c-8cd1-496f-9cf5-bd16de1d85fe', 'EM', 'Mottaker', FALSE, 0); INSERT INTO correspondence_part_type ( pk_correspondence_part_type_id, system_id, code, description, deleted, version) VALUES (3, '6c2ace2f-05b5-45c0-96da-cff41cc5b2e7', 'EK', 'Kopimottaker', FALSE, 0); INSERT INTO correspondence_part_type ( pk_correspondence_part_type_id, system_id, code, description, deleted, version) VALUES (4, 'dcb06157-c8d3-4b43-a065-5cc21e80fbf6', 'GM', 'Gruppemottaker', FALSE, 0); INSERT INTO correspondence_part_type ( pk_correspondence_part_type_id, system_id, code, description, deleted, version) VALUES (5, '896d5f6c-2093-492d-a531-7dd845d45808', 'IA', 'Intern avsender', FALSE, 0); INSERT INTO correspondence_part_type ( pk_correspondence_part_type_id, system_id, code, description, deleted, version) VALUES (6, '77e1fbc4-e480-4e41-a97e-f429b816629e', 'IM', 'Intern mottaker', FALSE, 0); INSERT INTO correspondence_part_type ( pk_correspondence_part_type_id, system_id, code, description, deleted, version) VALUES (7, '78e59b26-819c-4cf7-abe1-69fb6e457bcb', 'IK', 'Intern kopimottaker', FALSE, 0); /* registry_entry_status journalpoststatus */ INSERT INTO registry_entry_status ( pk_registry_entry_status_id, system_id, code, description, deleted, version) VALUES (1, '0b4cfcb9-e979-4cdd-94d3-1660172976a4', 'J', 'Journalført', FALSE, 0); INSERT INTO registry_entry_status ( pk_registry_entry_status_id, system_id, code, description, deleted, version) VALUES (2, '2f140067-8239-4ea3-88a3-c42380ec3885', 'F', 'Ferdigstilt fra saksbehandler', FALSE, 0); INSERT INTO registry_entry_status ( pk_registry_entry_status_id, system_id, code, description, deleted, version) VALUES (3, '218deb74-f9e0-48e2-a523-3f47a6a44aba', 'G', 'Godkjent av leder', FALSE, 0); INSERT INTO registry_entry_status ( pk_registry_entry_status_id, system_id, code, description, deleted, version) VALUES (4, '35940d96-e531-4e5b-8f0a-63f8c7d08cb0', 'E', 'Ekspedert', FALSE, 0); INSERT INTO registry_entry_status ( pk_registry_entry_status_id, system_id, code, description, deleted, version) VALUES (5, '74aef294-f3d1-4e77-a3c1-abcb45a7eeea', 'A', 'Arkivert', FALSE, 0); INSERT INTO registry_entry_status ( pk_registry_entry_status_id, system_id, code, description, deleted, version) VALUES (6, '8bc27628-f722-41c5-9ce9-4f46fc54bf34', 'U', 'Utgår', FALSE, 0); INSERT INTO registry_entry_status ( pk_registry_entry_status_id, system_id, code, description, deleted, version) VALUES (7, '395ff299-e60d-4550-979e-5b682d8e4f61', 'M', 'Midlertidig registrering av', FALSE, 0); /* registry_entry_type journalposttype */ INSERT INTO registry_entry_type ( pk_registry_entry_type_id, system_id, code, description, deleted, version) VALUES (1, '4827e5e0-0fae-4b9e-a01d-88ce00e8c62e', 'I', 'Inngående dokument', FALSE, 0); INSERT INTO registry_entry_type ( pk_registry_entry_type_id, system_id, code, description, deleted, version) VALUES (2, 'f87a8b7f-bb31-4dea-98c6-13e1ac17e24f', 'U', 'Utgående dokument', FALSE, 0); INSERT INTO registry_entry_type ( pk_registry_entry_type_id, system_id, code, description, deleted, version) VALUES (3, '001f176e-d68a-42f4-95f8-555a72c1a748', 'N', 'Organinternt dokument for oppfølging', FALSE, 0); INSERT INTO registry_entry_type ( pk_registry_entry_type_id, system_id, code, description, deleted, version) VALUES (4, '2014243a-5d33-4fd3-98af-eda7ddd4cdc8', 'X', 'Organinternt dokument uten oppfølging', FALSE, 0); INSERT INTO registry_entry_type ( pk_registry_entry_type_id, system_id, code, description, deleted, version) VALUES (5, '07c06822-50e8-47fb-a760-eaff70eaa64e', 'S', 'Saksframlegg', FALSE, 0); /* precedence_status / presedensstatus */ INSERT INTO precedence_status ( pk_precedence_status_id, system_id, code, description, deleted, version) VALUES (1, 'f2c39e2e-8353-49ca-91a1-6ae48c658cd1', 'G', 'Gjeldende', FALSE, 0); INSERT INTO precedence_status ( pk_precedence_status_id, system_id, code, description, deleted, version) VALUES (2, 'cacc4170-6149-4d65-8811-7ca5855e089b', 'F', 'Foreldet', FALSE, 0); /* case_party_role / sakspartrolle */ INSERT INTO case_party_role ( pk_case_party_role_id, system_id, code, description, deleted, version) VALUES (1, '391e6756-1885-4ef9-b2cb-226a7bbcd381', 'KLI', 'Klient', FALSE, 0); INSERT INTO case_party_role ( pk_case_party_role_id, system_id, code, description, deleted, version) VALUES (2, '882ada83-04ca-4a24-81ba-5572d653804d', 'PÅ', 'Pårørende', FALSE, 0); INSERT INTO case_party_role ( pk_case_party_role_id, system_id, code, description, deleted, version) VALUES (3, 'b49e85df-1512-4ad4-8ca9-5fe712bb16f7', 'FORM', 'Formynder', FALSE, 0); INSERT INTO case_party_role ( pk_case_party_role_id, system_id, code, description, deleted, version) VALUES (4, 'cd0373f5-01c3-4586-b9b7-9280b3e579b9', 'ADV', 'Advokat', FALSE, 0); /* file_type / mappetype Note. This is an open code list in the standard. I have added the following values based on common sense. */ INSERT INTO file_type ( pk_file_type_id, system_id, code, description, deleted, version) VALUES (1, '2a14a47d-4bbc-4d0d-b3e7-267b105ec539', 'SKM', 'Saksmappe', FALSE, 0); INSERT INTO file_type ( pk_file_type_id, system_id, code, description, deleted, version) VALUES (2, '84766390-8799-4e7d-96ab-1e5f26596804', 'PLM', 'Personalmappe', FALSE, 0); INSERT INTO file_type ( pk_file_type_id, system_id, code, description, deleted, version) VALUES (3, 'b027b486-9b42-48a0-88e3-c2a6ddc91589', 'BYM', 'Byggemappe', FALSE, 0); INSERT INTO file_type ( pk_file_type_id, system_id, code, description, deleted, version) VALUES (4, '1b8c9632-b5d1-49a1-a0ec-2ec2ee3e7483', 'MOM', 'Møtemappe', FALSE, 0); /* comment / merknad Note. This is an open code list in the standard. The following values are taken from the Noark 4 standard */ INSERT INTO comment_type ( pk_comment_type_id, system_id, code, description, deleted, version) VALUES (1, 'bf105de3-7eb7-4abc-b836-b89180df462c', 'MS', 'Merknad fra saksbehandler', FALSE, 0); INSERT INTO comment_type ( pk_comment_type_id, system_id, code, description, deleted, version) VALUES (2, 'c7d484ab-fb3c-4da5-b475-f39c085086e0', 'ML', 'Merknad fra leder', FALSE, 0); INSERT INTO comment_type ( pk_comment_type_id, system_id, code, description, deleted, version) VALUES (3, '7c1b04df-26b6-4a91-a949-3cb1717bd901', 'MA', 'Merknad fra arkivansvarlig', FALSE, 0); /* classification_type / klassifikasjonstype */ INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (1, 'd10dddcd-74c0-430a-8b03-32b489fb6900', 'GBN', 'Gårds- og bruksnummer Valgfri', FALSE, 0); INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (2, '0a101af4-ce12-47b2-9c48-6c7d9b72a260', 'FH', 'Funksjonsbasert, hierarkisk Valgfri', FALSE, 0); INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (3, 'cf999e08-d4ee-4afe-9d85-604c56fb4e0c', 'EH', 'Emnebasert, hierarkisk arkivnøkkel', FALSE, 0); INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (4, '50efdb25-bc8d-4ed8-abfc-3e12f6d314a1', 'E1', 'Emnebasert, ett nivå', FALSE, 0); INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (5, '2577e645-0207-4f12-8a58-8bc4dda2e7f6', 'KK', 'K-koder', FALSE, 0); INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (6, 'f32705c8-6572-4fd8-b9f0-96adc69202e2', 'MF', 'Mangefasettert, ikke hierarki', FALSE, 0); INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (7, 'b8b8982f-4464-4d9a-9103-e0682f353722', 'UO', 'Objektbasert', FALSE, 0); INSERT INTO classification_type ( pk_classification_type_id, system_id, code, description, deleted, version) VALUES (8, '9f8b839e-35c5-4382-a774-3f42f00e75a4', 'PNR', 'Fødselsnummer', FALSE, 0); /* variant_format / variantformat */ INSERT INTO variant_format ( pk_variant_format_id, system_id, code, description, deleted, version) VALUES (1, '04c49db4-5a6f-47a9-a763-d7d3d6fee2a2', 'P', 'Produksjonsformat', FALSE, 0); INSERT INTO variant_format ( pk_variant_format_id, system_id, code, description, deleted, version) VALUES (2, '0998cf74-d352-4aca-b8d7-ce6deba18ea4', 'A', 'Arkivformat', FALSE, 0); INSERT INTO variant_format ( pk_variant_format_id, system_id, code, description, deleted, version) VALUES (3, '3a89bb13-e796-4f44-a2ee-509fbbbef0aa', 'O', 'Dokument hvor deler av innholdet er skjermet', FALSE, 0); /* case_status / saksstatus*/ INSERT INTO case_status ( pk_case_status_id, system_id, code, description, deleted, version) VALUES (1, '33f1e0f1-ba44-4c9b-9493-28998c4f9fe4', 'B', 'Under behandling', FALSE, 0); INSERT INTO case_status ( pk_case_status_id, system_id, code, description, deleted, version) VALUES (2, '985a4607-0a24-4427-91e0-95438d6a2529', 'A', 'Avsluttet', FALSE, 0); INSERT INTO case_status ( pk_case_status_id, system_id, code, description, deleted, version) VALUES (3, '51f2d7c2-8146-4735-94c2-543d3cc17263', 'U', 'Utgår', FALSE, 0); INSERT INTO case_status ( pk_case_status_id, system_id, code, description, deleted, version) VALUES (4, 'a23b0a12-5e02-4edf-b75b-896a7744d7ca', 'R', 'Opprettet av saksbehandler', FALSE, 0); INSERT INTO case_status ( pk_case_status_id, system_id, code, description, deleted, version) VALUES (5, '0c9e8e57-1a5a-4c11-9f1b-5d646b6a683f', 'S', 'Avsluttet av saksbehandler', FALSE, 0); INSERT INTO case_status ( pk_case_status_id, system_id, code, description, deleted, version) VALUES (6, 'd26041b1-50cd-4a8b-9431-0833dfaa45d3', 'P', 'Unntatt prosesstyring', FALSE, 0); INSERT INTO case_status ( pk_case_status_id, system_id, code, description, deleted, version) VALUES (7, '6cc5cca6-8ae5-4a6d-a7d6-9383067a38a1', 'F', 'Ferdig fra saksbehandler', FALSE, 0); /* screening_document / skjermingdokument*/ INSERT INTO screening_document ( pk_screening_document_id, system_id, code, description, deleted, version) VALUES (1, 'bef2f7ea-c0ec-4e66-8344-79c47f08a83d', 'H', 'Skjerming av hele dokumentet', FALSE, 0); INSERT INTO screening_document ( pk_screening_document_id, system_id, code, description, deleted, version) VALUES (2, 'ebb87206-7bc9-45c4-8903-bff19f7f814e', 'D', 'Skjerming av deler av dokumentet', FALSE, 0); /* screening_metadata / skjermingmetadata*/ INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (1, 'd09621ac-3ae7-470b-93c5-c02f22c52124', 'KID', 'Skjerming klasseID', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (2, 'faff8507-edf9-464f-b539-080c3504e4bb', 'TKL', 'Skjerming tittel klasse', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (3, '3d24337c-e7d0-4b42-a153-115c59e0ec75', 'TM1', 'Skjerming tittel mappe - unntatt første linje', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (4, 'a524d3bd-8da0-423d-acb2-e2870d959724', 'TMO', 'Skjerming tittel mappe - utvalgte ord', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (5, 'f9a1cd40-2175-44ac-8262-bae0c3543e04', 'NPS', 'Skjerming navn part i sak', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (6, 'a0c2a727-dbd6-4197-b928-82698eeadbeb', 'TR1', 'Skjerming tittel registrering - unntatt første linje', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (7, '2197150e-0566-42a6-9838-687605e40b9b', 'TRO', 'Skjerming tittel registrering - utvalgte ord', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (8, 'f5d9452b-2acb-40e6-84bd-422796f01008', 'NA', 'Skjerming navn avsender', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (9, '0c688727-5b5d-4f59-be91-58850a869e9f', 'NM', 'Skjerming navn mottaker', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (10, 'b720d937-e512-49a8-a02e-a540ed57f72e', 'TD', 'Skjerming tittel dokumentbeskrivelse', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (11, '06706ffe-acd9-46c6-a67f-0a8733b2de06', 'MT', 'Skjerming merknadstekst', FALSE, 0); INSERT INTO screening_metadata ( pk_screening_metadata_id, system_id, code, description, deleted, version) VALUES (12, '2f68901a-a60a-4212-8b6a-7505c02d7104', 'M', 'Midlertidig skjerming', FALSE, 0);
HiOA-ABI/nikita-noark5-core
src/main/resources/db/noark5_metadata_values.sql
SQL
agpl-3.0
22,832
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.gxt.core.shared.dto.propertyAccessors; import com.ephesoft.gxt.core.shared.dto.ImportBatchClassSuperConfig; import com.sencha.gxt.core.client.ValueProvider; import com.sencha.gxt.data.shared.ModelKeyProvider; import com.sencha.gxt.data.shared.PropertyAccess; /** * This interface provides Property Accessors for {@link ImportBatchClassSuperConfig} * * @author Ephesoft * @version 1.0 * */ public interface ImportBatchClassSuperConfigProperties extends PropertyAccess<ImportBatchClassSuperConfig> { ModelKeyProvider<ImportBatchClassSuperConfig> identifier(); ValueProvider<ImportBatchClassSuperConfig, String> serverURL(); ValueProvider<ImportBatchClassSuperConfig, String> userName(); ValueProvider<ImportBatchClassSuperConfig, String> password(); ValueProvider<ImportBatchClassSuperConfig, String> repositoryID(); ValueProvider<ImportBatchClassSuperConfig, String> fileExtension(); ValueProvider<ImportBatchClassSuperConfig, String> folderName(); ValueProvider<ImportBatchClassSuperConfig, String> cmisProperty(); ValueProvider<ImportBatchClassSuperConfig, String> value(); ValueProvider<ImportBatchClassSuperConfig, String> valueToUpdate(); ValueProvider<ImportBatchClassSuperConfig, Boolean> isDeleted(); ValueProvider<ImportBatchClassSuperConfig, Boolean> isNew(); }
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-core/src/main/java/com/ephesoft/gxt/core/shared/dto/propertyAccessors/ImportBatchClassSuperConfigProperties.java
Java
agpl-3.0
3,301
// Copyright 2011, 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package ec2_test import ( "fmt" "net" "regexp" "sort" "strings" "github.com/juju/errors" jc "github.com/juju/testing/checkers" "github.com/juju/utils" "github.com/juju/utils/set" "gopkg.in/amz.v3/aws" amzec2 "gopkg.in/amz.v3/ec2" "gopkg.in/amz.v3/ec2/ec2test" "gopkg.in/amz.v3/s3/s3test" gc "gopkg.in/check.v1" goyaml "gopkg.in/yaml.v1" "github.com/juju/juju/constraints" "github.com/juju/juju/environs" "github.com/juju/juju/environs/bootstrap" "github.com/juju/juju/environs/config" "github.com/juju/juju/environs/configstore" "github.com/juju/juju/environs/imagemetadata" "github.com/juju/juju/environs/jujutest" "github.com/juju/juju/environs/simplestreams" envtesting "github.com/juju/juju/environs/testing" "github.com/juju/juju/environs/tools" "github.com/juju/juju/feature" "github.com/juju/juju/instance" "github.com/juju/juju/juju/arch" "github.com/juju/juju/juju/testing" "github.com/juju/juju/network" "github.com/juju/juju/provider/common" "github.com/juju/juju/provider/ec2" coretesting "github.com/juju/juju/testing" "github.com/juju/juju/utils/ssh" "github.com/juju/juju/version" ) type ProviderSuite struct { coretesting.BaseSuite } var _ = gc.Suite(&ProviderSuite{}) var localConfigAttrs = coretesting.FakeConfig().Merge(coretesting.Attrs{ "name": "sample", "type": "ec2", "region": "test", "control-bucket": "test-bucket", "access-key": "x", "secret-key": "x", "agent-version": version.Current.Number.String(), }) func registerLocalTests() { // N.B. Make sure the region we use here // has entries in the images/query txt files. aws.Regions["test"] = aws.Region{ Name: "test", } gc.Suite(&localServerSuite{}) gc.Suite(&localLiveSuite{}) gc.Suite(&localNonUSEastSuite{}) } // localLiveSuite runs tests from LiveTests using a fake // EC2 server that runs within the test process itself. type localLiveSuite struct { LiveTests srv localServer restoreEC2Patching func() } func (t *localLiveSuite) SetUpSuite(c *gc.C) { // Upload arches that ec2 supports; add to this // as ec2 coverage expands. t.UploadArches = []string{arch.AMD64, arch.I386} t.TestConfig = localConfigAttrs t.restoreEC2Patching = patchEC2ForTesting() t.srv.startServer(c) t.LiveTests.SetUpSuite(c) } func (t *localLiveSuite) TearDownSuite(c *gc.C) { t.LiveTests.TearDownSuite(c) t.srv.stopServer(c) t.restoreEC2Patching() } // localServer represents a fake EC2 server running within // the test process itself. type localServer struct { ec2srv *ec2test.Server s3srv *s3test.Server config *s3test.Config } func (srv *localServer) startServer(c *gc.C) { var err error srv.ec2srv, err = ec2test.NewServer() if err != nil { c.Fatalf("cannot start ec2 test server: %v", err) } srv.s3srv, err = s3test.NewServer(srv.config) if err != nil { c.Fatalf("cannot start s3 test server: %v", err) } aws.Regions["test"] = aws.Region{ Name: "test", EC2Endpoint: srv.ec2srv.URL(), S3Endpoint: srv.s3srv.URL(), S3LocationConstraint: true, } srv.addSpice(c) zones := make([]amzec2.AvailabilityZoneInfo, 3) zones[0].Region = "test" zones[0].Name = "test-available" zones[0].State = "available" zones[1].Region = "test" zones[1].Name = "test-impaired" zones[1].State = "impaired" zones[2].Region = "test" zones[2].Name = "test-unavailable" zones[2].State = "unavailable" srv.ec2srv.SetAvailabilityZones(zones) } // addSpice adds some "spice" to the local server // by adding state that may cause tests to fail. func (srv *localServer) addSpice(c *gc.C) { states := []amzec2.InstanceState{ ec2test.ShuttingDown, ec2test.Terminated, ec2test.Stopped, } for _, state := range states { srv.ec2srv.NewInstances(1, "m1.small", "ami-a7f539ce", state, nil) } } func (srv *localServer) stopServer(c *gc.C) { srv.ec2srv.Quit() srv.s3srv.Quit() // Clear out the region because the server address is // no longer valid. delete(aws.Regions, "test") } // localServerSuite contains tests that run against a fake EC2 server // running within the test process itself. These tests can test things that // would be unreasonably slow or expensive to test on a live Amazon server. // It starts a new local ec2test server for each test. The server is // accessed by using the "test" region, which is changed to point to the // network address of the local server. type localServerSuite struct { coretesting.BaseSuite jujutest.Tests srv localServer restoreEC2Patching func() } func (t *localServerSuite) SetUpSuite(c *gc.C) { // Upload arches that ec2 supports; add to this // as ec2 coverage expands. t.UploadArches = []string{arch.AMD64, arch.I386} t.TestConfig = localConfigAttrs t.restoreEC2Patching = patchEC2ForTesting() t.BaseSuite.SetUpSuite(c) } func (t *localServerSuite) TearDownSuite(c *gc.C) { t.BaseSuite.TearDownSuite(c) t.restoreEC2Patching() } func (t *localServerSuite) SetUpTest(c *gc.C) { t.BaseSuite.SetUpTest(c) t.SetFeatureFlags(feature.AddressAllocation) t.srv.startServer(c) t.Tests.SetUpTest(c) t.PatchValue(&version.Current, version.Binary{ Number: version.Current.Number, Series: coretesting.FakeDefaultSeries, Arch: arch.AMD64, }) } func (t *localServerSuite) TearDownTest(c *gc.C) { t.Tests.TearDownTest(c) t.srv.stopServer(c) t.BaseSuite.TearDownTest(c) } func (t *localServerSuite) prepareEnviron(c *gc.C) environs.NetworkingEnviron { env := t.Prepare(c) netenv, supported := environs.SupportsNetworking(env) c.Assert(supported, jc.IsTrue) return netenv } func (t *localServerSuite) TestBootstrapInstanceUserDataAndState(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) // check that StateServerInstances returns the id of the bootstrap machine. instanceIds, err := env.StateServerInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(instanceIds, gc.HasLen, 1) insts, err := env.AllInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(insts, gc.HasLen, 1) c.Check(insts[0].Id(), gc.Equals, instanceIds[0]) // check that the user data is configured to start zookeeper // and the machine and provisioning agents. // check that the user data is configured to only configure // authorized SSH keys and set the log output; everything // else happens after the machine is brought up. inst := t.srv.ec2srv.Instance(string(insts[0].Id())) c.Assert(inst, gc.NotNil) addresses, err := insts[0].Addresses() c.Assert(err, jc.ErrorIsNil) c.Assert(addresses, gc.Not(gc.HasLen), 0) userData, err := utils.Gunzip(inst.UserData) c.Assert(err, jc.ErrorIsNil) c.Logf("first instance: UserData: %q", userData) var userDataMap map[interface{}]interface{} err = goyaml.Unmarshal(userData, &userDataMap) c.Assert(err, jc.ErrorIsNil) c.Assert(userDataMap, jc.DeepEquals, map[interface{}]interface{}{ "output": map[interface{}]interface{}{ "all": "| tee -a /var/log/cloud-init-output.log", }, "ssh_authorized_keys": splitAuthKeys(env.Config().AuthorizedKeys()), "runcmd": []interface{}{ "set -xe", "install -D -m 644 /dev/null '/var/lib/juju/nonce.txt'", "printf '%s\\n' 'user-admin:bootstrap' > '/var/lib/juju/nonce.txt'", }, }) // check that a new instance will be started with a machine agent inst1, hc := testing.AssertStartInstance(c, env, "1") c.Check(*hc.Arch, gc.Equals, "amd64") c.Check(*hc.Mem, gc.Equals, uint64(1740)) c.Check(*hc.CpuCores, gc.Equals, uint64(1)) c.Assert(*hc.CpuPower, gc.Equals, uint64(100)) inst = t.srv.ec2srv.Instance(string(inst1.Id())) c.Assert(inst, gc.NotNil) userData, err = utils.Gunzip(inst.UserData) c.Assert(err, jc.ErrorIsNil) c.Logf("second instance: UserData: %q", userData) userDataMap = nil err = goyaml.Unmarshal(userData, &userDataMap) c.Assert(err, jc.ErrorIsNil) CheckPackage(c, userDataMap, "curl", true) CheckPackage(c, userDataMap, "mongodb-server", false) CheckScripts(c, userDataMap, "jujud bootstrap-state", false) CheckScripts(c, userDataMap, "/var/lib/juju/agents/machine-1/agent.conf", true) // TODO check for provisioning agent err = env.Destroy() c.Assert(err, jc.ErrorIsNil) _, err = env.StateServerInstances() c.Assert(err, gc.Equals, environs.ErrNotBootstrapped) } // splitAuthKeys splits the given authorized keys // into the form expected to be found in the // user data. func splitAuthKeys(keys string) []interface{} { slines := strings.FieldsFunc(keys, func(r rune) bool { return r == '\n' }) var lines []interface{} for _, line := range slines { lines = append(lines, ssh.EnsureJujuComment(strings.TrimSpace(line))) } return lines } func (t *localServerSuite) TestInstanceStatus(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) t.srv.ec2srv.SetInitialInstanceState(ec2test.Terminated) inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(err, jc.ErrorIsNil) c.Assert(inst.Status(), gc.Equals, "terminated") } func (t *localServerSuite) TestStartInstanceHardwareCharacteristics(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) _, hc := testing.AssertStartInstance(c, env, "1") c.Check(*hc.Arch, gc.Equals, "amd64") c.Check(*hc.Mem, gc.Equals, uint64(1740)) c.Check(*hc.CpuCores, gc.Equals, uint64(1)) c.Assert(*hc.CpuPower, gc.Equals, uint64(100)) } func (t *localServerSuite) TestStartInstanceAvailZone(c *gc.C) { inst, err := t.testStartInstanceAvailZone(c, "test-available") c.Assert(err, jc.ErrorIsNil) c.Assert(ec2.InstanceEC2(inst).AvailZone, gc.Equals, "test-available") } func (t *localServerSuite) TestStartInstanceAvailZoneImpaired(c *gc.C) { _, err := t.testStartInstanceAvailZone(c, "test-impaired") c.Assert(err, gc.ErrorMatches, `availability zone "test-impaired" is impaired`) } func (t *localServerSuite) TestStartInstanceAvailZoneUnknown(c *gc.C) { _, err := t.testStartInstanceAvailZone(c, "test-unknown") c.Assert(err, gc.ErrorMatches, `invalid availability zone "test-unknown"`) } func (t *localServerSuite) testStartInstanceAvailZone(c *gc.C, zone string) (instance.Instance, error) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) params := environs.StartInstanceParams{Placement: "zone=" + zone} result, err := testing.StartInstanceWithParams(env, "1", params, nil) if err != nil { return nil, err } return result.Instance, nil } func (t *localServerSuite) TestGetAvailabilityZones(c *gc.C) { var resultZones []amzec2.AvailabilityZoneInfo var resultErr error t.PatchValue(ec2.EC2AvailabilityZones, func(e *amzec2.EC2, f *amzec2.Filter) (*amzec2.AvailabilityZonesResp, error) { resp := &amzec2.AvailabilityZonesResp{ Zones: append([]amzec2.AvailabilityZoneInfo{}, resultZones...), } return resp, resultErr }) env := t.Prepare(c).(common.ZonedEnviron) resultErr = fmt.Errorf("failed to get availability zones") zones, err := env.AvailabilityZones() c.Assert(err, gc.Equals, resultErr) c.Assert(zones, gc.IsNil) resultErr = nil resultZones = make([]amzec2.AvailabilityZoneInfo, 1) resultZones[0].Name = "whatever" zones, err = env.AvailabilityZones() c.Assert(err, jc.ErrorIsNil) c.Assert(zones, gc.HasLen, 1) c.Assert(zones[0].Name(), gc.Equals, "whatever") // A successful result is cached, currently for the lifetime // of the Environ. This will change if/when we have long-lived // Environs to cut down repeated IaaS requests. resultErr = fmt.Errorf("failed to get availability zones") resultZones[0].Name = "andever" zones, err = env.AvailabilityZones() c.Assert(err, jc.ErrorIsNil) c.Assert(zones, gc.HasLen, 1) c.Assert(zones[0].Name(), gc.Equals, "whatever") } func (t *localServerSuite) TestGetAvailabilityZonesCommon(c *gc.C) { var resultZones []amzec2.AvailabilityZoneInfo t.PatchValue(ec2.EC2AvailabilityZones, func(e *amzec2.EC2, f *amzec2.Filter) (*amzec2.AvailabilityZonesResp, error) { resp := &amzec2.AvailabilityZonesResp{ Zones: append([]amzec2.AvailabilityZoneInfo{}, resultZones...), } return resp, nil }) env := t.Prepare(c).(common.ZonedEnviron) resultZones = make([]amzec2.AvailabilityZoneInfo, 2) resultZones[0].Name = "az1" resultZones[1].Name = "az2" resultZones[0].State = "available" resultZones[1].State = "impaired" zones, err := env.AvailabilityZones() c.Assert(err, jc.ErrorIsNil) c.Assert(zones, gc.HasLen, 2) c.Assert(zones[0].Name(), gc.Equals, resultZones[0].Name) c.Assert(zones[1].Name(), gc.Equals, resultZones[1].Name) c.Assert(zones[0].Available(), jc.IsTrue) c.Assert(zones[1].Available(), jc.IsFalse) } type mockAvailabilityZoneAllocations struct { group []instance.Id // input param result []common.AvailabilityZoneInstances err error } func (t *mockAvailabilityZoneAllocations) AvailabilityZoneAllocations( e common.ZonedEnviron, group []instance.Id, ) ([]common.AvailabilityZoneInstances, error) { t.group = group return t.result, t.err } func (t *localServerSuite) TestStartInstanceDistributionParams(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ result: []common.AvailabilityZoneInstances{{ZoneName: "az1"}}, } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) // no distribution group specified testing.AssertStartInstance(c, env, "1") c.Assert(mock.group, gc.HasLen, 0) // distribution group specified: ensure it's passed through to AvailabilityZone. expectedInstances := []instance.Id{"i-0", "i-1"} params := environs.StartInstanceParams{ DistributionGroup: func() ([]instance.Id, error) { return expectedInstances, nil }, } _, err = testing.StartInstanceWithParams(env, "1", params, nil) c.Assert(err, jc.ErrorIsNil) c.Assert(mock.group, gc.DeepEquals, expectedInstances) } func (t *localServerSuite) TestStartInstanceDistributionErrors(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ err: fmt.Errorf("AvailabilityZoneAllocations failed"), } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) _, _, _, err = testing.StartInstance(env, "1") c.Assert(errors.Cause(err), gc.Equals, mock.err) mock.err = nil dgErr := fmt.Errorf("DistributionGroup failed") params := environs.StartInstanceParams{ DistributionGroup: func() ([]instance.Id, error) { return nil, dgErr }, } _, err = testing.StartInstanceWithParams(env, "1", params, nil) c.Assert(errors.Cause(err), gc.Equals, dgErr) } func (t *localServerSuite) TestStartInstanceDistribution(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) // test-available is the only available AZ, so AvailabilityZoneAllocations // is guaranteed to return that. inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(ec2.InstanceEC2(inst).AvailZone, gc.Equals, "test-available") } var azConstrainedErr = &amzec2.Error{ Code: "Unsupported", Message: "The requested Availability Zone is currently constrained etc.", } var azVolumeTypeNotAvailableInZoneErr = &amzec2.Error{ Code: "VolumeTypeNotAvailableInZone", Message: "blah blah", } var azInsufficientInstanceCapacityErr = &amzec2.Error{ Code: "InsufficientInstanceCapacity", Message: "We currently do not have sufficient m1.small capacity in the " + "Availability Zone you requested (us-east-1d). Our system will " + "be working on provisioning additional capacity. You can currently get m1.small " + "capacity by not specifying an Availability Zone in your request or choosing " + "us-east-1c, us-east-1a.", } var azNoDefaultSubnetErr = &amzec2.Error{ Code: "InvalidInput", Message: "No default subnet for availability zone: ''us-east-1e''.", } func (t *localServerSuite) TestStartInstanceAvailZoneAllConstrained(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azConstrainedErr) } func (t *localServerSuite) TestStartInstanceVolumeTypeNotAvailable(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azVolumeTypeNotAvailableInZoneErr) } func (t *localServerSuite) TestStartInstanceAvailZoneAllInsufficientInstanceCapacity(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azInsufficientInstanceCapacityErr) } func (t *localServerSuite) TestStartInstanceAvailZoneAllNoDefaultSubnet(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azNoDefaultSubnetErr) } func (t *localServerSuite) testStartInstanceAvailZoneAllConstrained(c *gc.C, runInstancesError *amzec2.Error) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ result: []common.AvailabilityZoneInstances{ {ZoneName: "az1"}, {ZoneName: "az2"}, }, } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) var azArgs []string t.PatchValue(ec2.RunInstances, func(e *amzec2.EC2, ri *amzec2.RunInstances) (*amzec2.RunInstancesResp, error) { azArgs = append(azArgs, ri.AvailZone) return nil, runInstancesError }) _, _, _, err = testing.StartInstance(env, "1") c.Assert(err, gc.ErrorMatches, fmt.Sprintf( "cannot run instances: %s \\(%s\\)", regexp.QuoteMeta(runInstancesError.Message), runInstancesError.Code, )) c.Assert(azArgs, gc.DeepEquals, []string{"az1", "az2"}) } func (t *localServerSuite) TestStartInstanceAvailZoneOneConstrained(c *gc.C) { t.testStartInstanceAvailZoneOneConstrained(c, azConstrainedErr) } func (t *localServerSuite) TestStartInstanceAvailZoneOneInsufficientInstanceCapacity(c *gc.C) { t.testStartInstanceAvailZoneOneConstrained(c, azInsufficientInstanceCapacityErr) } func (t *localServerSuite) TestStartInstanceAvailZoneOneNoDefaultSubnetErr(c *gc.C) { t.testStartInstanceAvailZoneOneConstrained(c, azNoDefaultSubnetErr) } func (t *localServerSuite) testStartInstanceAvailZoneOneConstrained(c *gc.C, runInstancesError *amzec2.Error) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ result: []common.AvailabilityZoneInstances{ {ZoneName: "az1"}, {ZoneName: "az2"}, }, } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) // The first call to RunInstances fails with an error indicating the AZ // is constrained. The second attempt succeeds, and so allocates to az2. var azArgs []string realRunInstances := *ec2.RunInstances t.PatchValue(ec2.RunInstances, func(e *amzec2.EC2, ri *amzec2.RunInstances) (*amzec2.RunInstancesResp, error) { azArgs = append(azArgs, ri.AvailZone) if len(azArgs) == 1 { return nil, runInstancesError } return realRunInstances(e, ri) }) inst, hwc := testing.AssertStartInstance(c, env, "1") c.Assert(azArgs, gc.DeepEquals, []string{"az1", "az2"}) c.Assert(ec2.InstanceEC2(inst).AvailZone, gc.Equals, "az2") c.Check(*hwc.AvailabilityZone, gc.Equals, "az2") } func (t *localServerSuite) TestAddresses(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(err, jc.ErrorIsNil) addrs, err := inst.Addresses() c.Assert(err, jc.ErrorIsNil) // Expected values use Address type but really contain a regexp for // the value rather than a valid ip or hostname. expected := []network.Address{{ Value: "8.0.0.*", Type: network.IPv4Address, Scope: network.ScopePublic, }, { Value: "127.0.0.*", Type: network.IPv4Address, Scope: network.ScopeCloudLocal, }} c.Assert(addrs, gc.HasLen, len(expected)) for i, addr := range addrs { c.Check(addr.Value, gc.Matches, expected[i].Value) c.Check(addr.Type, gc.Equals, expected[i].Type) c.Check(addr.Scope, gc.Equals, expected[i].Scope) } } func (t *localServerSuite) TestConstraintsValidatorUnsupported(c *gc.C) { env := t.Prepare(c) validator, err := env.ConstraintsValidator() c.Assert(err, jc.ErrorIsNil) cons := constraints.MustParse("arch=amd64 tags=foo") unsupported, err := validator.Validate(cons) c.Assert(err, jc.ErrorIsNil) c.Assert(unsupported, gc.DeepEquals, []string{"tags"}) } func (t *localServerSuite) TestConstraintsValidatorVocab(c *gc.C) { env := t.Prepare(c) validator, err := env.ConstraintsValidator() c.Assert(err, jc.ErrorIsNil) cons := constraints.MustParse("arch=ppc64el") _, err = validator.Validate(cons) c.Assert(err, gc.ErrorMatches, "invalid constraint value: arch=ppc64el\nvalid values are:.*") cons = constraints.MustParse("instance-type=foo") _, err = validator.Validate(cons) c.Assert(err, gc.ErrorMatches, "invalid constraint value: instance-type=foo\nvalid values are:.*") } func (t *localServerSuite) TestConstraintsMerge(c *gc.C) { env := t.Prepare(c) validator, err := env.ConstraintsValidator() c.Assert(err, jc.ErrorIsNil) consA := constraints.MustParse("arch=amd64 mem=1G cpu-power=10 cpu-cores=2 tags=bar") consB := constraints.MustParse("arch=i386 instance-type=m1.small") cons, err := validator.Merge(consA, consB) c.Assert(err, jc.ErrorIsNil) c.Assert(cons, gc.DeepEquals, constraints.MustParse("arch=i386 instance-type=m1.small tags=bar")) } func (t *localServerSuite) TestPrecheckInstanceValidInstanceType(c *gc.C) { env := t.Prepare(c) cons := constraints.MustParse("instance-type=m1.small root-disk=1G") placement := "" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, cons, placement) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestPrecheckInstanceInvalidInstanceType(c *gc.C) { env := t.Prepare(c) cons := constraints.MustParse("instance-type=m1.invalid") placement := "" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, cons, placement) c.Assert(err, gc.ErrorMatches, `invalid AWS instance type "m1.invalid" specified`) } func (t *localServerSuite) TestPrecheckInstanceUnsupportedArch(c *gc.C) { env := t.Prepare(c) cons := constraints.MustParse("instance-type=cc1.4xlarge arch=i386") placement := "" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, cons, placement) c.Assert(err, gc.ErrorMatches, `invalid AWS instance type "cc1.4xlarge" and arch "i386" specified`) } func (t *localServerSuite) TestPrecheckInstanceAvailZone(c *gc.C) { env := t.Prepare(c) placement := "zone=test-available" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, constraints.Value{}, placement) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestPrecheckInstanceAvailZoneUnavailable(c *gc.C) { env := t.Prepare(c) placement := "zone=test-unavailable" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, constraints.Value{}, placement) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestPrecheckInstanceAvailZoneUnknown(c *gc.C) { env := t.Prepare(c) placement := "zone=test-unknown" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, constraints.Value{}, placement) c.Assert(err, gc.ErrorMatches, `invalid availability zone "test-unknown"`) } func (t *localServerSuite) TestValidateImageMetadata(c *gc.C) { env := t.Prepare(c) params, err := env.(simplestreams.MetadataValidator).MetadataLookupParams("test") c.Assert(err, jc.ErrorIsNil) params.Series = coretesting.FakeDefaultSeries params.Endpoint = "https://ec2.endpoint.com" params.Sources, err = environs.ImageMetadataSources(env) c.Assert(err, jc.ErrorIsNil) image_ids, _, err := imagemetadata.ValidateImageMetadata(params) c.Assert(err, jc.ErrorIsNil) sort.Strings(image_ids) c.Assert(image_ids, gc.DeepEquals, []string{"ami-00000033", "ami-00000034", "ami-00000035", "ami-00000039"}) } func (t *localServerSuite) TestGetToolsMetadataSources(c *gc.C) { t.PatchValue(&tools.DefaultBaseURL, "") env := t.Prepare(c) sources, err := tools.GetMetadataSources(env) c.Assert(err, jc.ErrorIsNil) c.Assert(sources, gc.HasLen, 0) } func (t *localServerSuite) TestSupportedArchitectures(c *gc.C) { env := t.Prepare(c) a, err := env.SupportedArchitectures() c.Assert(err, jc.ErrorIsNil) c.Assert(a, jc.SameContents, []string{"amd64", "i386"}) } func (t *localServerSuite) TestSupportsNetworking(c *gc.C) { env := t.Prepare(c) _, supported := environs.SupportsNetworking(env) c.Assert(supported, jc.IsTrue) } func (t *localServerSuite) TestAllocateAddressFailureToFindNetworkInterface(c *gc.C) { env := t.prepareEnviron(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) instanceIds, err := env.StateServerInstances() c.Assert(err, jc.ErrorIsNil) instId := instanceIds[0] addr := network.Address{Value: "8.0.0.4"} // Invalid instance found err = env.AllocateAddress(instId+"foo", "", addr) c.Assert(err, gc.ErrorMatches, ".*InvalidInstanceID.NotFound.*") // No network interface err = env.AllocateAddress(instId, "", addr) c.Assert(errors.Cause(err), gc.ErrorMatches, "unexpected AWS response: network interface not found") } func (t *localServerSuite) setUpInstanceWithDefaultVpc(c *gc.C) (environs.NetworkingEnviron, instance.Id) { // setting a default-vpc will create a network interface t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"vpc-xxxxxxx"}, }) env := t.prepareEnviron(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) instanceIds, err := env.StateServerInstances() c.Assert(err, jc.ErrorIsNil) return env, instanceIds[0] } func (t *localServerSuite) TestAllocateAddress(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} var actualAddr network.Address mockAssign := func(ec2Inst *amzec2.EC2, netId string, addr network.Address) error { actualAddr = addr return nil } t.PatchValue(&ec2.AssignPrivateIPAddress, mockAssign) err := env.AllocateAddress(instId, "", addr) c.Assert(err, jc.ErrorIsNil) c.Assert(actualAddr, gc.Equals, addr) } func (t *localServerSuite) TestAllocateAddressIPAddressInUseOrEmpty(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} mockAssign := func(ec2Inst *amzec2.EC2, netId string, addr network.Address) error { return &amzec2.Error{Code: "InvalidParameterValue"} } t.PatchValue(&ec2.AssignPrivateIPAddress, mockAssign) err := env.AllocateAddress(instId, "", addr) c.Assert(errors.Cause(err), gc.Equals, environs.ErrIPAddressUnavailable) err = env.AllocateAddress(instId, "", network.Address{}) c.Assert(errors.Cause(err), gc.Equals, environs.ErrIPAddressUnavailable) } func (t *localServerSuite) TestAllocateAddressNetworkInterfaceFull(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} mockAssign := func(ec2Inst *amzec2.EC2, netId string, addr network.Address) error { return &amzec2.Error{Code: "PrivateIpAddressLimitExceeded"} } t.PatchValue(&ec2.AssignPrivateIPAddress, mockAssign) err := env.AllocateAddress(instId, "", addr) c.Assert(errors.Cause(err), gc.Equals, environs.ErrIPAddressesExhausted) } func (t *localServerSuite) TestReleaseAddress(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} // Allocate the address first so we can release it err := env.AllocateAddress(instId, "", addr) c.Assert(err, jc.ErrorIsNil) err = env.ReleaseAddress(instId, "", addr) c.Assert(err, jc.ErrorIsNil) // Releasing a second time tests that the first call actually released // it plus tests the error handling of ReleaseAddress err = env.ReleaseAddress(instId, "", addr) msg := fmt.Sprintf(`failed to release address "8\.0\.0\.4" from instance %q.*`, instId) c.Assert(err, gc.ErrorMatches, msg) } func (t *localServerSuite) TestReleaseAddressUnknownInstance(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) // We should be able to release an address with an unknown instance id // without it being allocated. addr := network.Address{Value: "8.0.0.4"} err := env.ReleaseAddress(instance.UnknownId, "", addr) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestNetworkInterfaces(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) interfaces, err := env.NetworkInterfaces(instId) c.Assert(err, jc.ErrorIsNil) expectedInterfaces := []network.InterfaceInfo{{ DeviceIndex: 0, MACAddress: "20:01:60:cb:27:37", CIDR: "10.10.0.0/20", ProviderId: "eni-0", ProviderSubnetId: "subnet-0", VLANTag: 0, InterfaceName: "unsupported0", Disabled: false, NoAutoStart: false, ConfigType: network.ConfigDHCP, Address: network.NewScopedAddress("10.10.0.5", network.ScopeCloudLocal), }} c.Assert(interfaces, jc.DeepEquals, expectedInterfaces) } func (t *localServerSuite) TestSubnets(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) subnets, err := env.Subnets("", []network.Id{"subnet-0"}) c.Assert(err, jc.ErrorIsNil) defaultSubnets := []network.SubnetInfo{{ // this is defined in the test server for the default-vpc CIDR: "10.10.0.0/20", ProviderId: "subnet-0", VLANTag: 0, AllocatableIPLow: net.ParseIP("10.10.0.4").To4(), AllocatableIPHigh: net.ParseIP("10.10.15.254").To4(), }} c.Assert(subnets, jc.DeepEquals, defaultSubnets) } func (t *localServerSuite) TestSubnetsNoNetIds(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) _, err := env.Subnets("", []network.Id{}) c.Assert(err, gc.ErrorMatches, "subnetIds must not be empty") } func (t *localServerSuite) TestSubnetsMissingSubnet(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) _, err := env.Subnets("", []network.Id{"subnet-0", "Missing"}) c.Assert(err, gc.ErrorMatches, `failed to find the following subnet ids: \[Missing\]`) } func (t *localServerSuite) TestSupportsAddressAllocationTrue(c *gc.C) { t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"vpc-xxxxxxx"}, }) env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsTrue) } func (t *localServerSuite) TestSupportsAddressAllocationWithNoFeatureFlag(c *gc.C) { t.SetFeatureFlags() // clear the flags. env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, gc.ErrorMatches, "address allocation not supported") c.Assert(err, jc.Satisfies, errors.IsNotSupported) c.Assert(result, jc.IsFalse) } func (t *localServerSuite) TestAllocateAddressWithNoFeatureFlag(c *gc.C) { t.SetFeatureFlags() // clear the flags. env := t.prepareEnviron(c) err := env.AllocateAddress("i-foo", "net1", network.NewAddresses("1.2.3.4")[0]) c.Assert(err, gc.ErrorMatches, "address allocation not supported") c.Assert(err, jc.Satisfies, errors.IsNotSupported) } func (t *localServerSuite) TestReleaseAddressWithNoFeatureFlag(c *gc.C) { t.SetFeatureFlags() // clear the flags. env := t.prepareEnviron(c) err := env.ReleaseAddress("i-foo", "net1", network.NewAddresses("1.2.3.4")[0]) c.Assert(err, gc.ErrorMatches, "address allocation not supported") c.Assert(err, jc.Satisfies, errors.IsNotSupported) } func (t *localServerSuite) TestSupportsAddressAllocationCaches(c *gc.C) { t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"none"}, }) env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsFalse) // this value won't change normally, the change here is to // ensure that subsequent calls use the cached value t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"vpc-xxxxxxx"}, }) result, err = env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsFalse) } func (t *localServerSuite) TestSupportsAddressAllocationFalse(c *gc.C) { t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"none"}, }) env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsFalse) } // localNonUSEastSuite is similar to localServerSuite but the S3 mock server // behaves as if it is not in the us-east region. type localNonUSEastSuite struct { coretesting.BaseSuite restoreEC2Patching func() srv localServer env environs.Environ } func (t *localNonUSEastSuite) SetUpSuite(c *gc.C) { t.BaseSuite.SetUpSuite(c) t.restoreEC2Patching = patchEC2ForTesting() } func (t *localNonUSEastSuite) TearDownSuite(c *gc.C) { t.restoreEC2Patching() t.BaseSuite.TearDownSuite(c) } func (t *localNonUSEastSuite) SetUpTest(c *gc.C) { t.BaseSuite.SetUpTest(c) t.srv.config = &s3test.Config{ Send409Conflict: true, } t.srv.startServer(c) cfg, err := config.New(config.NoDefaults, localConfigAttrs) c.Assert(err, jc.ErrorIsNil) env, err := environs.Prepare(cfg, envtesting.BootstrapContext(c), configstore.NewMem()) c.Assert(err, jc.ErrorIsNil) t.env = env } func (t *localNonUSEastSuite) TearDownTest(c *gc.C) { t.srv.stopServer(c) t.BaseSuite.TearDownTest(c) } func patchEC2ForTesting() func() { ec2.UseTestImageData(ec2.TestImagesData) ec2.UseTestInstanceTypeData(ec2.TestInstanceTypeCosts) ec2.UseTestRegionData(ec2.TestRegions) restoreTimeouts := envtesting.PatchAttemptStrategies(ec2.ShortAttempt, ec2.StorageAttempt) restoreFinishBootstrap := envtesting.DisableFinishBootstrap() return func() { restoreFinishBootstrap() restoreTimeouts() ec2.UseTestImageData(nil) ec2.UseTestInstanceTypeData(nil) ec2.UseTestRegionData(nil) } } // If match is true, CheckScripts checks that at least one script started // by the cloudinit data matches the given regexp pattern, otherwise it // checks that no script matches. It's exported so it can be used by tests // defined in ec2_test. func CheckScripts(c *gc.C, userDataMap map[interface{}]interface{}, pattern string, match bool) { scripts0 := userDataMap["runcmd"] if scripts0 == nil { c.Errorf("cloudinit has no entry for runcmd") return } scripts := scripts0.([]interface{}) re := regexp.MustCompile(pattern) found := false for _, s0 := range scripts { s := s0.(string) if re.MatchString(s) { found = true } } switch { case match && !found: c.Errorf("script %q not found in %q", pattern, scripts) case !match && found: c.Errorf("script %q found but not expected in %q", pattern, scripts) } } // CheckPackage checks that the cloudinit will or won't install the given // package, depending on the value of match. It's exported so it can be // used by tests defined outside the ec2 package. func CheckPackage(c *gc.C, userDataMap map[interface{}]interface{}, pkg string, match bool) { pkgs0 := userDataMap["packages"] if pkgs0 == nil { if match { c.Errorf("cloudinit has no entry for packages") } return } pkgs := pkgs0.([]interface{}) found := false for _, p0 := range pkgs { p := p0.(string) // p might be a space separate list of packages eg 'foo bar qed' so split them up manyPkgs := set.NewStrings(strings.Split(p, " ")...) hasPkg := manyPkgs.Contains(pkg) if p == pkg || hasPkg { found = true break } } switch { case match && !found: c.Errorf("package %q not found in %v", pkg, pkgs) case !match && found: c.Errorf("%q found but not expected in %v", pkg, pkgs) } }
cherylj/juju
provider/ec2/local_test.go
GO
agpl-3.0
36,055
The code needs a ES2015+ polyfill to work, for example [babel-polyfill](https://babeljs.io/docs/usage/polyfill). ```js require( 'babel-polyfill' ) ; // or import 'babel-polyfill' ; ``` Then ```js const number = require( '@aureooms/js-parse' ) ; // or import number from '@aureooms/js-parse' ; ```
aureooms/es-parse
doc/manual/usage.md
Markdown
agpl-3.0
298
import _ from 'lodash' import Joi from 'joi' import { findOrCreateUserByProfile } from '../user-service' import request from 'request-promise' const schema = Joi.object({ clientId: Joi.string().required(), clientSecret: Joi.string().required(), }).required() exports.register = function (server, options, next) { Joi.assert(options, schema) const cookieConfig = _.get(server, 'connections[0].states.settings') server.auth.strategy('facebook', 'bell', { provider: 'facebook', clientId: options.clientId, clientSecret: options.clientSecret, location: server.info.uri, isSecure: cookieConfig.isSecure, password: cookieConfig.password, ttl: cookieConfig.ttl, }) server.route({ method: 'GET', path: '/auth/facebook', config: { auth: 'facebook', handler: authFacebook, }, }) next() } exports.register.attributes = { name: 'facebook', } function authFacebook(req, reply) { const creds = req.auth.credentials.profile const options = { uri: `https://graph.facebook.com/${creds.id}/picture?width=250&height=250`, resolveWithFullResponse: true, } request.get(options) .then((response) => { const profile = { name: creds.displayName, email: creds.email, avatarUrl: response.request.uri.href, oAuthId: creds.id, oAuthProvider: 'facebook', } return findOrCreateUserByProfile(profile) }) .then((token) => { reply() .state('token', token, { path: '/' }) .redirect('/') }) .catch(reply) }
huitparfait/huitparfait
huitparfait-auth/src/providers/facebook.js
JavaScript
agpl-3.0
1,771
# -*- coding: utf-8 -*- """ Tests the "preview" selector in the LMS that allows changing between Staff, Learner, and Content Groups. """ from textwrap import dedent from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc from common.test.acceptance.pages.common.auto_auth import AutoAuthPage from common.test.acceptance.pages.lms.courseware import CoursewarePage from common.test.acceptance.pages.lms.staff_view import StaffCoursewarePage from common.test.acceptance.tests.helpers import UniqueCourseTest, create_user_partition_json from openedx.core.lib.tests import attr from xmodule.partitions.partitions import ENROLLMENT_TRACK_PARTITION_ID, MINIMUM_STATIC_PARTITION_ID, Group @attr(shard=20) class StaffViewTest(UniqueCourseTest): """ Tests that verify the staff view. """ USERNAME = "STAFF_TESTER" EMAIL = "johndoe@example.com" def setUp(self): super(StaffViewTest, self).setUp() self.courseware_page = CoursewarePage(self.browser, self.course_id) # Install a course with sections/problems, tabs, updates, and handouts self.course_fixture = CourseFixture( self.course_info['org'], self.course_info['number'], self.course_info['run'], self.course_info['display_name'] ) self.populate_course_fixture(self.course_fixture) self.course_fixture.install() # Auto-auth register for the course. # Do this as global staff so that you will see the Staff View AutoAuthPage(self.browser, username=self.USERNAME, email=self.EMAIL, course_id=self.course_id, staff=True).visit() def _goto_staff_page(self): """ Open staff page with assertion """ self.courseware_page.visit() staff_page = StaffCoursewarePage(self.browser, self.course_id) self.assertEqual(staff_page.staff_view_mode, 'Staff') return staff_page @attr(shard=20) class CourseWithContentGroupsTest(StaffViewTest): """ Verifies that changing the "View this course as" selector works properly for content groups. """ def setUp(self): super(CourseWithContentGroupsTest, self).setUp() # pylint: disable=protected-access self.course_fixture._update_xblock(self.course_fixture._course_location, { "metadata": { u"user_partitions": [ create_user_partition_json( MINIMUM_STATIC_PARTITION_ID, 'Configuration alpha,beta', 'Content Group Partition', [ Group(MINIMUM_STATIC_PARTITION_ID + 1, 'alpha'), Group(MINIMUM_STATIC_PARTITION_ID + 2, 'beta') ], scheme="cohort" ) ], }, }) def populate_course_fixture(self, course_fixture): """ Populates test course with chapter, sequential, and 3 problems. One problem is visible to all, one problem is visible only to Group "alpha", and one problem is visible only to Group "beta". """ problem_data = dedent(""" <problem markdown="Simple Problem" max_attempts="" weight=""> <choiceresponse> <label>Choose Yes.</label> <checkboxgroup> <choice correct="true">Yes</choice> </checkboxgroup> </choiceresponse> </problem> """) self.alpha_text = "VISIBLE TO ALPHA" self.beta_text = "VISIBLE TO BETA" self.audit_text = "VISIBLE TO AUDIT" self.everyone_text = "VISIBLE TO EVERYONE" course_fixture.add_children( XBlockFixtureDesc('chapter', 'Test Section').add_children( XBlockFixtureDesc('sequential', 'Test Subsection').add_children( XBlockFixtureDesc('vertical', 'Test Unit').add_children( XBlockFixtureDesc( 'problem', self.alpha_text, data=problem_data, metadata={"group_access": {MINIMUM_STATIC_PARTITION_ID: [MINIMUM_STATIC_PARTITION_ID + 1]}} ), XBlockFixtureDesc( 'problem', self.beta_text, data=problem_data, metadata={"group_access": {MINIMUM_STATIC_PARTITION_ID: [MINIMUM_STATIC_PARTITION_ID + 2]}} ), XBlockFixtureDesc( 'problem', self.audit_text, data=problem_data, # Below 1 is the hardcoded group ID for "Audit" metadata={"group_access": {ENROLLMENT_TRACK_PARTITION_ID: [1]}} ), XBlockFixtureDesc( 'problem', self.everyone_text, data=problem_data ) ) ) ) ) @attr('a11y') def test_course_page(self): """ Run accessibility audit for course staff pages. """ course_page = self._goto_staff_page() course_page.a11y_audit.config.set_rules({ 'ignore': [ 'aria-allowed-attr', # TODO: AC-559 'aria-roles', # TODO: AC-559, 'aria-valid-attr', # TODO: AC-559 'color-contrast', # TODO: AC-559 'link-href', # TODO: AC-559 'section', # TODO: AC-559 'region', # TODO: AC-932 ] }) course_page.a11y_audit.check_for_accessibility_errors()
msegado/edx-platform
common/test/acceptance/tests/lms/test_lms_user_preview.py
Python
agpl-3.0
5,975
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_02) on Sat Apr 28 23:24:33 CEST 2012 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class net.sourceforge.jaad.mp4.boxes.impl.MediaDataBox</title> <meta name="date" content="2012-04-28"> <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="Uses of Class net.sourceforge.jaad.mp4.boxes.impl.MediaDataBox"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <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><a href="../../../../../../../net/sourceforge/jaad/mp4/boxes/impl/MediaDataBox.html" title="class in net.sourceforge.jaad.mp4.boxes.impl">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?net/sourceforge/jaad/mp4/boxes/impl/\class-useMediaDataBox.html" target="_top">Frames</a></li> <li><a href="MediaDataBox.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class net.sourceforge.jaad.mp4.boxes.impl.MediaDataBox" class="title">Uses of Class<br>net.sourceforge.jaad.mp4.boxes.impl.MediaDataBox</h2> </div> <div class="classUseContainer">No usage of net.sourceforge.jaad.mp4.boxes.impl.MediaDataBox</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_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><a href="../../../../../../../net/sourceforge/jaad/mp4/boxes/impl/MediaDataBox.html" title="class in net.sourceforge.jaad.mp4.boxes.impl">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?net/sourceforge/jaad/mp4/boxes/impl/\class-useMediaDataBox.html" target="_top">Frames</a></li> <li><a href="MediaDataBox.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate
lib/jaad-0.8.4-doc/net/sourceforge/jaad/mp4/boxes/impl/class-use/MediaDataBox.html
HTML
agpl-3.0
4,587
--- title: Episode 29 subtitle: Nachwuchs datum: 23. Oktober 2019 layout: post author: Birgit, Dominic, Friedl, Marco, Markus, Stefan und Steve explicit: 'no' duration: "01:03:15" audio: mp3: 3sh029_nachwuchs.mp3 chapters: - '00:00:00.000 Vorgeplänkel' - '00:00:59.000 Vorstellungsrunde' - '00:03:57.000 Einspieler von Dominic' - '00:06:40.000 Vorstellungsrunde Teil 2' - '00:08:00.000 Der Trainer macht ein Recap' - '00:11:00.000 Recap aller Teilnehmer:innen' - '00:34:45.000 Wie lange sollte man für HM trainieren?' - '00:46:12.000 Vorausschau' - '00:49:15.000 mögliche weitere Läufe' - '01:01:00.000 Verabschiebung' contributors: - name: Dominic Helm uri: https://therandomscientist.de/ email: hellmue@3-schweinehun.de - name: Stefan Haslinger uri: https://panoptikum.io/informatom email: stefan@3-schweinehun.de - name: Stefan Dillinger uri: https://raincastle.blog email: steve@3-schweinehun.de - name: Friedhelm Holzwarth uri: https://www.strava.com/athletes/27141570 - name: Marco Grunert uri: https://www.strava.com/athletes/17696623 - name: Markus Brandstätter uri: https://www.strava.com/athletes/3380227 - name: "Birgit Wimmer" uri: "http://www.papiertapir.de/" email: "birgit@papiertapir.de" --- {% podigee_player page %} ## Show Notes and Links * Halmarathonserie [Superhalfs](https://www.superhalfs.com/) * [sächsische Nachtlaufserie](https://dresdner-nachtlauf.de/nachtlaufserie/) * [Halbmarathon Cambridge](https://cambridgehalfmarathon.com/) * [Triathlon St.Pölten](https://challenge-stpoelten.com) * [Wolfgangseelauf](http://www.wolfgangseelauf.at/) * [Adventlauf Mödling](http://www.altstadtadventlauf.at/) * [Wien Staffelmarathon](https://www.vienna-marathon.com/) ### Erfahrungsberichte * Steve's [Rückblick auf das 3-Schweinehunde Main-Event](https://raincastle.blog/?p=942) * Stefan's Laufbericht [Breaking Three](https://www.informatom.com/2019/10/17/breaking_three.html) ### Nächste Termine * 1.12.2019: [Adventlauf Mödling](http://www.altstadtadventlauf.at/)
3schweinehunde/website-source
_posts/2019-10-23-episode29.md
Markdown
agpl-3.0
2,029
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone from crm.models import Person from geocodable.models import LocationAlias import uuid class Event(models.Model): name = models.CharField(max_length=200) timestamp = models.DateTimeField() end_timestamp = models.DateTimeField() attendees = models.ManyToManyField(Person, related_name='events', blank=True) uid = models.CharField(max_length=200, blank=True) location = models.ForeignKey(LocationAlias, default=None, blank=True, null=True) instance_id = models.CharField(max_length=200, blank=True) @property def geo(self): return {'lat': self.lat, 'lng': self.lng} @property def lat(self): if self.location is not None: return self.location.lat else: return None @property def lng(self): if self.location is not None: return self.location.lng else: return None def __unicode__(self): return "%s (%s)"%(self.name, self.timestamp)
tdfischer/organizer
events/models.py
Python
agpl-3.0
1,124
require "helper" module Nokogiri module XML class TestEntityDecl < Nokogiri::TestCase def setup super @xml = Nokogiri::XML(<<-eoxml) <?xml version="1.0"?><?TEST-STYLE PIDATA?> <!DOCTYPE staff SYSTEM "staff.dtd" [ <!ENTITY ent1 "es"> <!ENTITY nocontent > ]> <root /> eoxml @entities = @xml.internal_subset.children @entity_decl = @entities.first end def test_external_id assert_nil @entity_decl.external_id end def test_system_id assert_nil @entity_decl.system_id end def test_entity_type assert_equal 1, @entity_decl.entity_type end def test_original_content assert_equal "es", @entity_decl.original_content assert_nil @entities[1].original_content end def test_content assert_equal "es", @entity_decl.content assert_nil @entities[1].content end def test_type assert_equal 17, @entities.first.type end def test_class assert_instance_of Nokogiri::XML::EntityDecl, @entities.first end def test_attributes assert_raise NoMethodError do @entity_decl.attributes end end def test_namespace assert_raise NoMethodError do @entity_decl.namespace end end def test_namespace_definitions assert_raise NoMethodError do @entity_decl.namespace_definitions end end def test_line assert_raise NoMethodError do @entity_decl.line end end def test_inspect assert_equal( "#<#{@entity_decl.class.name}:#{sprintf("0x%x", @entity_decl.object_id)} #{@entity_decl.to_s.inspect}>", @entity_decl.inspect ) end end end end
ging/vcc
vendor/gems/nokogiri-1.4.1/test/xml/test_entity_decl.rb
Ruby
agpl-3.0
1,834
<!DOCTYPE html> <!--[if IE]><![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Class ComponentShouldHaveTestBuilderModelStateExtensions </title> <meta name="viewport" content="width=device-width"> <meta name="title" content="Class ComponentShouldHaveTestBuilderModelStateExtensions "> <meta name="generator" content="docfx 2.6.3.0"> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="../styles/docfx.vendor.css"> <link rel="stylesheet" href="../styles/docfx.css"> <link rel="stylesheet" href="../styles/main.css"> <meta property="docfx:navrel" content="../toc.html"> <meta property="docfx:tocrel" content="toc.html"> <meta property="docfx:rel" content="../"> <meta property="og:title" content="Flexible and asynchronous testing framework for ASP.NET Core MVC"> <meta property="og:site_name" content="My Tested ASP.NET Core MVC Docs"> <meta property="og:url" content="http://docs.mytestedasp.net/"> <meta property="og:description" content="A fluent unit testing library for ASP.NET Core MVC"> <meta property="og:image" content="https://mytestedasp.net/Content/Images/logosocial.jpg"> <meta property="og:type" content="website"> <meta property="og:locale" content="en_US"> <meta property="twitter:card" content="summary"> <meta property="twitter:title" content="Flexible and asynchronous testing framework for ASP.NET Core MVC"> <meta property="twitter:description" content="A fluent unit testing library for ASP.NET Core MVC"> <meta property="twitter:creator" content="@MyTestedASPNET"> <meta property="twitter:url" content="https://mytestedasp.net/"> <meta property="twitter:image" content="https://mytestedasp.net/Content/Images/logosocial.jpg"> </head> <body data-spy="scroll" data-target="#affix"> <div id="wrapper"> <header> <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> MY TESTED ASP.NET CORE MVC DOCS </a> </div> <div class="collapse navbar-collapse" id="navbar"> <form class="navbar-form navbar-right" role="search" id="search"> <div class="form-group"> <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off"> </div> </form> </div> </div> </nav> <div class="subnav navbar navbar-default"> <div class="container hide-when-search" id="breadcrumb"> <ul class="breadcrumb"> <li></li> </ul> </div> </div> </header> <div role="main" class="container body-content hide-when-search"> <div class="sidenav hide-when-search"> <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a> <div class="sidetoggle collapse" id="sidetoggle"> <div id="sidetoc"></div> </div> </div> <div class="article row grid-right"> <div class="col-md-10"> <article class="content wrap" id="_content"> <h1 id="MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions" data-uid="MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions">Class ComponentShouldHaveTestBuilderModelStateExtensions </h1> <div class="markdown level0 summary"><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="2" sourceendlinenumber="2">Contains <span class="xref">ModelStateDictionary</span> extension methods for <a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder-1.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder_1">IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt;</a>.</p> </div> <div class="markdown level0 conceptual"></div> <div class="inheritance"> <h5>Inheritance</h5> <div class="level0"><span class="xref">System.Object</span></div> <div class="level1"><span class="xref">ComponentShouldHaveTestBuilderModelStateExtensions</span></div> </div> <h6><strong>Namespace</strong>:MyTested.AspNetCore.Mvc</h6> <h6><strong>Assembly</strong>:MyTested.AspNetCore.Mvc.ModelState.dll</h6> <h5 id="MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions_syntax">Syntax</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public static class ComponentShouldHaveTestBuilderModelStateExtensions</code></pre> </div> <h3 id="methods">Methods </h3> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/new/tutorial/docs/_docfx/apispec/new?filename=MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions_InvalidModelState__1_MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder___0__System_Nullable_System_Int32__.md&amp;value=---%0Auid%3A%20MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.InvalidModelState%60%601(MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder%7B%60%600%7D%2CSystem.Nullable%7BSystem.Int32%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/blob/tutorial/src/MyTested.AspNetCore.Mvc.ModelState/ComponentShouldHaveTestBuilderModelStateExtensions.cs/#L62">View Source</a> </span> <h4 id="MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions_InvalidModelState__1_MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder___0__System_Nullable_System_Int32__" data-uid="MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.InvalidModelState``1(MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder{``0},System.Nullable{System.Int32})">InvalidModelState&lt;TBuilder&gt;(IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt;, Nullable&lt;Int32&gt;)</h4> <div class="markdown level1 summary"><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="2" sourceendlinenumber="2">Tests whether the action has invalid <span class="xref">ModelStateDictionary</span>.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public static TBuilder InvalidModelState&lt;TBuilder&gt;(this IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt; builder, int ? withNumberOfErrors = null)where TBuilder : IBaseTestBuilder</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder-1.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder_1">IBaseTestBuilderWithComponentShouldHaveTestBuilder</a>&lt;TBuilder&gt;</td> <td><em>builder</em></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="1">Instance of <a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder-1.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder_1">IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt;</a> type.</p> </td> </tr> <tr> <td><span class="xref">System.Nullable</span>&lt;<span class="xref">System.Int32</span>&gt;</td> <td><em>withNumberOfErrors</em></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="2">Expected number of <span class="xref">ModelStateDictionary</span> errors. If default null is provided, the test builder checks only if any errors are found.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">TBuilder</span></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="1">The same component should have test builder.</p> </td> </tr> </tbody> </table> <h5 class="typeParameters">Type Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><em>TBuilder</em></td> <td>Class representing ASP.NET Core MVC test builder.</td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/new/tutorial/docs/_docfx/apispec/new?filename=MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions_ModelState__1_MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder___0__System_Action_MyTested_AspNetCore_Mvc_Builders_Contracts_Models_IModelStateTestBuilder__.md&amp;value=---%0Auid%3A%20MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.ModelState%60%601(MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder%7B%60%600%7D%2CSystem.Action%7BMyTested.AspNetCore.Mvc.Builders.Contracts.Models.IModelStateTestBuilder%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/blob/tutorial/src/MyTested.AspNetCore.Mvc.ModelState/ComponentShouldHaveTestBuilderModelStateExtensions.cs/#L26">View Source</a> </span> <h4 id="MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions_ModelState__1_MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder___0__System_Action_MyTested_AspNetCore_Mvc_Builders_Contracts_Models_IModelStateTestBuilder__" data-uid="MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.ModelState``1(MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder{``0},System.Action{MyTested.AspNetCore.Mvc.Builders.Contracts.Models.IModelStateTestBuilder})">ModelState&lt;TBuilder&gt;(IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt;, Action&lt;IModelStateTestBuilder&gt;)</h4> <div class="markdown level1 summary"><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="2" sourceendlinenumber="2">Tests whether the component has specific <span class="xref">ModelStateDictionary</span> errors.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public static TBuilder ModelState&lt;TBuilder&gt;(this IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt; builder, Action&lt;IModelStateTestBuilder&gt; modelStateTestBuilder)where TBuilder : IBaseTestBuilder</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder-1.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder_1">IBaseTestBuilderWithComponentShouldHaveTestBuilder</a>&lt;TBuilder&gt;</td> <td><em>builder</em></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="1">Instance of <a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder-1.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder_1">IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt;</a> type.</p> </td> </tr> <tr> <td><span class="xref">System.Action</span>&lt;<a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Models.IModelStateTestBuilder.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Models_IModelStateTestBuilder">IModelStateTestBuilder</a>&gt;</td> <td><em>modelStateTestBuilder</em></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="1">Builder for testing specific <span class="xref">ModelStateDictionary</span> errors.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">TBuilder</span></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="1">The same component should have test builder.</p> </td> </tr> </tbody> </table> <h5 class="typeParameters">Type Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><em>TBuilder</em></td> <td>Class representing ASP.NET Core MVC test builder.</td> </tr> </tbody> </table> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/new/tutorial/docs/_docfx/apispec/new?filename=MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions_ValidModelState__1_MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder___0__.md&amp;value=---%0Auid%3A%20MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.ValidModelState%60%601(MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder%7B%60%600%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/blob/tutorial/src/MyTested.AspNetCore.Mvc.ModelState/ComponentShouldHaveTestBuilderModelStateExtensions.cs/#L44">View Source</a> </span> <h4 id="MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions_ValidModelState__1_MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder___0__" data-uid="MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.ValidModelState``1(MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder{``0})">ValidModelState&lt;TBuilder&gt;(IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt;)</h4> <div class="markdown level1 summary"><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="2" sourceendlinenumber="2">Tests whether the component has valid <span class="xref">ModelStateDictionary</span> with no errors.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public static TBuilder ValidModelState&lt;TBuilder&gt;(this IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt; builder)where TBuilder : IBaseTestBuilder</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder-1.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder_1">IBaseTestBuilderWithComponentShouldHaveTestBuilder</a>&lt;TBuilder&gt;</td> <td><em>builder</em></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="1">Instance of <a class="xref" href="MyTested.AspNetCore.Mvc.Builders.Contracts.Base.IBaseTestBuilderWithComponentShouldHaveTestBuilder-1.html#MyTested_AspNetCore_Mvc_Builders_Contracts_Base_IBaseTestBuilderWithComponentShouldHaveTestBuilder_1">IBaseTestBuilderWithComponentShouldHaveTestBuilder&lt;TBuilder&gt;</a> type.</p> </td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><span class="xref">TBuilder</span></td> <td><p sourcefile="api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.yml" sourcestartlinenumber="1" sourceendlinenumber="1">The same component should have test builder.</p> </td> </tr> </tbody> </table> <h5 class="typeParameters">Type Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><em>TBuilder</em></td> <td>Class representing ASP.NET Core MVC test builder.</td> </tr> </tbody> </table> </article> </div> <div class="hidden-sm col-md-2" role="complementary"> <div class="sideaffix"> <div class="contribution"> <ul class="nav"> <li> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/new/tutorial/docs/_docfx/apispec/new?filename=MyTested_AspNetCore_Mvc_ComponentShouldHaveTestBuilderModelStateExtensions.md&amp;value=---%0Auid%3A%20MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A" class="contribution-link">Improve this Doc</a> </li> <li> <a href="https://github.com/ivaylokenov/MyTested.AspNetCore.Mvc/blob/tutorial/src/MyTested.AspNetCore.Mvc.ModelState/ComponentShouldHaveTestBuilderModelStateExtensions.cs/#L17" class="contribution-link">View Source</a> </li> </ul> </div> <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix"> <!-- <p><a class="back-to-top" href="#top">Back to top</a><p> --> </nav> </div> </div> </div> </div> <footer> <div class="grad-bottom"></div> <div class="footer"> <div class="container"> <span class="pull-right"> <a href="#top">Back to top</a> </span> <span>Copyright © 2015-2016 <strong><a href="http://mytestedasp.net">MyTestedASP.NET</a></strong>. All Rights Reserved. Generated by <strong><a href="http://dotnet.github.io/docfx/">DocFX</a></strong></span> </div> </div> </footer> </div> <script type="text/javascript" src="../styles/docfx.vendor.js"></script> <script type="text/javascript" src="../styles/docfx.js"></script> <script type="text/javascript" src="../styles/main.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=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.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-51720358-4', 'auto'); ga('send', 'pageview'); </script> <script> !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n; n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window, document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '884740311601716'); fbq('track', 'PageView'); </script> <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=884740311601716&ev=PageView&noscript=1"></noscript> </body> </html>
ivaylokenov/MyTested.Mvc
docs/api/MyTested.AspNetCore.Mvc.ComponentShouldHaveTestBuilderModelStateExtensions.html
HTML
agpl-3.0
25,804
#ifndef _CASSANDRA_H #define _CASSANDRA_H #include <boost/bind.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <cql/cql.hpp> #include <cql/cql_error.hpp> #include <cql/cql_event.hpp> #include <cql/cql_connection.hpp> #include <cql/cql_session.hpp> #include <cql/cql_cluster.hpp> #include <cql/cql_builder.hpp> #include <cql/cql_execute.hpp> #include <cql/cql_result.hpp> bool checkToken(char *inToken, char *internalToken, bool use_ssl); #endif
kkdawkins/manwe
gateway/src/cassandra.hpp
C++
agpl-3.0
471
// Copyright 2017 Baliance. All rights reserved. // // DO NOT EDIT: generated by gooxml ECMA-376 generator // // Use of this source code is governed by the terms of the Affero GNU General // Public License version 3.0 as published by the Free Software Foundation and // appearing in the file LICENSE included in the packaging of this file. A // commercial license can be purchased by contacting sales@baliance.com. package vml_test import ( "encoding/xml" "testing" "baliance.com/gooxml/schema/urn/schemas_microsoft_com/vml" ) func TestRoundrectConstructor(t *testing.T) { v := vml.NewRoundrect() if v == nil { t.Errorf("vml.NewRoundrect must return a non-nil value") } if err := v.Validate(); err != nil { t.Errorf("newly constructed vml.Roundrect should validate: %s", err) } } func TestRoundrectMarshalUnmarshal(t *testing.T) { v := vml.NewRoundrect() buf, _ := xml.Marshal(v) v2 := vml.NewRoundrect() xml.Unmarshal(buf, v2) }
LYY/code2docx
vendor/baliance.com/gooxml/schema/urn/schemas_microsoft_com/vml/Roundrect_test.go
GO
agpl-3.0
951
/** * Copyright (c) 2002-2012 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.com; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.neo4j.kernel.impl.nioneo.store.StoreId; public class MadeUpServerImplementation implements MadeUpCommunicationInterface { private final StoreId storeIdToRespondWith; private boolean gotCalled; public MadeUpServerImplementation( StoreId storeIdToRespondWith ) { this.storeIdToRespondWith = storeIdToRespondWith; } @Override public Response<Integer> multiply( int value1, int value2 ) { gotCalled = true; return new Response<Integer>( value1 * value2, storeIdToRespondWith, TransactionStream.EMPTY, ResourceReleaser.NO_OP ); } @Override public Response<Void> fetchDataStream( MadeUpWriter writer, int dataSize ) { // Reversed on the server side. This will send data back to the client. writer.write( new KnownDataByteChannel( dataSize ) ); return emptyResponse(); } private Response<Void> emptyResponse() { return new Response<Void>( null, storeIdToRespondWith, TransactionStream.EMPTY, ResourceReleaser.NO_OP ); } @Override public Response<Void> sendDataStream( ReadableByteChannel data ) { // TOOD Verify as well? readFully( data ); return emptyResponse(); } private void readFully( ReadableByteChannel data ) { ByteBuffer buffer = ByteBuffer.allocate( 1000 ); try { while ( true ) { buffer.clear(); if ( data.read( buffer ) == -1 ) break; } } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public Response<Integer> throwException( String messageInException ) { throw new MadeUpException( messageInException, new Exception( "The cause of it" ) ); } public boolean gotCalled() { return this.gotCalled; } }
dmontag/neo4j-enterprise
com/src/test/java/org/neo4j/com/MadeUpServerImplementation.java
Java
agpl-3.0
2,903
<?php /** * @file entitenj.class.php * Définition de la classe entitenj */ /** * Classe abstraite entitenj * Classe gérant les entité non joueurs dont les informatiosn sotn réparties sur deux tables */ class entitenj extends entite { protected $incarn; ///< Objet contenant les informations sur une incarnation particulière de l'entité (dérivé de entnj_incarn) private $def; ///< Objet contenant les informations sur la définition de l'entité (dérivé de entitenj_def) function __construct($incarn, $perso=null, $attaquant=true, $adversaire=null) { $def = $incarn->get_def(); $this->id = $incarn->get_id(); $this->incarn = &$incarn; $this->def = $def; $this->action = $incarn->get_action($attaquant); if( $this->action === false ) $this->action = $def->get_action(); $this->arme_type = $def->get_arme(); $this->comp_combat = 'melee'; $this->comp = array(); $this->x = $incarn->get_x(); $this->y = $incarn->get_y(); if( !$this->x && $perso ) { $this->x = $perso->get_x(); $this->y = $perso->get_y(); } $this->hp = $incarn->get_hp(); $this->hp_max = $def->get_hp(); $this->reserve = $def->get_reserve(); $this->rm_restant = $def->get_reserve(); $this->pa = 0; $this->nom = $incarn->get_nom() ? $incarn->get_nom() : $def->get_nom(); $this->race = $incarn->get_race($perso); $this->pp = $def->get_pp() + $incarn->get_bonus_pp(); $this->pm = $def->get_pm() + $incarn->get_bonus_pm(); $this->pm_para = $this->pm; $this->distance_tir = $incarn->get_distance_tir(); if( !$this->distance_tir ) $this->distance_tir = $def->get_distance_tir(); $this->esquive = ceil( $def->get_esquive() * $incarn->get_coeff_comp($perso, $def) ); $this->distance = ceil( $def->get_distance() * $incarn->get_coeff_comp($perso, $def) ); $this->melee = ceil( $def->get_melee() * $incarn->get_coeff_comp($perso, $def) ); $this->incantation = ceil( $def->get_incantation() * $incarn->get_coeff_comp($perso, $def) ); $this->sort_mort = ceil( $def->get_sort_mort() * $incarn->get_coeff_comp($perso, $def) ); $this->sort_vie = ceil( $def->get_sort_vie() * $incarn->get_coeff_comp($perso, $def) ); $this->sort_element = ceil( $def->get_sort_element() * $incarn->get_coeff_comp($perso, $def) ); $this->blocage = $def->get_blocage(); $this->buff = $incarn->get_buff(); $this->etat = array(); $this->force = ceil( $def->get_force() * $incarn->get_coeff_carac() ); $this->puissance = ceil( $def->get_puissance() * $incarn->get_coeff_carac() ); $this->energie = ceil( $def->get_energie() * $incarn->get_coeff_carac() ); $this->vie = ceil( $def->get_constitution() * $incarn->get_coeff_carac() ); $this->volonte = ceil( $def->get_volonte() * $incarn->get_coeff_carac() ); $this->dexterite = ceil( $def->get_dexterite() * $incarn->get_coeff_carac() ); $this->enchantement = array(); $this->arme_degat = $incarn->get_arme_degat() + $def->get_arme_degat($perso, $adversaire); $this->bouclier_degat = $def->get_bouclier(); $this->level = $def->get_level(); $this->rang_royaume = 0; $this->star = $def->get_star(); $this->espece = $def->get_type(); $this->point_victoire = $def->get_point_victoire(); } /// Action effectuées à la fin d'un combat function fin_combat(&$perso, $degats=null) { $this->incarn->set_hp( $this->get_hp() ); if( $this->get_hp() > 0 ) $this->incarn->sauver(); else $this->incarn->mort($perso); } /// Action effectuées à la fin d'un combat pour le défenseur function fin_defense(&$perso, &$royaume, $pet, $degats, $batiment) { return $this->incarn->fin_defense($perso, $royaume, $pet, $degats, $this->def); } // à améliorer function get_type_def() { return $this->def->get_type(); } /// Renvoie le coût en PA de l'attaque function get_cout_attaque(&$perso, $cible) { $cout = $this->incarn->get_cout_attaque($perso, $cible); if( $cout !== null ) return $cout; else return parent::get_cout_attaque($perso, $cible); } /// Renvoie le coût en PA pour attaquer l'entité function get_cout_attaque_base(&$perso) { return $this->incarn->get_cout_attaque_base($perso); } /// Indique si l'entité peut attaquer function peut_attaquer() { return $this->incarn->peut_attaquer(); } /// Actions effectuées à la fin d'un combat pour l'attaquant function fin_attaque(&$perso, &$cible, $cout_pa) { $this->incarn->fin_attaque($cible); } /// Date de pose ou construction de l'entité function get_date_debut() { return $this->incarn->get_date_debut(); } /// @todo change nom function get_id_joueur() { return $this->incarn->get_id_joueur(); } } ?>
StarshineOnline/Starshine-Online
class/entitenj.class.php
PHP
agpl-3.0
4,726
export class TrainingCanceledError extends Error { constructor() { super('Training Canceled') } } export class TrainingAlreadyStartedError extends Error { constructor() { super('Training Already Started') } }
botpress/botpress
modules/nlu/src/backend/stan/errors.ts
TypeScript
agpl-3.0
226
/*! jQuery UI - v1.11.0 - 2014-08-12 * http://jqueryui.com * Includes: core.js, widget.js, mouse.js, position.js, draggable.js, droppable.js, resizable.js, selectable.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, menu.js, progressbar.js, selectmenu.js, slider.js, spinner.js, tabs.js, tooltip.js, effect.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI Core 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.0", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function() { var position = this.css( "position" ), excludeStaticParent = position === "absolute", scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return (/(auto|scroll)/).test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; /*! * jQuery UI Widget 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); var widget = $.widget; /*! * jQuery UI Mouse 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/mouse/ */ var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); var mouse = $.widget("ui.mouse", { version: "1.11.0", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown." + this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click." + this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("." + this.widgetName); if ( this._mouseMoveDelegate ) { this.document .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate) .unbind("mouseup." + this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if ( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; this.document .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .bind( "mouseup." + this.widgetName, this._mouseUpDelegate ); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); // Iframe mouseup check - mouseup occurred in another document } else if ( !event.which ) { return this._mouseUp( event ); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { this.document .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate ); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } mouseHandled = false; return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); /*! * jQuery UI Position 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/position/ */ (function() { $.ui = $.ui || {}; var cachedScrollbarWidth, supportsOffsetFractions, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ), isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9; return { element: withinElement, isWindow: isWindow, isDocument: isDocument, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !supportsOffsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem: elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function() { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); })(); var position = $.ui.position; /*! * jQuery UI Draggable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/draggable/ */ $.widget("ui.draggable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { this.element[0].style.position = "relative"; } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._setHandleClassName(); this._mouseInit(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._setHandleClassName(); } }, _destroy: function() { if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) { this.destroyOnClear = true; return; } this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._removeHandleClassName(); this._mouseDestroy(); }, _mouseCapture: function(event) { var document = this.document[ 0 ], o = this.options; // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { // Support: IE9+ // If the <body> is blurred, IE will switch windows, see #9520 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { // Blur any element that currently has focus, see #4261 $( document.activeElement ).blur(); } } catch ( error ) {} // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") .css({ width: this.offsetWidth + "px", height: this.offsetHeight + "px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if ($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent(); this.offsetParent = this.helper.offsetParent(); this.offsetParentCssPosition = this.offsetParent.css( "position" ); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; //Reset scroll cache this.offset.scroll = false; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this.position = this._generatePosition( event, false ); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if (this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.offsetParentCssPosition === "fixed" ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition( event, true ); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if (this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } this.helper[ 0 ].style.left = this.position.left + "px"; this.helper[ 0 ].style.top = this.position.top + "px"; if ($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if (this.dropped) { dropped = this.dropped; this.dropped = false; } if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if (that._trigger("stop", event) !== false) { that._clear(); } }); } else { if (this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function(event) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } // The interaction is over; whether or not the click resulted in a drag, focus the element this.element.focus(); return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if (this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _setHandleClassName: function() { this._removeHandleClassName(); $( this.options.handle || this.element ).addClass( "ui-draggable-handle" ); }, _removeHandleClassName: function() { this.element.find( ".ui-draggable-handle" ) .addBack() .removeClass( "ui-draggable-handle" ); }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[ 0 ], [ event ])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element); if (!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = { left: +obj[0], top: +obj[1] || 0 }; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _isRootNode: function( element ) { return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ]; }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(), document = this.document[ 0 ]; // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if ( this._isRootNode( this.offsetParent[ 0 ] ) ) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if ( this.cssPosition !== "relative" ) { return { top: 0, left: 0 }; } var p = this.element.position(), scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ), left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 ) }; }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0), right: (parseInt(this.element.css("marginRight"),10) || 0), bottom: (parseInt(this.element.css("marginBottom"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var over, c, ce, o = this.options, document = this.document[ 0 ]; this.relative_container = null; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if ( !ce ) { return; } over = c.css( "overflow" ) !== "hidden"; this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ), ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relative_container = c; }, _convertPositionTo: function(d, pos) { if (!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod) ) }; }, _generatePosition: function( event, constrainPosition ) { var containment, co, top, left, o = this.options, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ), pageX = event.pageX, pageY = event.pageY; // Cache the scroll if ( !scrollIsRootNode || !this.offset.scroll ) { this.offset.scroll = { top: this.scrollParent.scrollTop(), left: this.scrollParent.scrollLeft() }; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( constrainPosition ) { if ( this.containment ) { if ( this.relative_container ){ co = this.relative_container.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if (event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if (event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if (event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if (event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if (o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } if ( o.axis === "y" ) { pageX = this.originalPageX; } if ( o.axis === "x" ) { pageY = this.originalPageY; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; if ( this.destroyOnClear ) { this.destroy(); } }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call( this, type, [ event, ui, this ], true ); //The absolute position has to be recalculated after plugins if (type === "drag") { this.positionAbs = this._convertPositionTo("absolute"); } return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function( event, ui, inst ) { var o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $( this ).sortable( "instance" ); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function( event, ui, inst ) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var uiSortable = $.extend( {}, ui, { item: inst.element }); $.each(inst.sortables, function() { if (this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" if (this.shouldRevert) { this.instance.options.revert = this.shouldRevert; } //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if (inst.options.helper === "original") { this.instance.currentItem.css({ top: "auto", left: "auto" }); } } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function( event, ui, inst ) { var that = this; $.each(inst.sortables, function() { var innermostIntersecting = false, thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function() { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this !== thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.contains(thisSortable.instance.element[0], this.instance.element[0]) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if (innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if (!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if (this.instance.currentItem) { this.instance._mouseDrag(event); } } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if (this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger("out", event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if (this.instance.placeholder) { this.instance.placeholder.remove(); } inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function( event, ui, instance ) { var t = $( "body" ), o = instance.options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function( event, ui, i ) { if ( i.scrollParent[ 0 ] !== i.document[ 0 ] && i.scrollParent[ 0 ].tagName !== "HTML" ) { i.overflowOffset = i.scrollParent.offset(); } }, drag: function( event, ui, i ) { var o = i.options, scrolled = false, document = i.document[ 0 ]; if ( i.scrollParent[ 0 ] !== document && i.scrollParent[ 0 ].tagName !== "HTML" ) { if (!o.axis || o.axis !== "x") { if ((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; } else if (event.pageY - i.overflowOffset.top < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } } if (!o.axis || o.axis !== "y") { if ((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; } else if (event.pageX - i.overflowOffset.left < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } } else { if (!o.axis || o.axis !== "x") { if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if (!o.axis || o.axis !== "y") { if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function( event, ui, i ) { var o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if (this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function( event, ui, inst ) { var ts, bs, ls, rs, l, r, t, b, i, first, o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if (inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if (o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } } first = (ts || bs || ls || rs); if (o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } } if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function( event, ui, instance ) { var min, o = instance.options, group = $.makeArray($(o.stack)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); var draggable = $.ui.draggable; /*! * jQuery UI Droppable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/droppable/ */ $.widget( "ui.droppable", { version: "1.11.0", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var proportions, o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction( accept ) ? accept : function( d ) { return d.is( accept ); }; this.proportions = function( /* valueToWrite */ ) { if ( arguments.length ) { // Store the droppable's proportions proportions = arguments[ 0 ]; } else { // Retrieve or derive the droppable's proportions return proportions ? proportions : proportions = { width: this.element[ 0 ].offsetWidth, height: this.element[ 0 ].offsetHeight }; } }; this._addToManager( o.scope ); o.addClasses && this.element.addClass( "ui-droppable" ); }, _addToManager: function( scope ) { // Add the reference and positions to the manager $.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || []; $.ui.ddmanager.droppables[ scope ].push( this ); }, _splice: function( drop ) { var i = 0; for ( ; i < drop.length; i++ ) { if ( drop[ i ] === this ) { drop.splice( i, 1 ); } } }, _destroy: function() { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this.element.removeClass( "ui-droppable ui-droppable-disabled" ); }, _setOption: function( key, value ) { if ( key === "accept" ) { this.accept = $.isFunction( value ) ? value : function( d ) { return d.is( value ); }; } else if ( key === "scope" ) { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this._addToManager( value ); } this._super( key, value ); }, _activate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.addClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "activate", event, this.ui( draggable ) ); } }, _deactivate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "deactivate", event, this.ui( draggable ) ); } }, _over: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.addClass( this.options.hoverClass ); } this._trigger( "over", event, this.ui( draggable ) ); } }, _out: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "out", event, this.ui( draggable ) ); } }, _drop: function( event, custom ) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return false; } this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() { var inst = $( this ).droppable( "instance" ); if ( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) && $.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance ) ) { childrenIntersection = true; return false; } }); if ( childrenIntersection ) { return false; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "drop", event, this.ui( draggable ) ); return this.element; } return false; }, ui: function( c ) { return { draggable: ( c.currentItem || c.element ), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = (function() { function isOverAxis( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); } return function( draggable, droppable, toleranceMode ) { if ( !droppable.offset ) { return false; } var draggableLeft, draggableTop, x1 = ( draggable.positionAbs || draggable.position.absolute ).left, y1 = ( draggable.positionAbs || draggable.position.absolute ).top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions().width, b = t + droppable.proportions().height; switch ( toleranceMode ) { case "fit": return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b ); case "intersect": return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half case "pointer": draggableLeft = ( ( draggable.positionAbs || draggable.position.absolute ).left + ( draggable.clickOffset || draggable.offset.click ).left ); draggableTop = ( ( draggable.positionAbs || draggable.position.absolute ).top + ( draggable.clickOffset || draggable.offset.click ).top ); return isOverAxis( draggableTop, t, droppable.proportions().height ) && isOverAxis( draggableLeft, l, droppable.proportions().width ); case "touch": return ( ( y1 >= t && y1 <= b ) || // Top edge touching ( y2 >= t && y2 <= b ) || // Bottom edge touching ( y1 < t && y2 > b ) // Surrounded vertically ) && ( ( x1 >= l && x1 <= r ) || // Left edge touching ( x2 >= l && x2 <= r ) || // Right edge touching ( x1 < l && x2 > r ) // Surrounded horizontally ); default: return false; } }; })(); /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { // No disabled and non-accepted if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } // Filter out elements in the current dragged item for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } // Activate the droppable if used directly from draggables if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight }); } }, drop: function( draggable, event ) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() { if ( !this.options ) { return; } if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance ) ) { dropped = this._drop.call( this, event ) || dropped; } if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { this.isout = true; this.isover = false; this._deactivate.call( this, event ); } }); return dropped; }, dragStart: function( draggable, event ) { // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function( draggable, event ) { // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if ( draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } // Run through all droppables and check their positions based on specific tolerance options $.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() { if ( this.options.disabled || this.greedyChild || !this.visible ) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect( draggable, this, this.options.tolerance ), c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null ); if ( !c ) { return; } if ( this.options.greedy ) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents( ":data(ui-droppable)" ).filter(function() { return $( this ).droppable( "instance" ).options.scope === scope; }); if ( parent.length ) { parentInstance = $( parent[ 0 ] ).droppable( "instance" ); parentInstance.greedyChild = ( c === "isover" ); } } // we just moved into a greedy child if ( parentInstance && c === "isover" ) { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call( parentInstance, event ); } this[ c ] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call( this, event ); // we just moved out of a greedy child if ( parentInstance && c === "isout" ) { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call( parentInstance, event ); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; var droppable = $.ui.droppable; /*! * jQuery UI Resizable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/resizable/ */ $.widget("ui.resizable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, // See #7960 zIndex: 90, // callbacks resize: null, start: null, stop: null }, _num: function( value ) { return parseInt( value, 10 ) || 0; }, _isNumber: function( value ) { return !isNaN( parseInt( value , 10 ) ); }, _hasScroll: function( el, a ) { if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; }, _create: function() { var n, i, handle, axis, hname, that = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null }); // Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { this.element.wrap( $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({ position: this.element.css("position"), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css("top"), left: this.element.css("left") }) ); this.element = this.element.parent().data( "ui-resizable", this.element.resizable( "instance" ) ); this.elementIsWrapper = true; this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); // support: Safari // Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css("resize"); this.originalElement.css("resize", "none"); this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" })); // support: IE9 // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css("margin") }); this._proportionallyResize(); } this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" }); if(this.handles.constructor === String) { if ( this.handles === "all") { this.handles = "n,e,s,w,se,sw,ne,nw"; } n = this.handles.split(","); this.handles = {}; for(i = 0; i < n.length; i++) { handle = $.trim(n[i]); hname = "ui-resizable-"+handle; axis = $("<div class='ui-resizable-handle " + hname + "'></div>"); axis.css({ zIndex: o.zIndex }); // TODO : What's going on here? if ("se" === handle) { axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); } this.handles[handle] = ".ui-resizable-"+handle; this.element.append(axis); } } this._renderAxis = function(target) { var i, axis, padPos, padWrapper; target = target || this.element; for(i in this.handles) { if(this.handles[i].constructor === String) { this.handles[i] = this.element.children( this.handles[ i ] ).first().show(); } if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); padPos = [ "padding", /ne|nw|n/.test(i) ? "Top" : /se|sw|s/.test(i) ? "Bottom" : /^e$/.test(i) ? "Right" : "Left" ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } // TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) { continue; } } }; // TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $(".ui-resizable-handle", this.element) .disableSelection(); this._handles.mouseover(function() { if (!that.resizing) { if (this.className) { axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); } that.axis = axis && axis[1] ? axis[1] : "se"; } }); if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .mouseenter(function() { if (o.disabled) { return; } $(this).removeClass("ui-resizable-autohide"); that._handles.show(); }) .mouseleave(function(){ if (o.disabled) { return; } if (!that.resizing) { $(this).addClass("ui-resizable-autohide"); that._handles.hide(); } }); } this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var wrapper, _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove(); }; // TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); wrapper = this.element; this.originalElement.css({ position: wrapper.css("position"), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css("top"), left: wrapper.css("left") }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css("resize", this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var i, handle, capture = false; for (i in this.handles) { handle = $(this.handles[i])[0]; if (handle === event.target || $.contains(handle, event.target)) { capture = true; } } return !this.options.disabled && capture; }, _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, el = this.element; this.resizing = true; this._renderProxy(); curleft = this._num(this.helper.css("left")); curtop = this._num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: this.helper.width(), height: this.helper.height() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $(".ui-resizable-" + this.axis).css("cursor"); $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0, trigger = this._change[a]; this.prevPosition = { top: this.position.top, left: this.position.left }; this.prevSize = { width: this.size.width, height: this.size.height }; if (!trigger) { return false; } data = trigger.apply(this, [event, dx, dy]); this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); this._propagate("resize", event); if ( this.position.top !== this.prevPosition.top ) { props.top = this.position.top + "px"; } if ( this.position.left !== this.prevPosition.left ) { props.left = this.position.left + "px"; } if ( this.size.width !== this.prevSize.width ) { props.width = this.size.width + "px"; } if ( this.size.height !== this.prevSize.height ) { props.height = this.size.height + "px"; } el.css( props ); if ( !this._helper && this._proportionallyResizeElements.length ) { this._proportionallyResize(); } if ( !$.isEmptyObject( props ) ) { this._trigger( "resize", event, this.ui() ); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if(this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && this._hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $("body").css("cursor", "auto"); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if(pMinWidth > b.minWidth) { b.minWidth = pMinWidth; } if(pMinHeight > b.minHeight) { b.minHeight = pMinHeight; } if(pMaxWidth < b.maxWidth) { b.maxWidth = pMaxWidth; } if(pMaxHeight < b.maxHeight) { b.maxHeight = pMaxHeight; } } this._vBoundaries = b; }, _updateCache: function(data) { this.offset = this.helper.offset(); if (this._isNumber(data.left)) { this.position.left = data.left; } if (this._isNumber(data.top)) { this.position.top = data.top; } if (this._isNumber(data.height)) { this.size.height = data.height; } if (this._isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (this._isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (this._isNumber(data.width)) { data.height = (data.width / this.aspectRatio); } if (a === "sw") { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a === "nw") { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function( data ) { var o = this._vBoundaries, a = this.axis, ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height), dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height, cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw) { data.width = o.minWidth; } if (isminh) { data.height = o.minHeight; } if (ismaxw) { data.width = o.maxWidth; } if (ismaxh) { data.height = o.maxHeight; } if (isminw && cw) { data.left = dw - o.minWidth; } if (ismaxw && cw) { data.left = dw - o.maxWidth; } if (isminh && ch) { data.top = dh - o.minHeight; } if (ismaxh && ch) { data.top = dh - o.maxHeight; } // Fixing jump error on top/left - bug #2330 if (!data.width && !data.height && !data.left && data.top) { data.top = null; } else if (!data.width && !data.height && !data.top && data.left) { data.left = null; } return data; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var i, j, borders, paddings, prel, element = this.helper || this.element; for ( i=0; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { this.borderDif = []; borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")]; paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")]; for ( j = 0; j < borders.length; j++ ) { this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); } } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); } }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $("<div style='overflow:hidden;'></div>"); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() - 1, height: this.element.outerHeight() - 1, position: "absolute", left: this.elementOffset.left +"px", top: this.elementOffset.top +"px", zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx) { return { width: this.originalSize.width + dx }; }, w: function(event, dx) { var cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n !== "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition, prevSize: this.prevSize, prevPosition: this.prevPosition }; } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "animate", { stop: function( event ) { var that = $(this).resizable( "instance" ), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && that._hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width, style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css("width"), 10), height: parseInt(that.element.css("height"), 10), top: parseInt(that.element.css("top"), 10), left: parseInt(that.element.css("left"), 10) }; if (pr && pr.length) { $(pr[0]).css({ width: data.width, height: data.height }); } // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.ui.plugin.add( "resizable", "containment", { start: function() { var element, p, co, ch, cw, width, height, that = $( this ).resizable( "instance" ), o = that.options, el = that.element, oc = o.containment, ce = ( oc instanceof $ ) ? oc.get( 0 ) : ( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc; if ( !ce ) { return; } that.containerElement = $( ce ); if ( /document/.test( oc ) || oc === document ) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $( document ), left: 0, top: 0, width: $( document ).width(), height: $( document ).height() || document.body.parentNode.scrollHeight }; } else { element = $( ce ); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function( i, name ) { p[ i ] = that._num( element.css( "padding" + name ) ); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: ( element.innerHeight() - p[ 3 ] ), width: ( element.innerWidth() - p[ 1 ] ) }; co = that.containerOffset; ch = that.containerSize.height; cw = that.containerSize.width; width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw ); height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ; that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function( event, ui ) { var woset, hoset, isParent, isOffsetRelative, that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top: 0, left: 0 }, ce = that.containerElement, continueResize = true; if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) { cop = co; } if ( cp.left < ( that._helper ? co.left : 0 ) ) { that.size.width = that.size.width + ( that._helper ? ( that.position.left - co.left ) : ( that.position.left - cop.left ) ); if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } that.position.left = o.helper ? co.left : 0; } if ( cp.top < ( that._helper ? co.top : 0 ) ) { that.size.height = that.size.height + ( that._helper ? ( that.position.top - co.top ) : that.position.top ); if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left + that.position.left; that.offset.top = that.parentData.top + that.position.top; woset = Math.abs( ( that._helper ? that.offset.left - cop.left : ( that.offset.left - co.left ) ) + that.sizeDiff.width ); hoset = Math.abs( ( that._helper ? that.offset.top - cop.top : ( that.offset.top - co.top ) ) + that.sizeDiff.height ); isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 ); isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) ); if ( isParent && isOffsetRelative ) { woset -= Math.abs( that.parentData.left ); } if ( woset + that.size.width >= that.parentData.width ) { that.size.width = that.parentData.width - woset; if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } } if ( hoset + that.size.height >= that.parentData.height ) { that.size.height = that.parentData.height - hoset; if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } } if ( !continueResize ){ that.position.left = ui.prevPosition.left; that.position.top = ui.prevPosition.top; that.size.width = ui.prevSize.width; that.size.height = ui.prevSize.height; } }, stop: function(){ var that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement, helper = $( that.helper ), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } } }); $.ui.plugin.add("resizable", "alsoResize", { start: function () { var that = $(this).resizable( "instance" ), o = that.options, _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("ui-resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10) }); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var that = $(this).resizable( "instance" ), o = that.options, os = that.originalSize, op = that.originalPosition, delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"]; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) { style[prop] = sum || null; } }); el.css(style); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function () { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "ghost", { start: function() { var that = $(this).resizable( "instance" ), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass("ui-resizable-ghost") .addClass(typeof o.ghost === "string" ? o.ghost : ""); that.ghost.appendTo(that.helper); }, resize: function(){ var that = $(this).resizable( "instance" ); if (that.ghost) { that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).resizable( "instance" ); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.ui.plugin.add("resizable", "grid", { resize: function() { var that = $(this).resizable( "instance" ), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid, gridX = (grid[0]||1), gridY = (grid[1]||1), ox = Math.round((cs.width - os.width) / gridX) * gridX, oy = Math.round((cs.height - os.height) / gridY) * gridY, newWidth = os.width + ox, newHeight = os.height + oy, isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), isMinWidth = o.minWidth && (o.minWidth > newWidth), isMinHeight = o.minHeight && (o.minHeight > newHeight); o.grid = grid; if (isMinWidth) { newWidth = newWidth + gridX; } if (isMinHeight) { newHeight = newHeight + gridY; } if (isMaxWidth) { newWidth = newWidth - gridX; } if (isMaxHeight) { newHeight = newHeight - gridY; } if (/^(se|s|e)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; } else if (/^(ne)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.left = op.left - ox; } else { if ( newHeight - gridY > 0 ) { that.size.height = newHeight; that.position.top = op.top - oy; } else { that.size.height = gridY; that.position.top = op.top + os.height - gridY; } if ( newWidth - gridX > 0 ) { that.size.width = newWidth; that.position.left = op.left - ox; } else { that.size.width = gridX; that.position.left = op.left + os.width - gridX; } } } }); var resizable = $.ui.resizable; /*! * jQuery UI Selectable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/selectable/ */ var selectable = $.widget("ui.selectable", $.ui.mouse, { version: "1.11.0", options: { appendTo: "body", autoRefresh: true, distance: 0, filter: "*", tolerance: "touch", // callbacks selected: null, selecting: null, start: null, stop: null, unselected: null, unselecting: null }, _create: function() { var selectees, that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this), pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass("ui-selected"), selecting: $this.hasClass("ui-selecting"), unselecting: $this.hasClass("ui-unselecting") }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $("<div class='ui-selectable-helper'></div>"); }, _destroy: function() { this.selectees .removeClass("ui-selectee") .removeData("selectable-item"); this.element .removeClass("ui-selectable ui-selectable-disabled"); this._mouseDestroy(); }, _mouseStart: function(event) { var that = this, options = this.options; this.opos = [ event.pageX, event.pageY ]; if (this.options.disabled) { return; } this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.pageX, "top": event.pageY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter(".ui-selected").each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey && !event.ctrlKey) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().addBack().each(function() { var doSelect, selectee = $.data(this, "selectable-item"); if (selectee) { doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected"); selectee.$element .removeClass(doSelect ? "ui-unselecting" : "ui-selected") .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); selectee.unselecting = !doSelect; selectee.selecting = doSelect; selectee.selected = doSelect; // selectable (UN)SELECTING callback if (doSelect) { that._trigger("selecting", event, { selecting: selectee.element }); } else { that._trigger("unselecting", event, { unselecting: selectee.element }); } return false; } }); }, _mouseDrag: function(event) { this.dragged = true; if (this.options.disabled) { return; } var tmp, that = this, options = this.options, x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 }); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"), hit = false; //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element === that.element[0]) { return; } if (options.tolerance === "touch") { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance === "fit") { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass("ui-selecting"); selectee.selecting = true; // selectable SELECTING callback that._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if ((event.metaKey || event.ctrlKey) && selectee.startselected) { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; selectee.$element.addClass("ui-selected"); selectee.selected = true; } else { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; } // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var that = this; this.dragged = false; $(".ui-unselecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; selectee.startselected = false; that._trigger("unselected", event, { unselected: selectee.element }); }); $(".ui-selecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-selecting").addClass("ui-selected"); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; that._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } }); /*! * jQuery UI Accordion 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/accordion/ */ var accordion = $.widget( "ui.accordion", { version: "1.11.0", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, hideProps: { borderTopWidth: "hide", borderBottomWidth: "hide", paddingTop: "hide", paddingBottom: "hide", height: "hide" }, showProps: { borderTopWidth: "show", borderBottomWidth: "show", paddingTop: "show", paddingBottom: "show", height: "show" }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) // ARIA .attr( "role", "tablist" ); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default " + "ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this._destroyIcons(); // clean up content panels contents = this.headers.next() .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom " + "ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeUniqueId(); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown: function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var options = this.options; this._processPanels(); // was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { this.headers = this.element.find( this.options.header ) .addClass( "ui-accordion-header ui-state-default ui-corner-all" ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .filter( ":not(.ui-accordion-content-active)" ) .hide(); }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(); this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) .removeClass( "ui-corner-all" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this.headers .attr( "role", "tab" ) .each(function() { var header = $( this ), headerId = header.uniqueId().attr( "id" ), panel = header.next(), panelId = panel.uniqueId().attr( "id" ); header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }) .next() .attr({ "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }) .next() .attr({ "aria-hidden": "false" }); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split( " " ), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr({ "tabIndex": -1, "aria-expanded": "false" }); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr( "aria-hidden", "false" ) .prev() .attr({ "aria-selected": "true", tabIndex: 0, "aria-expanded": "true" }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( this.showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( this.hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( this.hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( this.showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className; } this._trigger( "activate", null, data ); } }); /*! * jQuery UI Menu 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/menu/ */ var menu = $.widget( "ui.menu", { version: "1.11.0", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, items: "> *", menus: "ul", position: { my: "left-1 top", at: "right top" }, role: "menu", // callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; // Flag used to prevent firing of the click handler // as the event bubbles up through nested menus this.mouseHandled = false; this.element .uniqueId() .addClass( "ui-menu ui-widget ui-widget-content" ) .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) .attr({ role: this.options.role, tabIndex: 0 }); if ( this.options.disabled ) { this.element .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } this._on({ // Prevent focus from sticking to links inside menu after clicking // them (focus should always stay on UL during navigation). "mousedown .ui-menu-item": function( event ) { event.preventDefault(); }, "click .ui-menu-item": function( event ) { var target = $( event.target ); if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) { this.select( event ); // Only set the mouseHandled flag if the event will bubble, see #9469. if ( !event.isPropagationStopped() ) { this.mouseHandled = true; } // Open submenu on click if ( target.has( ".ui-menu" ).length ) { this.expand( event ); } else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) { // Redirect focus to the menu this.element.trigger( "focus", [ true ] ); // If the active item is on the top level, let it stay active. // Otherwise, blur the active item since it is no longer visible. if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { clearTimeout( this.timer ); } } } }, "mouseenter .ui-menu-item": function( event ) { var target = $( event.currentTarget ); // Remove ui-state-active class from siblings of the newly focused menu item // to avoid a jump caused by adjacent elements both having a class with a border target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" ); this.focus( event, target ); }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function( event, keepActiveItem ) { // If there's already an active item, keep it active // If not, activate the first item var item = this.active || this.element.find( this.options.items ).eq( 0 ); if ( !keepActiveItem ) { this.focus( event, item ); } }, blur: function( event ) { this._delay(function() { if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { this.collapseAll( event ); } }); }, keydown: "_keydown" }); this.refresh(); // Clicks outside of a menu collapse any open menus this._on( this.document, { click: function( event ) { if ( this._closeOnDocumentClick( event ) ) { this.collapseAll( event ); } // Reset the mouseHandled flag this.mouseHandled = false; } }); }, _destroy: function() { // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).addBack() .removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .show(); // Destroy menu items this.element.find( ".ui-menu-item" ) .removeClass( "ui-menu-item" ) .removeAttr( "role" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .removeClass( "ui-state-hover" ) .removeAttr( "tabIndex" ) .removeAttr( "role" ) .removeAttr( "aria-haspopup" ) .children().each( function() { var elem = $( this ); if ( elem.data( "ui-menu-submenu-carat" ) ) { elem.remove(); } }); // Destroy menu dividers this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); }, _keydown: function( event ) { var match, prev, character, skip, regex, preventDefault = true; function escape( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); } switch ( event.keyCode ) { case $.ui.keyCode.PAGE_UP: this.previousPage( event ); break; case $.ui.keyCode.PAGE_DOWN: this.nextPage( event ); break; case $.ui.keyCode.HOME: this._move( "first", "first", event ); break; case $.ui.keyCode.END: this._move( "last", "last", event ); break; case $.ui.keyCode.UP: this.previous( event ); break; case $.ui.keyCode.DOWN: this.next( event ); break; case $.ui.keyCode.LEFT: this.collapse( event ); break; case $.ui.keyCode.RIGHT: if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { this.expand( event ); } break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: this._activate( event ); break; case $.ui.keyCode.ESCAPE: this.collapse( event ); break; default: preventDefault = false; prev = this.previousFilter || ""; character = String.fromCharCode( event.keyCode ); skip = false; clearTimeout( this.filterTimer ); if ( character === prev ) { skip = true; } else { character = prev + character; } regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.find( this.options.items ).filter(function() { return regex.test( $( this ).text() ); }); match = skip && match.index( this.active.next() ) !== -1 ? this.active.nextAll( ".ui-menu-item" ) : match; // If no matches on the current filter, reset to the last character pressed // to move down the menu to the first item that starts with that character if ( !match.length ) { character = String.fromCharCode( event.keyCode ); regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.find( this.options.items ).filter(function() { return regex.test( $( this ).text() ); }); } if ( match.length ) { this.focus( event, match ); if ( match.length > 1 ) { this.previousFilter = character; this.filterTimer = this._delay(function() { delete this.previousFilter; }, 1000 ); } else { delete this.previousFilter; } } else { delete this.previousFilter; } } if ( preventDefault ) { event.preventDefault(); } }, _activate: function( event ) { if ( !this.active.is( ".ui-state-disabled" ) ) { if ( this.active.is( "[aria-haspopup='true']" ) ) { this.expand( event ); } else { this.select( event ); } } }, refresh: function() { var menus, items, that = this, icon = this.options.icons.submenu, submenus = this.element.find( this.options.menus ); this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ); // Initialize nested menus submenus.filter( ":not(.ui-menu)" ) .addClass( "ui-menu ui-widget ui-widget-content ui-front" ) .hide() .attr({ role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" }) .each(function() { var menu = $( this ), item = menu.parent(), submenuCarat = $( "<span>" ) .addClass( "ui-menu-icon ui-icon " + icon ) .data( "ui-menu-submenu-carat", true ); item .attr( "aria-haspopup", "true" ) .prepend( submenuCarat ); menu.attr( "aria-labelledby", item.attr( "id" ) ); }); menus = submenus.add( this.element ); items = menus.find( this.options.items ); // Initialize menu-items containing spaces and/or dashes only as dividers items.not( ".ui-menu-item" ).each(function() { var item = $( this ); if ( that._isDivider( item ) ) { item.addClass( "ui-widget-content ui-menu-divider" ); } }); // Don't refresh list items that are already adapted items.not( ".ui-menu-item, .ui-menu-divider" ) .addClass( "ui-menu-item" ) .uniqueId() .attr({ tabIndex: -1, role: this._itemRole() }); // Add aria-disabled attribute to any disabled menu item items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); // If the active item has been removed, blur the menu if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { this.blur(); } }, _itemRole: function() { return { menu: "menuitem", listbox: "option" }[ this.options.role ]; }, _setOption: function( key, value ) { if ( key === "icons" ) { this.element.find( ".ui-menu-icon" ) .removeClass( this.options.icons.submenu ) .addClass( value.submenu ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, focus: function( event, item ) { var nested, focused; this.blur( event, event && event.type === "focus" ); this._scrollIntoView( item ); this.active = item.first(); focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" ); // Only update aria-activedescendant if there's a role // otherwise we assume focus is managed elsewhere if ( this.options.role ) { this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); } // Highlight active parent menu item, if any this.active .parent() .closest( ".ui-menu-item" ) .addClass( "ui-state-active" ); if ( event && event.type === "keydown" ) { this._close(); } else { this.timer = this._delay(function() { this._close(); }, this.delay ); } nested = item.children( ".ui-menu" ); if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) { this._startOpening(nested); } this.activeMenu = item.parent(); this._trigger( "focus", event, { item: item } ); }, _scrollIntoView: function( item ) { var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; if ( this._hasScroll() ) { borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; scroll = this.activeMenu.scrollTop(); elementHeight = this.activeMenu.height(); itemHeight = item.outerHeight(); if ( offset < 0 ) { this.activeMenu.scrollTop( scroll + offset ); } else if ( offset + itemHeight > elementHeight ) { this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); } } }, blur: function( event, fromFocus ) { if ( !fromFocus ) { clearTimeout( this.timer ); } if ( !this.active ) { return; } this.active.removeClass( "ui-state-focus" ); this.active = null; this._trigger( "blur", event, { item: this.active } ); }, _startOpening: function( submenu ) { clearTimeout( this.timer ); // Don't open if already open fixes a Firefox bug that caused a .5 pixel // shift in the submenu position when mousing over the carat icon if ( submenu.attr( "aria-hidden" ) !== "true" ) { return; } this.timer = this._delay(function() { this._close(); this._open( submenu ); }, this.delay ); }, _open: function( submenu ) { var position = $.extend({ of: this.active }, this.options.position ); clearTimeout( this.timer ); this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) .hide() .attr( "aria-hidden", "true" ); submenu .show() .removeAttr( "aria-hidden" ) .attr( "aria-expanded", "true" ) .position( position ); }, collapseAll: function( event, all ) { clearTimeout( this.timer ); this.timer = this._delay(function() { // If we were passed an event, look for the submenu that contains the event var currentMenu = all ? this.element : $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway if ( !currentMenu.length ) { currentMenu = this.element; } this._close( currentMenu ); this.blur( event ); this.activeMenu = currentMenu; }, this.delay ); }, // With no arguments, closes the currently active menu - if nothing is active // it closes all menus. If passed an argument, it will search for menus BELOW _close: function( startMenu ) { if ( !startMenu ) { startMenu = this.active ? this.active.parent() : this.element; } startMenu .find( ".ui-menu" ) .hide() .attr( "aria-hidden", "true" ) .attr( "aria-expanded", "false" ) .end() .find( ".ui-state-active" ).not( ".ui-state-focus" ) .removeClass( "ui-state-active" ); }, _closeOnDocumentClick: function( event ) { return !$( event.target ).closest( ".ui-menu" ).length; }, _isDivider: function( item ) { // Match hyphen, em dash, en dash return !/[^\-\u2014\u2013\s]/.test( item.text() ); }, collapse: function( event ) { var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element ); if ( newItem && newItem.length ) { this._close(); this.focus( event, newItem ); } }, expand: function( event ) { var newItem = this.active && this.active .children( ".ui-menu " ) .find( this.options.items ) .first(); if ( newItem && newItem.length ) { this._open( newItem.parent() ); // Delay so Firefox will not hide activedescendant change in expanding submenu from AT this._delay(function() { this.focus( event, newItem ); }); } }, next: function( event ) { this._move( "next", "first", event ); }, previous: function( event ) { this._move( "prev", "last", event ); }, isFirstItem: function() { return this.active && !this.active.prevAll( ".ui-menu-item" ).length; }, isLastItem: function() { return this.active && !this.active.nextAll( ".ui-menu-item" ).length; }, _move: function( direction, filter, event ) { var next; if ( this.active ) { if ( direction === "first" || direction === "last" ) { next = this.active [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) .eq( -1 ); } else { next = this.active [ direction + "All" ]( ".ui-menu-item" ) .eq( 0 ); } } if ( !next || !next.length || !this.active ) { next = this.activeMenu.find( this.options.items )[ filter ](); } this.focus( event, next ); }, nextPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isLastItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.nextAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base - height < 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ) [ !this.active ? "first" : "last" ]() ); } }, previousPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isFirstItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.prevAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base + height > 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ).first() ); } }, _hasScroll: function() { return this.element.outerHeight() < this.element.prop( "scrollHeight" ); }, select: function( event ) { // TODO: It should never be possible to not have an active item at this // point, but the tests don't trigger mouseenter before click. this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); var ui = { item: this.active }; if ( !this.active.has( ".ui-menu" ).length ) { this.collapseAll( event, true ); } this._trigger( "select", event, ui ); } }); /*! * jQuery UI Autocomplete 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/autocomplete/ */ $.widget( "ui.autocomplete", { version: "1.11.0", defaultElement: "<input>", options: { appendTo: null, autoFocus: false, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, // callbacks change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, requestIndex: 0, pending: 0, _create: function() { // Some browsers only repeat keydown events, not keypress events, // so we use the suppressKeyPress flag to determine if we've already // handled the keydown event. #7269 // Unfortunately the code for & in keypress is the same as the up arrow, // so we use the suppressKeyPressRepeat flag to avoid handling keypress // events when we know the keydown event was used to modify the // search term. #7799 var suppressKeyPress, suppressKeyPressRepeat, suppressInput, nodeName = this.element[ 0 ].nodeName.toLowerCase(), isTextarea = nodeName === "textarea", isInput = nodeName === "input"; this.isMultiLine = // Textareas are always multi-line isTextarea ? true : // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable isInput ? false : // All other element types are determined by whether or not they're contentEditable this.element.prop( "isContentEditable" ); this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ]; this.isNewMenu = true; this.element .addClass( "ui-autocomplete-input" ) .attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { if ( this.element.prop( "readOnly" ) ) { suppressKeyPress = true; suppressInput = true; suppressKeyPressRepeat = true; return; } suppressKeyPress = false; suppressInput = false; suppressKeyPressRepeat = false; var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: suppressKeyPress = true; this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: suppressKeyPress = true; this._move( "nextPage", event ); break; case keyCode.UP: suppressKeyPress = true; this._keyEvent( "previous", event ); break; case keyCode.DOWN: suppressKeyPress = true; this._keyEvent( "next", event ); break; case keyCode.ENTER: // when menu is open and has focus if ( this.menu.active ) { // #6055 - Opera still allows the keypress to occur // which causes forms to submit suppressKeyPress = true; event.preventDefault(); this.menu.select( event ); } break; case keyCode.TAB: if ( this.menu.active ) { this.menu.select( event ); } break; case keyCode.ESCAPE: if ( this.menu.element.is( ":visible" ) ) { this._value( this.term ); this.close( event ); // Different browsers have different default behavior for escape // Single press can mean undo or clear // Double press in IE means clear the whole form event.preventDefault(); } break; default: suppressKeyPressRepeat = true; // search timeout should be triggered before the input value is changed this._searchTimeout( event ); break; } }, keypress: function( event ) { if ( suppressKeyPress ) { suppressKeyPress = false; if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { event.preventDefault(); } return; } if ( suppressKeyPressRepeat ) { return; } // replicate some key handlers to allow them to repeat in Firefox and Opera var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: this._move( "nextPage", event ); break; case keyCode.UP: this._keyEvent( "previous", event ); break; case keyCode.DOWN: this._keyEvent( "next", event ); break; } }, input: function( event ) { if ( suppressInput ) { suppressInput = false; event.preventDefault(); return; } this._searchTimeout( event ); }, focus: function() { this.selectedItem = null; this.previous = this._value(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } clearTimeout( this.searching ); this.close( event ); this._change( event ); } }); this._initSource(); this.menu = $( "<ul>" ) .addClass( "ui-autocomplete ui-front" ) .appendTo( this._appendTo() ) .menu({ // disable ARIA support, the live region takes care of that role: null }) .hide() .menu( "instance" ); this._on( this.menu.element, { mousedown: function( event ) { // prevent moving focus out of the text field event.preventDefault(); // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; }); // clicking on the scrollbar causes focus to shift to the body // but we can't detect a mouseup or a click immediately afterward // so we have to track the next mousedown and close the menu if // the user clicks somewhere outside of the autocomplete var menuElement = this.menu.element[ 0 ]; if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { this._delay(function() { var that = this; this.document.one( "mousedown", function( event ) { if ( event.target !== that.element[ 0 ] && event.target !== menuElement && !$.contains( menuElement, event.target ) ) { that.close(); } }); }); } }, menufocus: function( event, ui ) { var label, item; // support: Firefox // Prevent accidental activation of menu items in Firefox (#7024 #9118) if ( this.isNewMenu ) { this.isNewMenu = false; if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { this.menu.blur(); this.document.one( "mousemove", function() { $( event.target ).trigger( event.originalEvent ); }); return; } } item = ui.item.data( "ui-autocomplete-item" ); if ( false !== this._trigger( "focus", event, { item: item } ) ) { // use value to match what will end up in the input, if it was a key event if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { this._value( item.value ); } } // Announce the value in the liveRegion label = ui.item.attr( "aria-label" ) || item.value; if ( label && jQuery.trim( label ).length ) { this.liveRegion.children().hide(); $( "<div>" ).text( label ).appendTo( this.liveRegion ); } }, menuselect: function( event, ui ) { var item = ui.item.data( "ui-autocomplete-item" ), previous = this.previous; // only trigger when focus was lost (click on menu) if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) { this.element.focus(); this.previous = previous; // #6109 - IE triggers two focus events and the second // is asynchronous, so we need to reset the previous // term synchronously and asynchronously :-( this._delay(function() { this.previous = previous; this.selectedItem = item; }); } if ( false !== this._trigger( "select", event, { item: item } ) ) { this._value( item.value ); } // reset the term after the select event // this allows custom select handling to work properly this.term = this._value(); this.close( event ); this.selectedItem = item; } }); this.liveRegion = $( "<span>", { role: "status", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _destroy: function() { clearTimeout( this.searching ); this.element .removeClass( "ui-autocomplete-input" ) .removeAttr( "autocomplete" ); this.menu.element.remove(); this.liveRegion.remove(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "source" ) { this._initSource(); } if ( key === "appendTo" ) { this.menu.element.appendTo( this._appendTo() ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _initSource: function() { var array, url, that = this; if ( $.isArray( this.options.source ) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax({ url: url, data: request, dataType: "json", success: function( data ) { response( data ); }, error: function() { response([]); } }); }; } else { this.source = this.options.source; } }, _searchTimeout: function( event ) { clearTimeout( this.searching ); this.searching = this._delay(function() { // Search if the value has changed, or if the user retypes the same value (see #7434) var equalValues = this.term === this._value(), menuVisible = this.menu.element.is( ":visible" ), modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) { this.selectedItem = null; this.search( null, event ); } }, this.options.delay ); }, search: function( value, event ) { value = value != null ? value : this._value(); // always save the actual value, not the one passed as an argument this.term = this._value(); if ( value.length < this.options.minLength ) { return this.close( event ); } if ( this._trigger( "search", event ) === false ) { return; } return this._search( value ); }, _search: function( value ) { this.pending++; this.element.addClass( "ui-autocomplete-loading" ); this.cancelSearch = false; this.source( { term: value }, this._response() ); }, _response: function() { var index = ++this.requestIndex; return $.proxy(function( content ) { if ( index === this.requestIndex ) { this.__response( content ); } this.pending--; if ( !this.pending ) { this.element.removeClass( "ui-autocomplete-loading" ); } }, this ); }, __response: function( content ) { if ( content ) { content = this._normalize( content ); } this._trigger( "response", null, { content: content } ); if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { this._suggest( content ); this._trigger( "open" ); } else { // use ._close() instead of .close() so we don't cancel future searches this._close(); } }, close: function( event ) { this.cancelSearch = true; this._close( event ); }, _close: function( event ) { if ( this.menu.element.is( ":visible" ) ) { this.menu.element.hide(); this.menu.blur(); this.isNewMenu = true; this._trigger( "close", event ); } }, _change: function( event ) { if ( this.previous !== this._value() ) { this._trigger( "change", event, { item: this.selectedItem } ); } }, _normalize: function( items ) { // assume all items have the right format when the first item is complete if ( items.length && items[ 0 ].label && items[ 0 ].value ) { return items; } return $.map( items, function( item ) { if ( typeof item === "string" ) { return { label: item, value: item }; } return $.extend( {}, item, { label: item.label || item.value, value: item.value || item.label }); }); }, _suggest: function( items ) { var ul = this.menu.element.empty(); this._renderMenu( ul, items ); this.isNewMenu = true; this.menu.refresh(); // size and position menu ul.show(); this._resizeMenu(); ul.position( $.extend({ of: this.element }, this.options.position ) ); if ( this.options.autoFocus ) { this.menu.next(); } }, _resizeMenu: function() { var ul = this.menu.element; ul.outerWidth( Math.max( // Firefox wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping (#7513) ul.width( "" ).outerWidth() + 1, this.element.outerWidth() ) ); }, _renderMenu: function( ul, items ) { var that = this; $.each( items, function( index, item ) { that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); }, _renderItem: function( ul, item ) { return $( "<li>" ).text( item.label ).appendTo( ul ); }, _move: function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.isFirstItem() && /^previous/.test( direction ) || this.menu.isLastItem() && /^next/.test( direction ) ) { if ( !this.isMultiLine ) { this._value( this.term ); } this.menu.blur(); return; } this.menu[ direction ]( event ); }, widget: function() { return this.menu.element; }, _value: function() { return this.valueMethod.apply( this.element, arguments ); }, _keyEvent: function( keyEvent, event ) { if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { this._move( keyEvent, event ); // prevents moving cursor to beginning/end of the text field in some browsers event.preventDefault(); } } }); $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); }, filter: function( array, term ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" ); return $.grep( array, function( value ) { return matcher.test( value.label || value.value || value ); }); } }); // live region extension, adding a `messages` option // NOTE: This is an experimental API. We are still investigating // a full solution for string manipulation and internationalization. $.widget( "ui.autocomplete", $.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function( amount ) { return amount + ( amount > 1 ? " results are" : " result is" ) + " available, use up and down arrow keys to navigate."; } } }, __response: function( content ) { var message; this._superApply( arguments ); if ( this.options.disabled || this.cancelSearch ) { return; } if ( content && content.length ) { message = this.options.messages.results( content.length ); } else { message = this.options.messages.noResults; } this.liveRegion.children().hide(); $( "<div>" ).text( message ).appendTo( this.liveRegion ); } }); var autocomplete = $.ui.autocomplete; /*! * jQuery UI Button 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/button/ */ var lastActive, baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", formResetHandler = function() { var form = $( this ); setTimeout(function() { form.find( ":ui-button" ).button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { name = name.replace( /'/g, "\\'" ); if ( form ) { radios = $( form ).find( "[name='" + name + "'][type=radio]" ); } else { radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument ) .filter(function() { return !this.form; }); } } return radios; }; $.widget( "ui.button", { version: "1.11.0", defaultElement: "<button>", options: { disabled: null, text: true, label: null, icons: { primary: null, secondary: null } }, _create: function() { this.element.closest( "form" ) .unbind( "reset" + this.eventNamespace ) .bind( "reset" + this.eventNamespace, formResetHandler ); if ( typeof this.options.disabled !== "boolean" ) { this.options.disabled = !!this.element.prop( "disabled" ); } else { this.element.prop( "disabled", this.options.disabled ); } this._determineButtonType(); this.hasTitle = !!this.buttonElement.attr( "title" ); var that = this, options = this.options, toggleButton = this.type === "checkbox" || this.type === "radio", activeClass = !toggleButton ? "ui-state-active" : ""; if ( options.label === null ) { options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); } this._hoverable( this.buttonElement ); this.buttonElement .addClass( baseClasses ) .attr( "role", "button" ) .bind( "mouseenter" + this.eventNamespace, function() { if ( options.disabled ) { return; } if ( this === lastActive ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "mouseleave" + this.eventNamespace, function() { if ( options.disabled ) { return; } $( this ).removeClass( activeClass ); }) .bind( "click" + this.eventNamespace, function( event ) { if ( options.disabled ) { event.preventDefault(); event.stopImmediatePropagation(); } }); // Can't use _focusable() because the element that receives focus // and the element that gets the ui-state-focus class are different this._on({ focus: function() { this.buttonElement.addClass( "ui-state-focus" ); }, blur: function() { this.buttonElement.removeClass( "ui-state-focus" ); } }); if ( toggleButton ) { this.element.bind( "change" + this.eventNamespace, function() { that.refresh(); }); } if ( this.type === "checkbox" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } }); } else if ( this.type === "radio" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", "true" ); var radio = that.element[ 0 ]; radioGroup( radio ) .not( radio ) .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); }); } else { this.buttonElement .bind( "mousedown" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); lastActive = this; that.document.one( "mouseup", function() { lastActive = null; }); }) .bind( "mouseup" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).removeClass( "ui-state-active" ); }) .bind( "keydown" + this.eventNamespace, function(event) { if ( options.disabled ) { return false; } if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { $( this ).addClass( "ui-state-active" ); } }) // see #8559, we bind to blur here in case the button element loses // focus between keydown and keyup, it would be left in an "active" state .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() { $( this ).removeClass( "ui-state-active" ); }); if ( this.buttonElement.is("a") ) { this.buttonElement.keyup(function(event) { if ( event.keyCode === $.ui.keyCode.SPACE ) { // TODO pass through original event correctly (just as 2nd argument doesn't work) $( this ).click(); } }); } } this._setOption( "disabled", options.disabled ); this._resetButton(); }, _determineButtonType: function() { var ancestor, labelSelector, checked; if ( this.element.is("[type=checkbox]") ) { this.type = "checkbox"; } else if ( this.element.is("[type=radio]") ) { this.type = "radio"; } else if ( this.element.is("input") ) { this.type = "input"; } else { this.type = "button"; } if ( this.type === "checkbox" || this.type === "radio" ) { // we don't search against the document in case the element // is disconnected from the DOM ancestor = this.element.parents().last(); labelSelector = "label[for='" + this.element.attr("id") + "']"; this.buttonElement = ancestor.find( labelSelector ); if ( !this.buttonElement.length ) { ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); this.buttonElement = ancestor.filter( labelSelector ); if ( !this.buttonElement.length ) { this.buttonElement = ancestor.find( labelSelector ); } } this.element.addClass( "ui-helper-hidden-accessible" ); checked = this.element.is( ":checked" ); if ( checked ) { this.buttonElement.addClass( "ui-state-active" ); } this.buttonElement.prop( "aria-pressed", checked ); } else { this.buttonElement = this.element; } }, widget: function() { return this.buttonElement; }, _destroy: function() { this.element .removeClass( "ui-helper-hidden-accessible" ); this.buttonElement .removeClass( baseClasses + " ui-state-active " + typeClasses ) .removeAttr( "role" ) .removeAttr( "aria-pressed" ) .html( this.buttonElement.find(".ui-button-text").html() ); if ( !this.hasTitle ) { this.buttonElement.removeAttr( "title" ); } }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); if ( value ) { if ( this.type === "checkbox" || this.type === "radio" ) { this.buttonElement.removeClass( "ui-state-focus" ); } else { this.buttonElement.removeClass( "ui-state-focus ui-state-active" ); } } return; } this._resetButton(); }, refresh: function() { //See #8237 & #8828 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); if ( isDisabled !== this.options.disabled ) { this._setOption( "disabled", isDisabled ); } if ( this.type === "radio" ) { radioGroup( this.element[0] ).each(function() { if ( $( this ).is( ":checked" ) ) { $( this ).button( "widget" ) .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { $( this ).button( "widget" ) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } }); } else if ( this.type === "checkbox" ) { if ( this.element.is( ":checked" ) ) { this.buttonElement .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { this.buttonElement .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } } }, _resetButton: function() { if ( this.type === "input" ) { if ( this.options.label ) { this.element.val( this.options.label ); } return; } var buttonElement = this.buttonElement.removeClass( typeClasses ), buttonText = $( "<span></span>", this.document[0] ) .addClass( "ui-button-text" ) .html( this.options.label ) .appendTo( buttonElement.empty() ) .text(), icons = this.options.icons, multipleIcons = icons.primary && icons.secondary, buttonClasses = []; if ( icons.primary || icons.secondary ) { if ( this.options.text ) { buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); } if ( icons.primary ) { buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); } if ( icons.secondary ) { buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); } if ( !this.options.text ) { buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); if ( !this.hasTitle ) { buttonElement.attr( "title", $.trim( buttonText ) ); } } } else { buttonClasses.push( "ui-button-text-only" ); } buttonElement.addClass( buttonClasses.join( " " ) ); } }); $.widget( "ui.buttonset", { version: "1.11.0", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)" }, _create: function() { this.element.addClass( "ui-buttonset" ); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { if ( key === "disabled" ) { this.buttons.button( "option", key, value ); } this._super( key, value ); }, refresh: function() { var rtl = this.element.css( "direction" ) === "rtl", allButtons = this.element.find( this.options.items ), existingButtons = allButtons.filter( ":ui-button" ); // Initialize new buttons allButtons.not( ":ui-button" ).button(); // Refresh existing buttons existingButtons.button( "refresh" ); this.buttons = allButtons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) .filter( ":first" ) .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) .end() .filter( ":last" ) .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) .end() .end(); }, _destroy: function() { this.element.removeClass( "ui-buttonset" ); this.buttons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-left ui-corner-right" ) .end() .button( "destroy" ); } }); var button = $.ui.button; /*! * jQuery UI Datepicker 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/datepicker/ */ $.extend($.ui, { datepicker: { version: "1.11.0" } }); var datepicker_instActive; function datepicker_getZindex( elem ) { var position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } return 0; } /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.regional.en = $.extend( true, {}, this.regional[ "" ]); this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en ); this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { datepicker_extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, "datepicker", inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, "datepicker", inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], "datepicker", inst); } datepicker_extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], "datepicker", inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, "datepicker"); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, "datepicker"); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); datepicker_extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } datepicker_extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 ); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) datepicker_instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); inst.dpDiv.find("." + this._dayOverClass + " a"); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17; inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, "datepicker"))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), digits = new RegExp("^\\d{1," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function datepicker_bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate(selector, "mouseover", function(){ if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? dpDiv.parent()[0] : datepicker_instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } }); } /* jQuery extend now ignores nulls! */ function datepicker_extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.11.0"; var datepicker = $.datepicker; /*! * jQuery UI Dialog 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/dialog/ */ var dialog = $.widget( "ui.dialog", { version: "1.11.0", options: { appendTo: "body", autoOpen: true, buttons: [], closeOnEscape: true, closeText: "Close", dialogClass: "", draggable: true, hide: null, height: "auto", maxHeight: null, maxWidth: null, minHeight: 150, minWidth: 150, modal: false, position: { my: "center", at: "center", of: window, collision: "fit", // Ensure the titlebar is always visible using: function( pos ) { var topOffset = $( this ).css( pos ).offset().top; if ( topOffset < 0 ) { $( this ).css( "top", pos.top - topOffset ); } } }, resizable: true, show: null, title: null, width: 300, // callbacks beforeClose: null, close: null, drag: null, dragStart: null, dragStop: null, focus: null, open: null, resize: null, resizeStart: null, resizeStop: null }, sizeRelatedOptions: { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions: { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, _create: function() { this.originalCss = { display: this.element[ 0 ].style.display, width: this.element[ 0 ].style.width, minHeight: this.element[ 0 ].style.minHeight, maxHeight: this.element[ 0 ].style.maxHeight, height: this.element[ 0 ].style.height }; this.originalPosition = { parent: this.element.parent(), index: this.element.parent().children().index( this.element ) }; this.originalTitle = this.element.attr( "title" ); this.options.title = this.options.title || this.originalTitle; this._createWrapper(); this.element .show() .removeAttr( "title" ) .addClass( "ui-dialog-content ui-widget-content" ) .appendTo( this.uiDialog ); this._createTitlebar(); this._createButtonPane(); if ( this.options.draggable && $.fn.draggable ) { this._makeDraggable(); } if ( this.options.resizable && $.fn.resizable ) { this._makeResizable(); } this._isOpen = false; this._trackFocus(); }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element && (element.jquery || element.nodeType) ) { return $( element ); } return this.document.find( element || "body" ).eq( 0 ); }, _destroy: function() { var next, originalPosition = this.originalPosition; this._destroyOverlay(); this.element .removeUniqueId() .removeClass( "ui-dialog-content ui-widget-content" ) .css( this.originalCss ) // Without detaching first, the following becomes really slow .detach(); this.uiDialog.stop( true, true ).remove(); if ( this.originalTitle ) { this.element.attr( "title", this.originalTitle ); } next = originalPosition.parent.children().eq( originalPosition.index ); // Don't try to place the dialog next to itself (#8613) if ( next.length && next[ 0 ] !== this.element[ 0 ] ) { next.before( this.element ); } else { originalPosition.parent.append( this.element ); } }, widget: function() { return this.uiDialog; }, disable: $.noop, enable: $.noop, close: function( event ) { var activeElement, that = this; if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) { return; } this._isOpen = false; this._focusedElement = null; this._destroyOverlay(); this._untrackInstance(); if ( !this.opener.filter( ":focusable" ).focus().length ) { // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { activeElement = this.document[ 0 ].activeElement; // Support: IE9, IE10 // If the <body> is blurred, IE will switch windows, see #4520 if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) { // Hiding a focused element doesn't trigger blur in WebKit // so in case we have nothing to focus on, explicitly blur the active element // https://bugs.webkit.org/show_bug.cgi?id=47182 $( activeElement ).blur(); } } catch ( error ) {} } this._hide( this.uiDialog, this.options.hide, function() { that._trigger( "close", event ); }); }, isOpen: function() { return this._isOpen; }, moveToTop: function() { this._moveToTop(); }, _moveToTop: function( event, silent ) { var moved = false, zIndicies = this.uiDialog.siblings( ".ui-front:visible" ).map(function() { return +$( this ).css( "z-index" ); }).get(), zIndexMax = Math.max.apply( null, zIndicies ); if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) { this.uiDialog.css( "z-index", zIndexMax + 1 ); moved = true; } if ( moved && !silent ) { this._trigger( "focus", event ); } return moved; }, open: function() { var that = this; if ( this._isOpen ) { if ( this._moveToTop() ) { this._focusTabbable(); } return; } this._isOpen = true; this.opener = $( this.document[ 0 ].activeElement ); this._size(); this._position(); this._createOverlay(); this._moveToTop( null, true ); this._show( this.uiDialog, this.options.show, function() { that._focusTabbable(); that._trigger( "focus" ); }); this._trigger( "open" ); }, _focusTabbable: function() { // Set focus to the first match: // 1. An element that was focused previously // 2. First element inside the dialog matching [autofocus] // 3. Tabbable element inside the content element // 4. Tabbable element inside the buttonpane // 5. The close button // 6. The dialog itself var hasFocus = this._focusedElement; if ( !hasFocus ) { hasFocus = this.element.find( "[autofocus]" ); } if ( !hasFocus.length ) { hasFocus = this.element.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogButtonPane.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialog; } hasFocus.eq( 0 ).focus(); }, _keepFocus: function( event ) { function checkFocus() { var activeElement = this.document[0].activeElement, isActive = this.uiDialog[0] === activeElement || $.contains( this.uiDialog[0], activeElement ); if ( !isActive ) { this._focusTabbable(); } } event.preventDefault(); checkFocus.call( this ); // support: IE // IE <= 8 doesn't prevent moving focus even with event.preventDefault() // so we check again later this._delay( checkFocus ); }, _createWrapper: function() { this.uiDialog = $("<div>") .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " + this.options.dialogClass ) .hide() .attr({ // Setting tabIndex makes the div focusable tabIndex: -1, role: "dialog" }) .appendTo( this._appendTo() ); this._on( this.uiDialog, { keydown: function( event ) { if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { event.preventDefault(); this.close( event ); return; } // prevent tabbing out of dialogs if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) { return; } var tabbables = this.uiDialog.find( ":tabbable" ), first = tabbables.filter( ":first" ), last = tabbables.filter( ":last" ); if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) { this._delay(function() { first.focus(); }); event.preventDefault(); } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) { this._delay(function() { last.focus(); }); event.preventDefault(); } }, mousedown: function( event ) { if ( this._moveToTop( event ) ) { this._focusTabbable(); } } }); // We assume that any existing aria-describedby attribute means // that the dialog content is marked up properly // otherwise we brute force the content as the description if ( !this.element.find( "[aria-describedby]" ).length ) { this.uiDialog.attr({ "aria-describedby": this.element.uniqueId().attr( "id" ) }); } }, _createTitlebar: function() { var uiDialogTitle; this.uiDialogTitlebar = $( "<div>" ) .addClass( "ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" ) .prependTo( this.uiDialog ); this._on( this.uiDialogTitlebar, { mousedown: function( event ) { // Don't prevent click on close button (#8838) // Focusing a dialog that is partially scrolled out of view // causes the browser to scroll it into view, preventing the click event if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) { // Dialog isn't getting focus when dragging (#8063) this.uiDialog.focus(); } } }); // support: IE // Use type="button" to prevent enter keypresses in textboxes from closing the // dialog in IE (#9312) this.uiDialogTitlebarClose = $( "<button type='button'></button>" ) .button({ label: this.options.closeText, icons: { primary: "ui-icon-closethick" }, text: false }) .addClass( "ui-dialog-titlebar-close" ) .appendTo( this.uiDialogTitlebar ); this._on( this.uiDialogTitlebarClose, { click: function( event ) { event.preventDefault(); this.close( event ); } }); uiDialogTitle = $( "<span>" ) .uniqueId() .addClass( "ui-dialog-title" ) .prependTo( this.uiDialogTitlebar ); this._title( uiDialogTitle ); this.uiDialog.attr({ "aria-labelledby": uiDialogTitle.attr( "id" ) }); }, _title: function( title ) { if ( !this.options.title ) { title.html( "&#160;" ); } title.text( this.options.title ); }, _createButtonPane: function() { this.uiDialogButtonPane = $( "<div>" ) .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" ); this.uiButtonSet = $( "<div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( this.uiDialogButtonPane ); this._createButtons(); }, _createButtons: function() { var that = this, buttons = this.options.buttons; // if we already have a button pane, remove it this.uiDialogButtonPane.remove(); this.uiButtonSet.empty(); if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) { this.uiDialog.removeClass( "ui-dialog-buttons" ); return; } $.each( buttons, function( name, props ) { var click, buttonOptions; props = $.isFunction( props ) ? { click: props, text: name } : props; // Default to a non-submitting button props = $.extend( { type: "button" }, props ); // Change the context for the click callback to be the main element click = props.click; props.click = function() { click.apply( that.element[ 0 ], arguments ); }; buttonOptions = { icons: props.icons, text: props.showText }; delete props.icons; delete props.showText; $( "<button></button>", props ) .button( buttonOptions ) .appendTo( that.uiButtonSet ); }); this.uiDialog.addClass( "ui-dialog-buttons" ); this.uiDialogButtonPane.appendTo( this.uiDialog ); }, _makeDraggable: function() { var that = this, options = this.options; function filteredUi( ui ) { return { position: ui.position, offset: ui.offset }; } this.uiDialog.draggable({ cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", handle: ".ui-dialog-titlebar", containment: "document", start: function( event, ui ) { $( this ).addClass( "ui-dialog-dragging" ); that._blockFrames(); that._trigger( "dragStart", event, filteredUi( ui ) ); }, drag: function( event, ui ) { that._trigger( "drag", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var left = ui.offset.left - that.document.scrollLeft(), top = ui.offset.top - that.document.scrollTop(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-dragging" ); that._unblockFrames(); that._trigger( "dragStop", event, filteredUi( ui ) ); } }); }, _makeResizable: function() { var that = this, options = this.options, handles = options.resizable, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = this.uiDialog.css("position"), resizeHandles = typeof handles === "string" ? handles : "n,e,s,w,se,sw,ne,nw"; function filteredUi( ui ) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } this.uiDialog.resizable({ cancel: ".ui-dialog-content", containment: "document", alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: this._minHeight(), handles: resizeHandles, start: function( event, ui ) { $( this ).addClass( "ui-dialog-resizing" ); that._blockFrames(); that._trigger( "resizeStart", event, filteredUi( ui ) ); }, resize: function( event, ui ) { that._trigger( "resize", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var offset = that.uiDialog.offset(), left = offset.left - that.document.scrollLeft(), top = offset.top - that.document.scrollTop(); options.height = that.uiDialog.height(); options.width = that.uiDialog.width(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-resizing" ); that._unblockFrames(); that._trigger( "resizeStop", event, filteredUi( ui ) ); } }) .css( "position", position ); }, _trackFocus: function() { this._on( this.widget(), { "focusin": function( event ) { this._untrackInstance(); this._trackingInstances().unshift( this ); this._focusedElement = $( event.target ); } }); }, _untrackInstance: function() { var instances = this._trackingInstances(), exists = $.inArray( this, instances ); if ( exists !== -1 ) { instances.splice( exists, 1 ); } }, _trackingInstances: function() { var instances = this.document.data( "ui-dialog-instances" ); if ( !instances ) { instances = []; this.document.data( "ui-dialog-instances", instances ); } return instances; }, _minHeight: function() { var options = this.options; return options.height === "auto" ? options.minHeight : Math.min( options.minHeight, options.height ); }, _position: function() { // Need to show the dialog to get the actual offset in the position plugin var isVisible = this.uiDialog.is( ":visible" ); if ( !isVisible ) { this.uiDialog.show(); } this.uiDialog.position( this.options.position ); if ( !isVisible ) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var that = this, resize = false, resizableOptions = {}; $.each( options, function( key, value ) { that._setOption( key, value ); if ( key in that.sizeRelatedOptions ) { resize = true; } if ( key in that.resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); this._position(); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function( key, value ) { var isDraggable, isResizable, uiDialog = this.uiDialog; if ( key === "dialogClass" ) { uiDialog .removeClass( this.options.dialogClass ) .addClass( value ); } if ( key === "disabled" ) { return; } this._super( key, value ); if ( key === "appendTo" ) { this.uiDialog.appendTo( this._appendTo() ); } if ( key === "buttons" ) { this._createButtons(); } if ( key === "closeText" ) { this.uiDialogTitlebarClose.button({ // Ensure that we always pass a string label: "" + value }); } if ( key === "draggable" ) { isDraggable = uiDialog.is( ":data(ui-draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { this._makeDraggable(); } } if ( key === "position" ) { this._position(); } if ( key === "resizable" ) { // currently resizable, becoming non-resizable isResizable = uiDialog.is( ":data(ui-resizable)" ); if ( isResizable && !value ) { uiDialog.resizable( "destroy" ); } // currently resizable, changing handles if ( isResizable && typeof value === "string" ) { uiDialog.resizable( "option", "handles", value ); } // currently non-resizable, becoming resizable if ( !isResizable && value !== false ) { this._makeResizable(); } } if ( key === "title" ) { this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) ); } }, _size: function() { // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content // divs will both have width and height set, so we need to reset them var nonContentHeight, minContentHeight, maxContentHeight, options = this.options; // Reset content sizing this.element.show().css({ width: "auto", minHeight: 0, maxHeight: "none", height: 0 }); if ( options.minWidth > options.width ) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: "auto", width: options.width }) .outerHeight(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); maxContentHeight = typeof options.maxHeight === "number" ? Math.max( 0, options.maxHeight - nonContentHeight ) : "none"; if ( options.height === "auto" ) { this.element.css({ minHeight: minContentHeight, maxHeight: maxContentHeight, height: "auto" }); } else { this.element.height( Math.max( 0, options.height - nonContentHeight ) ); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); } }, _blockFrames: function() { this.iframeBlocks = this.document.find( "iframe" ).map(function() { var iframe = $( this ); return $( "<div>" ) .css({ position: "absolute", width: iframe.outerWidth(), height: iframe.outerHeight() }) .appendTo( iframe.parent() ) .offset( iframe.offset() )[0]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _allowInteraction: function( event ) { if ( $( event.target ).closest( ".ui-dialog" ).length ) { return true; } // TODO: Remove hack when datepicker implements // the .ui-front logic (#8989) return !!$( event.target ).closest( ".ui-datepicker" ).length; }, _createOverlay: function() { if ( !this.options.modal ) { return; } // We use a delay in case the overlay is created from an // event that we're going to be cancelling (#2804) var isOpening = true; this._delay(function() { isOpening = false; }); if ( !this.document.data( "ui-dialog-overlays" ) ) { // Prevent use of anchors and inputs // Using _on() for an event handler shared across many instances is // safe because the dialogs stack and must be closed in reverse order this._on( this.document, { focusin: function( event ) { if ( isOpening ) { return; } if ( !this._allowInteraction( event ) ) { event.preventDefault(); this._trackingInstances()[ 0 ]._focusTabbable(); } } }); } this.overlay = $( "<div>" ) .addClass( "ui-widget-overlay ui-front" ) .appendTo( this._appendTo() ); this._on( this.overlay, { mousedown: "_keepFocus" }); this.document.data( "ui-dialog-overlays", (this.document.data( "ui-dialog-overlays" ) || 0) + 1 ); }, _destroyOverlay: function() { if ( !this.options.modal ) { return; } if ( this.overlay ) { var overlays = this.document.data( "ui-dialog-overlays" ) - 1; if ( !overlays ) { this.document .unbind( "focusin" ) .removeData( "ui-dialog-overlays" ); } else { this.document.data( "ui-dialog-overlays", overlays ); } this.overlay.remove(); this.overlay = null; } } }); /*! * jQuery UI Progressbar 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/progressbar/ */ var progressbar = $.widget( "ui.progressbar", { version: "1.11.0", options: { max: 100, value: 0, change: null, complete: null }, min: 0, _create: function() { // Constrain initial value this.oldValue = this.options.value = this._constrainedValue(); this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ // Only set static values, aria-valuenow and aria-valuemax are // set inside _refreshValue() role: "progressbar", "aria-valuemin": this.min }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this.options.value; } this.options.value = this._constrainedValue( newValue ); this._refreshValue(); }, _constrainedValue: function( newValue ) { if ( newValue === undefined ) { newValue = this.options.value; } this.indeterminate = newValue === false; // sanitize value if ( typeof newValue !== "number" ) { newValue = 0; } return this.indeterminate ? false : Math.min( this.options.max, Math.max( this.min, newValue ) ); }, _setOptions: function( options ) { // Ensure "value" option is set after other values (like max) var value = options.value; delete options.value; this._super( options ); this.options.value = this._constrainedValue( value ); this._refreshValue(); }, _setOption: function( key, value ) { if ( key === "max" ) { // Don't allow a max less than min value = Math.max( this.min, value ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, _percentage: function() { return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); }, _refreshValue: function() { var value = this.options.value, percentage = this._percentage(); this.valueDiv .toggle( this.indeterminate || value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); if ( this.indeterminate ) { this.element.removeAttr( "aria-valuenow" ); if ( !this.overlayDiv ) { this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); } } else { this.element.attr({ "aria-valuemax": this.options.max, "aria-valuenow": value }); if ( this.overlayDiv ) { this.overlayDiv.remove(); this.overlayDiv = null; } } if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } if ( value === this.options.max ) { this._trigger( "complete" ); } } }); /*! * jQuery UI Selectmenu 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/selectmenu */ var selectmenu = $.widget( "ui.selectmenu", { version: "1.11.0", defaultElement: "<select>", options: { appendTo: null, disabled: null, icons: { button: "ui-icon-triangle-1-s" }, position: { my: "left top", at: "left bottom", collision: "none" }, width: null, // callbacks change: null, close: null, focus: null, open: null, select: null }, _create: function() { var selectmenuId = this.element.uniqueId().attr( "id" ); this.ids = { element: selectmenuId, button: selectmenuId + "-button", menu: selectmenuId + "-menu" }; this._drawButton(); this._drawMenu(); if ( this.options.disabled ) { this.disable(); } }, _drawButton: function() { var that = this, tabindex = this.element.attr( "tabindex" ); // Associate existing label with the new button this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button ); this._on( this.label, { click: function( event ) { this.button.focus(); event.preventDefault(); } }); // Hide original select element this.element.hide(); // Create button this.button = $( "<span>", { "class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all", tabindex: tabindex || this.options.disabled ? -1 : 0, id: this.ids.button, role: "combobox", "aria-expanded": "false", "aria-autocomplete": "list", "aria-owns": this.ids.menu, "aria-haspopup": "true" }) .insertAfter( this.element ); $( "<span>", { "class": "ui-icon " + this.options.icons.button }) .prependTo( this.button ); this.buttonText = $( "<span>", { "class": "ui-selectmenu-text" }) .appendTo( this.button ); this._setText( this.buttonText, this.element.find( "option:selected" ).text() ); this._setOption( "width", this.options.width ); this._on( this.button, this._buttonEvents ); this.button.one( "focusin", function() { // Delay rendering the menu items until the button receives focus. // The menu may have already been rendered via a programmatic open. if ( !that.menuItems ) { that._refreshMenu(); } }); this._hoverable( this.button ); this._focusable( this.button ); }, _drawMenu: function() { var that = this; // Create menu this.menu = $( "<ul>", { "aria-hidden": "true", "aria-labelledby": this.ids.button, id: this.ids.menu }); // Wrap menu this.menuWrap = $( "<div>", { "class": "ui-selectmenu-menu ui-front" }) .append( this.menu ) .appendTo( this._appendTo() ); // Initialize menu widget this.menuInstance = this.menu .menu({ role: "listbox", select: function( event, ui ) { event.preventDefault(); that._select( ui.item.data( "ui-selectmenu-item" ), event ); }, focus: function( event, ui ) { var item = ui.item.data( "ui-selectmenu-item" ); // Prevent inital focus from firing and check if its a newly focused item if ( that.focusIndex != null && item.index !== that.focusIndex ) { that._trigger( "focus", event, { item: item } ); if ( !that.isOpen ) { that._select( item, event ); } } that.focusIndex = item.index; that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) ); } }) .menu( "instance" ); // Adjust menu styles to dropdown this.menu .addClass( "ui-corner-bottom" ) .removeClass( "ui-corner-all" ); // Don't close the menu on mouseleave this.menuInstance._off( this.menu, "mouseleave" ); // Cancel the menu's collapseAll on document click this.menuInstance._closeOnDocumentClick = function() { return false; }; // Selects often contain empty items, but never contain dividers this.menuInstance._isDivider = function() { return false; }; }, refresh: function() { this._refreshMenu(); this._setText( this.buttonText, this._getSelectedItem().text() ); this._setOption( "width", this.options.width ); }, _refreshMenu: function() { this.menu.empty(); var item, options = this.element.find( "option" ); if ( !options.length ) { return; } this._parseOptions( options ); this._renderMenu( this.menu, this.items ); this.menuInstance.refresh(); this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ); item = this._getSelectedItem(); // Update the menu to have the correct item focused this.menuInstance.focus( null, item ); this._setAria( item.data( "ui-selectmenu-item" ) ); // Set disabled state this._setOption( "disabled", this.element.prop( "disabled" ) ); }, open: function( event ) { if ( this.options.disabled ) { return; } // If this is the first time the menu is being opened, render the items if ( !this.menuItems ) { this._refreshMenu(); } else { // Menu clears focus on close, reset focus to selected item this.menu.find( ".ui-state-focus" ).removeClass( "ui-state-focus" ); this.menuInstance.focus( null, this._getSelectedItem() ); } this.isOpen = true; this._toggleAttr(); this._resizeMenu(); this._position(); this._on( this.document, this._documentClick ); this._trigger( "open", event ); }, _position: function() { this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) ); }, close: function( event ) { if ( !this.isOpen ) { return; } this.isOpen = false; this._toggleAttr(); this._off( this.document ); this._trigger( "close", event ); }, widget: function() { return this.button; }, menuWidget: function() { return this.menu; }, _renderMenu: function( ul, items ) { var that = this, currentOptgroup = ""; $.each( items, function( index, item ) { if ( item.optgroup !== currentOptgroup ) { $( "<li>", { "class": "ui-selectmenu-optgroup ui-menu-divider" + ( item.element.parent( "optgroup" ).prop( "disabled" ) ? " ui-state-disabled" : "" ), text: item.optgroup }) .appendTo( ul ); currentOptgroup = item.optgroup; } that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-selectmenu-item", item ); }, _renderItem: function( ul, item ) { var li = $( "<li>" ); if ( item.disabled ) { li.addClass( "ui-state-disabled" ); } this._setText( li, item.label ); return li.appendTo( ul ); }, _setText: function( element, value ) { if ( value ) { element.text( value ); } else { element.html( "&#160;" ); } }, _move: function( direction, event ) { var item, next, filter = ".ui-menu-item"; if ( this.isOpen ) { item = this.menuItems.eq( this.focusIndex ); } else { item = this.menuItems.eq( this.element[ 0 ].selectedIndex ); filter += ":not(.ui-state-disabled)"; } if ( direction === "first" || direction === "last" ) { next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 ); } else { next = item[ direction + "All" ]( filter ).eq( 0 ); } if ( next.length ) { this.menuInstance.focus( event, next ); } }, _getSelectedItem: function() { return this.menuItems.eq( this.element[ 0 ].selectedIndex ); }, _toggle: function( event ) { this[ this.isOpen ? "close" : "open" ]( event ); }, _documentClick: { mousedown: function( event ) { if ( !this.isOpen ) { return; } if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" + this.ids.button ).length ) { this.close( event ); } } }, _buttonEvents: { click: "_toggle", keydown: function( event ) { var preventDefault = true; switch ( event.keyCode ) { case $.ui.keyCode.TAB: case $.ui.keyCode.ESCAPE: this.close( event ); preventDefault = false; break; case $.ui.keyCode.ENTER: if ( this.isOpen ) { this._selectFocusedItem( event ); } break; case $.ui.keyCode.UP: if ( event.altKey ) { this._toggle( event ); } else { this._move( "prev", event ); } break; case $.ui.keyCode.DOWN: if ( event.altKey ) { this._toggle( event ); } else { this._move( "next", event ); } break; case $.ui.keyCode.SPACE: if ( this.isOpen ) { this._selectFocusedItem( event ); } else { this._toggle( event ); } break; case $.ui.keyCode.LEFT: this._move( "prev", event ); break; case $.ui.keyCode.RIGHT: this._move( "next", event ); break; case $.ui.keyCode.HOME: case $.ui.keyCode.PAGE_UP: this._move( "first", event ); break; case $.ui.keyCode.END: case $.ui.keyCode.PAGE_DOWN: this._move( "last", event ); break; default: this.menu.trigger( event ); preventDefault = false; } if ( preventDefault ) { event.preventDefault(); } } }, _selectFocusedItem: function( event ) { var item = this.menuItems.eq( this.focusIndex ); if ( !item.hasClass( "ui-state-disabled" ) ) { this._select( item.data( "ui-selectmenu-item" ), event ); } }, _select: function( item, event ) { var oldIndex = this.element[ 0 ].selectedIndex; // Change native select element this.element[ 0 ].selectedIndex = item.index; this._setText( this.buttonText, item.label ); this._setAria( item ); this._trigger( "select", event, { item: item } ); if ( item.index !== oldIndex ) { this._trigger( "change", event, { item: item } ); } this.close( event ); }, _setAria: function( item ) { var id = this.menuItems.eq( item.index ).attr( "id" ); this.button.attr({ "aria-labelledby": id, "aria-activedescendant": id }); this.menu.attr( "aria-activedescendant", id ); }, _setOption: function( key, value ) { if ( key === "icons" ) { this.button.find( "span.ui-icon" ) .removeClass( this.options.icons.button ) .addClass( value.button ); } this._super( key, value ); if ( key === "appendTo" ) { this.menuWrap.appendTo( this._appendTo() ); } if ( key === "disabled" ) { this.menuInstance.option( "disabled", value ); this.button .toggleClass( "ui-state-disabled", value ) .attr( "aria-disabled", value ); this.element.prop( "disabled", value ); if ( value ) { this.button.attr( "tabindex", -1 ); this.close(); } else { this.button.attr( "tabindex", 0 ); } } if ( key === "width" ) { if ( !value ) { value = this.element.outerWidth(); } this.button.outerWidth( value ); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _toggleAttr: function() { this.button .toggleClass( "ui-corner-top", this.isOpen ) .toggleClass( "ui-corner-all", !this.isOpen ) .attr( "aria-expanded", this.isOpen ); this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen ); this.menu.attr( "aria-hidden", !this.isOpen ); }, _resizeMenu: function() { this.menu.outerWidth( Math.max( this.button.outerWidth(), // support: IE10 // IE10 wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping this.menu.width( "" ).outerWidth() + 1 ) ); }, _getCreateOptions: function() { return { disabled: this.element.prop( "disabled" ) }; }, _parseOptions: function( options ) { var data = []; options.each(function( index, item ) { var option = $( item ), optgroup = option.parent( "optgroup" ); data.push({ element: option, index: index, value: option.attr( "value" ), label: option.text(), optgroup: optgroup.attr( "label" ) || "", disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" ) }); }); this.items = data; }, _destroy: function() { this.menuWrap.remove(); this.button.remove(); this.element.show(); this.element.removeUniqueId(); this.label.attr( "for", this.ids.element ); } }); /*! * jQuery UI Slider 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/slider/ */ var slider = $.widget( "ui.slider", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, // number of pages in a slider // (how many times can you page up/down to go through the whole range) numPages: 5, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { if ( this.range ) { this.range.remove(); } this.range = null; } }, _setupEvents: function() { this._off( this.handles ); this._on( this.handles, this._handleEvents ); this._hoverable( this.handles ); this._focusable( this.handles ); }, _destroy: function() { this.handles.remove(); if ( this.range ) { this.range.remove(); } this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length - 1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } if ( key === "disabled" ) { this.element.toggleClass( "ui-state-disabled", !!value ); } this._super( key, value ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); /*! * jQuery UI Spinner 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/spinner/ */ function spinner_modifier( fn ) { return function() { var previous = this.element.val(); fn.apply( this, arguments ); this._refresh(); if ( previous !== this.element.val() ) { this._trigger( "change" ); } }; } var spinner = $.widget( "ui.spinner", { version: "1.11.0", defaultElement: "<input>", widgetEventPrefix: "spin", options: { culture: null, icons: { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }, incremental: true, max: null, min: null, numberFormat: null, page: 10, step: 1, change: null, spin: null, start: null, stop: null }, _create: function() { // handle string values that need to be parsed this._setOption( "max", this.options.max ); this._setOption( "min", this.options.min ); this._setOption( "step", this.options.step ); // Only format if there is a value, prevents the field from being marked // as invalid in Firefox, see #9573. if ( this.value() !== "" ) { // Format the value, but don't constrain. this._value( this.element.val(), true ); } this._draw(); this._on( this._events ); this._refresh(); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _getCreateOptions: function() { var options = {}, element = this.element; $.each( [ "min", "max", "step" ], function( i, option ) { var value = element.attr( option ); if ( value !== undefined && value.length ) { options[ option ] = value; } }); return options; }, _events: { keydown: function( event ) { if ( this._start( event ) && this._keydown( event ) ) { event.preventDefault(); } }, keyup: "_stop", focus: function() { this.previous = this.element.val(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } this._stop(); this._refresh(); if ( this.previous !== this.element.val() ) { this._trigger( "change", event ); } }, mousewheel: function( event, delta ) { if ( !delta ) { return; } if ( !this.spinning && !this._start( event ) ) { return false; } this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); clearTimeout( this.mousewheelTimer ); this.mousewheelTimer = this._delay(function() { if ( this.spinning ) { this._stop( event ); } }, 100 ); event.preventDefault(); }, "mousedown .ui-spinner-button": function( event ) { var previous; // We never want the buttons to have focus; whenever the user is // interacting with the spinner, the focus should be on the input. // If the input is focused then this.previous is properly set from // when the input first received focus. If the input is not focused // then we need to set this.previous based on the value before spinning. previous = this.element[0] === this.document[0].activeElement ? this.previous : this.element.val(); function checkFocus() { var isActive = this.element[0] === this.document[0].activeElement; if ( !isActive ) { this.element.focus(); this.previous = previous; // support: IE // IE sets focus asynchronously, so we need to check if focus // moved off of the input because the user clicked on the button. this._delay(function() { this.previous = previous; }); } } // ensure focus is on (or stays on) the text field event.preventDefault(); checkFocus.call( this ); // support: IE // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event // and check (again) if focus moved off of the input. this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; checkFocus.call( this ); }); if ( this._start( event ) === false ) { return; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, "mouseup .ui-spinner-button": "_stop", "mouseenter .ui-spinner-button": function( event ) { // button will add ui-state-active if mouse was down while mouseleave and kept down if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { return; } if ( this._start( event ) === false ) { return false; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, // TODO: do we really want to consider this a stop? // shouldn't we just stop the repeater and wait until mouseup before // we trigger the stop event? "mouseleave .ui-spinner-button": "_stop" }, _draw: function() { var uiSpinner = this.uiSpinner = this.element .addClass( "ui-spinner-input" ) .attr( "autocomplete", "off" ) .wrap( this._uiSpinnerHtml() ) .parent() // add buttons .append( this._buttonHtml() ); this.element.attr( "role", "spinbutton" ); // button bindings this.buttons = uiSpinner.find( ".ui-spinner-button" ) .attr( "tabIndex", -1 ) .button() .removeClass( "ui-corner-all" ); // IE 6 doesn't understand height: 50% for the buttons // unless the wrapper has an explicit height if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && uiSpinner.height() > 0 ) { uiSpinner.height( uiSpinner.height() ); } // disable spinner if element was already disabled if ( this.options.disabled ) { this.disable(); } }, _keydown: function( event ) { var options = this.options, keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.UP: this._repeat( null, 1, event ); return true; case keyCode.DOWN: this._repeat( null, -1, event ); return true; case keyCode.PAGE_UP: this._repeat( null, options.page, event ); return true; case keyCode.PAGE_DOWN: this._repeat( null, -options.page, event ); return true; } return false; }, _uiSpinnerHtml: function() { return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"; }, _buttonHtml: function() { return "" + "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" + "<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" + "</a>" + "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + "<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" + "</a>"; }, _start: function( event ) { if ( !this.spinning && this._trigger( "start", event ) === false ) { return false; } if ( !this.counter ) { this.counter = 1; } this.spinning = true; return true; }, _repeat: function( i, steps, event ) { i = i || 500; clearTimeout( this.timer ); this.timer = this._delay(function() { this._repeat( 40, steps, event ); }, i ); this._spin( steps * this.options.step, event ); }, _spin: function( step, event ) { var value = this.value() || 0; if ( !this.counter ) { this.counter = 1; } value = this._adjustValue( value + step * this._increment( this.counter ) ); if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { this._value( value ); this.counter++; } }, _increment: function( i ) { var incremental = this.options.incremental; if ( incremental ) { return $.isFunction( incremental ) ? incremental( i ) : Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 ); } return 1; }, _precision: function() { var precision = this._precisionOf( this.options.step ); if ( this.options.min !== null ) { precision = Math.max( precision, this._precisionOf( this.options.min ) ); } return precision; }, _precisionOf: function( num ) { var str = num.toString(), decimal = str.indexOf( "." ); return decimal === -1 ? 0 : str.length - decimal - 1; }, _adjustValue: function( value ) { var base, aboveMin, options = this.options; // make sure we're at a valid step // - find out where we are relative to the base (min or 0) base = options.min !== null ? options.min : 0; aboveMin = value - base; // - round to the nearest step aboveMin = Math.round(aboveMin / options.step) * options.step; // - rounding is based on 0, so adjust back to our base value = base + aboveMin; // fix precision from bad JS floating point math value = parseFloat( value.toFixed( this._precision() ) ); // clamp the value if ( options.max !== null && value > options.max) { return options.max; } if ( options.min !== null && value < options.min ) { return options.min; } return value; }, _stop: function( event ) { if ( !this.spinning ) { return; } clearTimeout( this.timer ); clearTimeout( this.mousewheelTimer ); this.counter = 0; this.spinning = false; this._trigger( "stop", event ); }, _setOption: function( key, value ) { if ( key === "culture" || key === "numberFormat" ) { var prevValue = this._parse( this.element.val() ); this.options[ key ] = value; this.element.val( this._format( prevValue ) ); return; } if ( key === "max" || key === "min" || key === "step" ) { if ( typeof value === "string" ) { value = this._parse( value ); } } if ( key === "icons" ) { this.buttons.first().find( ".ui-icon" ) .removeClass( this.options.icons.up ) .addClass( value.up ); this.buttons.last().find( ".ui-icon" ) .removeClass( this.options.icons.down ) .addClass( value.down ); } this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); this.buttons.button( value ? "disable" : "enable" ); } }, _setOptions: spinner_modifier(function( options ) { this._super( options ); }), _parse: function( val ) { if ( typeof val === "string" && val !== "" ) { val = window.Globalize && this.options.numberFormat ? Globalize.parseFloat( val, 10, this.options.culture ) : +val; } return val === "" || isNaN( val ) ? null : val; }, _format: function( value ) { if ( value === "" ) { return ""; } return window.Globalize && this.options.numberFormat ? Globalize.format( value, this.options.numberFormat, this.options.culture ) : value; }, _refresh: function() { this.element.attr({ "aria-valuemin": this.options.min, "aria-valuemax": this.options.max, // TODO: what should we do with values that can't be parsed? "aria-valuenow": this._parse( this.element.val() ) }); }, isValid: function() { var value = this.value(); // null is invalid if ( value === null ) { return false; } // if value gets adjusted, it's invalid return value === this._adjustValue( value ); }, // update the value without triggering change _value: function( value, allowAny ) { var parsed; if ( value !== "" ) { parsed = this._parse( value ); if ( parsed !== null ) { if ( !allowAny ) { parsed = this._adjustValue( parsed ); } value = this._format( parsed ); } } this.element.val( value ); this._refresh(); }, _destroy: function() { this.element .removeClass( "ui-spinner-input" ) .prop( "disabled", false ) .removeAttr( "autocomplete" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.uiSpinner.replaceWith( this.element ); }, stepUp: spinner_modifier(function( steps ) { this._stepUp( steps ); }), _stepUp: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * this.options.step ); this._stop(); } }, stepDown: spinner_modifier(function( steps ) { this._stepDown( steps ); }), _stepDown: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * -this.options.step ); this._stop(); } }, pageUp: spinner_modifier(function( pages ) { this._stepUp( (pages || 1) * this.options.page ); }), pageDown: spinner_modifier(function( pages ) { this._stepDown( (pages || 1) * this.options.page ); }), value: function( newVal ) { if ( !arguments.length ) { return this._parse( this.element.val() ); } spinner_modifier( this._value ).call( this, newVal ); }, widget: function() { return this.uiSpinner; } }); /*! * jQuery UI Tabs 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tabs/ */ var tabs = $.widget( "ui.tabs", { version: "1.11.0", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _isLocal: (function() { var rhash = /#.*$/; return function( anchor ) { var anchorUrl, locationUrl; // support: IE7 // IE7 doesn't normalize the href property when set via script (#9317) anchor = anchor.cloneNode( false ); anchorUrl = anchor.href.replace( rhash, "" ); locationUrl = location.href.replace( rhash, "" ); // decoding may throw an error if the URL isn't UTF-8 (#9518) try { anchorUrl = decodeURIComponent( anchorUrl ); } catch ( error ) {} try { locationUrl = decodeURIComponent( locationUrl ); } catch ( error ) {} return anchor.hash.length > 1 && anchorUrl === locationUrl; }; })(), _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( that._isLocal( anchor ) ) { selector = anchor.hash; panelId = selector.substring( 1 ); panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { // If the tab doesn't already have aria-controls, // generate an id by using a throw-away element panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id; selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": panelId, "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.tablist || this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = {}; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); // Always prevent the default action, even when disabled this._on( true, this.anchors, { click: function( event ) { event.preventDefault(); } }); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr( "aria-hidden", "true" ); eventData.oldTab.attr({ "aria-selected": "false", "aria-expanded": "false" }); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr( "aria-hidden", "false" ); eventData.newTab.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( this._isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); /*! * jQuery UI Tooltip 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tooltip/ */ var tooltip = $.widget( "ui.tooltip", { version: "1.11.0", options: { content: function() { // support: IE<9, Opera in jQuery <1.7 // .text() can't accept undefined, so coerce to a string var title = $( this ).attr( "title" ) || ""; // Escape title, since we're going from an attribute to raw HTML return $( "<a>" ).text( title ).html(); }, hide: true, // Disabled elements have inconsistent behavior across browsers (#8661) items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, open: null }, _addDescribedBy: function( elem, id ) { var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); describedby.push( id ); elem .data( "ui-tooltip-id", id ) .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); }, _removeDescribedBy: function( elem ) { var id = elem.data( "ui-tooltip-id" ), describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), index = $.inArray( id, describedby ); if ( index !== -1 ) { describedby.splice( index, 1 ); } elem.removeData( "ui-tooltip-id" ); describedby = $.trim( describedby.join( " " ) ); if ( describedby ) { elem.attr( "aria-describedby", describedby ); } else { elem.removeAttr( "aria-describedby" ); } }, _create: function() { this._on({ mouseover: "open", focusin: "open" }); // IDs of generated tooltips, needed for destroy this.tooltips = {}; // IDs of parent tooltips where we removed the title attribute this.parents = {}; if ( this.options.disabled ) { this._disable(); } // Append the aria-live region so tooltips announce correctly this.liveRegion = $( "<div>" ) .attr({ role: "log", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); }, _setOption: function( key, value ) { var that = this; if ( key === "disabled" ) { this[ value ? "_disable" : "_enable" ](); this.options[ key ] = value; // disable element style changes return; } this._super( key, value ); if ( key === "content" ) { $.each( this.tooltips, function( id, element ) { that._updateContent( element ); }); } }, _disable: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); }); // remove title attributes to prevent native tooltips this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.is( "[title]" ) ) { element .data( "ui-tooltip-title", element.attr( "title" ) ) .removeAttr( "title" ); } }); }, _enable: function() { // restore title attributes this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } }); }, open: function( event ) { var that = this, target = $( event ? event.target : this.element ) // we need closest here due to mouseover bubbling, // but always pointing at the same event target .closest( this.options.items ); // No element to show a tooltip for or the tooltip is already open if ( !target.length || target.data( "ui-tooltip-id" ) ) { return; } if ( target.attr( "title" ) ) { target.data( "ui-tooltip-title", target.attr( "title" ) ); } target.data( "ui-tooltip-open", true ); // kill parent tooltips, custom or native, for hover if ( event && event.type === "mouseover" ) { target.parents().each(function() { var parent = $( this ), blurEvent; if ( parent.data( "ui-tooltip-open" ) ) { blurEvent = $.Event( "blur" ); blurEvent.target = blurEvent.currentTarget = this; that.close( blurEvent, true ); } if ( parent.attr( "title" ) ) { parent.uniqueId(); that.parents[ this.id ] = { element: this, title: parent.attr( "title" ) }; parent.attr( "title", "" ); } }); } this._updateContent( target, event ); }, _updateContent: function( target, event ) { var content, contentOption = this.options.content, that = this, eventType = event ? event.type : null; if ( typeof contentOption === "string" ) { return this._open( event, target, contentOption ); } content = contentOption.call( target[0], function( response ) { // ignore async response if tooltip was closed already if ( !target.data( "ui-tooltip-open" ) ) { return; } // IE may instantly serve a cached response for ajax requests // delay this call to _open so the other call to _open runs first that._delay(function() { // jQuery creates a special event for focusin when it doesn't // exist natively. To improve performance, the native event // object is reused and the type is changed. Therefore, we can't // rely on the type being correct after the event finished // bubbling, so we set it back to the previous value. (#8740) if ( event ) { event.type = eventType; } this._open( event, target, response ); }); }); if ( content ) { this._open( event, target, content ); } }, _open: function( event, target, content ) { var tooltip, events, delayedShow, a11yContent, positionOption = $.extend( {}, this.options.position ); if ( !content ) { return; } // Content can be updated multiple times. If the tooltip already // exists, then just update the content and bail. tooltip = this._find( target ); if ( tooltip.length ) { tooltip.find( ".ui-tooltip-content" ).html( content ); return; } // if we have a title, clear it to prevent the native tooltip // we have to check first to avoid defining a title if none exists // (we don't want to cause an element to start matching [title]) // // We use removeAttr only for key events, to allow IE to export the correct // accessible attributes. For mouse events, set to empty string to avoid // native tooltip showing up (happens only when removing inside mouseover). if ( target.is( "[title]" ) ) { if ( event && event.type === "mouseover" ) { target.attr( "title", "" ); } else { target.removeAttr( "title" ); } } tooltip = this._tooltip( target ); this._addDescribedBy( target, tooltip.attr( "id" ) ); tooltip.find( ".ui-tooltip-content" ).html( content ); // Support: Voiceover on OS X, JAWS on IE <= 9 // JAWS announces deletions even when aria-relevant="additions" // Voiceover will sometimes re-read the entire log region's contents from the beginning this.liveRegion.children().hide(); if ( content.clone ) { a11yContent = content.clone(); a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" ); } else { a11yContent = content; } $( "<div>" ).html( a11yContent ).appendTo( this.liveRegion ); function position( event ) { positionOption.of = event; if ( tooltip.is( ":hidden" ) ) { return; } tooltip.position( positionOption ); } if ( this.options.track && event && /^mouse/.test( event.type ) ) { this._on( this.document, { mousemove: position }); // trigger once to override element-relative positioning position( event ); } else { tooltip.position( $.extend({ of: target }, this.options.position ) ); } tooltip.hide(); this._show( tooltip, this.options.show ); // Handle tracking tooltips that are shown with a delay (#8644). As soon // as the tooltip is visible, position the tooltip using the most recent // event. if ( this.options.show && this.options.show.delay ) { delayedShow = this.delayedShow = setInterval(function() { if ( tooltip.is( ":visible" ) ) { position( positionOption.of ); clearInterval( delayedShow ); } }, $.fx.interval ); } this._trigger( "open", event, { tooltip: tooltip } ); events = { keyup: function( event ) { if ( event.keyCode === $.ui.keyCode.ESCAPE ) { var fakeEvent = $.Event(event); fakeEvent.currentTarget = target[0]; this.close( fakeEvent, true ); } } }; // Only bind remove handler for delegated targets. Non-delegated // tooltips will handle this in destroy. if ( target[ 0 ] !== this.element[ 0 ] ) { events.remove = function() { this._removeTooltip( tooltip ); }; } if ( !event || event.type === "mouseover" ) { events.mouseleave = "close"; } if ( !event || event.type === "focusin" ) { events.focusout = "close"; } this._on( true, target, events ); }, close: function( event ) { var that = this, target = $( event ? event.currentTarget : this.element ), tooltip = this._find( target ); // disabling closes the tooltip, so we need to track when we're closing // to avoid an infinite loop in case the tooltip becomes disabled on close if ( this.closing ) { return; } // Clear the interval for delayed tracking tooltips clearInterval( this.delayedShow ); // only set title if we had one before (see comment in _open()) // If the title attribute has changed since open(), don't restore if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) { target.attr( "title", target.data( "ui-tooltip-title" ) ); } this._removeDescribedBy( target ); tooltip.stop( true ); this._hide( tooltip, this.options.hide, function() { that._removeTooltip( $( this ) ); }); target.removeData( "ui-tooltip-open" ); this._off( target, "mouseleave focusout keyup" ); // Remove 'remove' binding only on delegated targets if ( target[ 0 ] !== this.element[ 0 ] ) { this._off( target, "remove" ); } this._off( this.document, "mousemove" ); if ( event && event.type === "mouseleave" ) { $.each( this.parents, function( id, parent ) { $( parent.element ).attr( "title", parent.title ); delete that.parents[ id ]; }); } this.closing = true; this._trigger( "close", event, { tooltip: tooltip } ); this.closing = false; }, _tooltip: function( element ) { var tooltip = $( "<div>" ) .attr( "role", "tooltip" ) .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + ( this.options.tooltipClass || "" ) ), id = tooltip.uniqueId().attr( "id" ); $( "<div>" ) .addClass( "ui-tooltip-content" ) .appendTo( tooltip ); tooltip.appendTo( this.document[0].body ); this.tooltips[ id ] = element; return tooltip; }, _find: function( target ) { var id = target.data( "ui-tooltip-id" ); return id ? $( "#" + id ) : $(); }, _removeTooltip: function( tooltip ) { tooltip.remove(); delete this.tooltips[ tooltip.attr( "id" ) ]; }, _destroy: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { // Delegate to close method to handle common cleanup var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); // Remove immediately; destroying an open tooltip doesn't use the // hide animation $( "#" + id ).remove(); // Restore the title if ( element.data( "ui-tooltip-title" ) ) { // If the title attribute has changed since open(), don't restore if ( !element.attr( "title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } element.removeData( "ui-tooltip-title" ); } }); this.liveRegion.remove(); } }); /*! * jQuery UI Effects 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/effects-core/ */ var dataSpace = "ui-effects-"; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.1.2 * https://github.com/jquery/jquery-color * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Wed Jan 16 08:47:09 2013 -0600 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [ { re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } } ], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + ( q - p ) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6; } return p; } spaces.hsla.to = function( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch( e ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ (function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; }); function getElementStyles( elem ) { var key, len, style = elem.ownerDocument.defaultView ? elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : elem.currentStyle, styles = {}; if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { styles[ $.camelCase( key ) ] = style[ key ]; } } // support: Opera, IE <9 } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { styles[ key ] = style[ key ]; } } } return styles; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).addBack() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles( this ) }; }); // apply class change applyClassChange = function() { $.each( classAnimationActions, function(i, action) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } }); }; applyClassChange(); // map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map(function() { this.end = getElementStyles( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; }); // apply original class animated.attr( "class", baseClass ); // map all animated objects again - this time collecting a promise allAnimations = allAnimations.map(function() { var styleInfo = this, dfd = $.Deferred(), opts = $.extend({}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } }); this.el.animate( this.diff, opts ); return dfd.promise(); }); // once all animations have completed: $.when.apply( $, allAnimations.get() ).done(function() { // set the final class applyClassChange(); // for each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function(key) { el.css( key, "" ); }); }); // this is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); }); }); }; $.fn.extend({ addClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.addClass ), removeClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return arguments.length > 1 ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.removeClass ), toggleClass: (function( orig ) { return function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return orig.apply( this, arguments ); } else { return $.effects.animateClass.call( this, (force ? { add: classNames } : { remove: classNames }), speed, easing, callback ); } } else { // without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }; })( $.fn.toggleClass ), switchClass: function( remove, add, speed, easing, callback) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } }); })(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ (function() { $.extend( $.effects, { version: "1.11.0", // Saves a set of properties in a data storage save: function( element, set ) { for ( var i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i; for ( i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); // support: jQuery 1.6.2 // http://bugs.jquery.com/ticket/9917 // jQuery 1.6.2 incorrectly returns undefined for any falsy value. // We can't differentiate between "" and 0 here, so we just assume // empty string since it's likely to be a more common value... if ( val === undefined ) { val = ""; } element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if (mode === "toggle") { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } } return element; }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } }); return value; } }); // return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // convert to an object effect = { effect: effect }; // catch (effect, null, ...) if ( options == null ) { options = {}; } // catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardAnimationOption( option ) { // Valid standard speeds (nothing, number, named speed) if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { return true; } // Invalid strings - treat as "normal" speed if ( typeof option === "string" && !$.effects.effect[ option ] ) { return true; } // Complete callback if ( $.isFunction( option ) ) { return true; } // Options hash (but not naming an effect) if ( typeof option === "object" && !option.effect ) { return true; } // Didn't match any standard API return false; } $.fn.extend({ effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), mode = args.mode, queue = args.queue, effectMethod = $.effects.effect[ args.effect ]; if ( $.fx.off || !effectMethod ) { // delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, args.complete ); } else { return this.each( function() { if ( args.complete ) { args.complete.call( this ); } }); } } function run( next ) { var elem = $( this ), complete = args.complete, mode = args.mode; function done() { if ( $.isFunction( complete ) ) { complete.call( elem[0] ); } if ( $.isFunction( next ) ) { next(); } } // If the element already has the correct final state, delegate to // the core methods so the internal tracking of "olddisplay" works. if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { elem[ mode ](); done(); } else { effectMethod.call( elem[0], args, done ); } } return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); }, show: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }; })( $.fn.show ), hide: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }; })( $.fn.hide ), toggle: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) || typeof option === "boolean" ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }; })( $.fn.toggle ), // helper functions cssUnit: function(key) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } }); return val; } }); })(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ (function() { // based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; }); $.extend( baseEasings, { Sine: function( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } }); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; }); })(); var effect = $.effects; /*! * jQuery UI Effects Blind 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/blind-effect/ */ var effectBlind = $.effects.effect.blind = function( o, done ) { // Create element var el = $( this ), rvertical = /up|down|vertical/, rpositivemotion = /up|left|vertical|horizontal/, props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), direction = o.direction || "up", vertical = rvertical.test( direction ), ref = vertical ? "height" : "width", ref2 = vertical ? "top" : "left", motion = rpositivemotion.test( direction ), animation = {}, show = mode === "show", wrapper, distance, margin; // if already wrapped, the wrapper's properties are my property. #6245 if ( el.parent().is( ".ui-effects-wrapper" ) ) { $.effects.save( el.parent(), props ); } else { $.effects.save( el, props ); } el.show(); wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = wrapper[ ref ](); margin = parseFloat( wrapper.css( ref2 ) ) || 0; animation[ ref ] = show ? distance : 0; if ( !motion ) { el .css( vertical ? "bottom" : "right", 0 ) .css( vertical ? "top" : "left", "auto" ) .css({ position: "absolute" }); animation[ ref2 ] = show ? margin : distance + margin; } // start at 0 if we are showing if ( show ) { wrapper.css( ref, 0 ); if ( !motion ) { wrapper.css( ref2, margin + distance ); } } // Animate wrapper.animate( animation, { duration: o.duration, easing: o.easing, queue: false, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Bounce 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/bounce-effect/ */ var effectBounce = $.effects.effect.bounce = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], // defaults: mode = $.effects.setMode( el, o.mode || "effect" ), hide = mode === "hide", show = mode === "show", direction = o.direction || "up", distance = o.distance, times = o.times || 5, // number of internal animations anims = times * 2 + ( show || hide ? 1 : 0 ), speed = o.duration / anims, easing = o.easing, // utility: ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ), i, upAnim, downAnim, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; // Avoid touching opacity to prevent clearType and PNG issues in IE if ( show || hide ) { props.push( "opacity" ); } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Create Wrapper // default distance for the BIGGEST bounce is the outer Distance / 3 if ( !distance ) { distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; } if ( show ) { downAnim = { opacity: 1 }; downAnim[ ref ] = 0; // if we are showing, force opacity 0 and set the initial position // then do the "first" animation el.css( "opacity", 0 ) .css( ref, motion ? -distance * 2 : distance * 2 ) .animate( downAnim, speed, easing ); } // start at the smallest distance if we are hiding if ( hide ) { distance = distance / Math.pow( 2, times - 1 ); } downAnim = {}; downAnim[ ref ] = 0; // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here for ( i = 0; i < times; i++ ) { upAnim = {}; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ) .animate( downAnim, speed, easing ); distance = hide ? distance * 2 : distance / 2; } // Last Bounce when Hiding if ( hide ) { upAnim = { opacity: 0 }; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ); } el.queue(function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; /*! * jQuery UI Effects Clip 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/clip-effect/ */ var effectClip = $.effects.effect.clip = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "vertical", vert = direction === "vertical", size = vert ? "height" : "width", position = vert ? "top" : "left", animation = {}, wrapper, animate, distance; // Save & Show $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); animate = ( el[0].tagName === "IMG" ) ? wrapper : el; distance = animate[ size ](); // Shift if ( show ) { animate.css( size, 0 ); animate.css( position, distance / 2 ); } // Create Animation Object: animation[ size ] = show ? distance : 0; animation[ position ] = show ? 0 : distance / 2; // Animate animate.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( !show ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Drop 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/drop-effect/ */ var effectDrop = $.effects.effect.drop = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "left", ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", animation = { opacity: show ? 1 : 0 }, distance; // Adjust $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2; if ( show ) { el .css( "opacity", 0 ) .css( ref, motion === "pos" ? -distance : distance ); } // Animation animation[ ref ] = ( show ? ( motion === "pos" ? "+=" : "-=" ) : ( motion === "pos" ? "-=" : "+=" ) ) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Explode 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/explode-effect/ */ var effectExplode = $.effects.effect.explode = function( o, done ) { var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, cells = rows, el = $( this ), mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", // show and then visibility:hidden the element before calculating offset offset = el.show().css( "visibility", "hidden" ).offset(), // width and height of a piece width = Math.ceil( el.outerWidth() / cells ), height = Math.ceil( el.outerHeight() / rows ), pieces = [], // loop i, j, left, top, mx, my; // children animate complete: function childComplete() { pieces.push( this ); if ( pieces.length === rows * cells ) { animComplete(); } } // clone the element for each row and cell. for ( i = 0; i < rows ; i++ ) { // ===> top = offset.top + i * height; my = i - ( rows - 1 ) / 2 ; for ( j = 0; j < cells ; j++ ) { // ||| left = offset.left + j * width; mx = j - ( cells - 1 ) / 2 ; // Create a clone of the now hidden main element that will be absolute positioned // within a wrapper div off the -left and -top equal to size of our pieces el .clone() .appendTo( "body" ) .wrap( "<div></div>" ) .css({ position: "absolute", visibility: "visible", left: -j * width, top: -i * height }) // select the wrapper - make it overflow: hidden and absolute positioned based on // where the original was located +left and +top equal to the size of pieces .parent() .addClass( "ui-effects-explode" ) .css({ position: "absolute", overflow: "hidden", width: width, height: height, left: left + ( show ? mx * width : 0 ), top: top + ( show ? my * height : 0 ), opacity: show ? 0 : 1 }).animate({ left: left + ( show ? 0 : mx * width ), top: top + ( show ? 0 : my * height ), opacity: show ? 1 : 0 }, o.duration || 500, o.easing, childComplete ); } } function animComplete() { el.css({ visibility: "visible" }); $( pieces ).remove(); if ( !show ) { el.hide(); } done(); } }; /*! * jQuery UI Effects Fade 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/fade-effect/ */ var effectFade = $.effects.effect.fade = function( o, done ) { var el = $( this ), mode = $.effects.setMode( el, o.mode || "toggle" ); el.animate({ opacity: mode }, { queue: false, duration: o.duration, easing: o.easing, complete: done }); }; /*! * jQuery UI Effects Fold 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/fold-effect/ */ var effectFold = $.effects.effect.fold = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", hide = mode === "hide", size = o.size || 15, percent = /([0-9]+)%/.exec( size ), horizFirst = !!o.horizFirst, widthFirst = show !== horizFirst, ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], duration = o.duration / 2, wrapper, distance, animation1 = {}, animation2 = {}; $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = widthFirst ? [ wrapper.width(), wrapper.height() ] : [ wrapper.height(), wrapper.width() ]; if ( percent ) { size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; } if ( show ) { wrapper.css( horizFirst ? { height: 0, width: size } : { height: size, width: 0 }); } // Animation animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; // Animate wrapper .animate( animation1, duration, o.easing ) .animate( animation2, duration, o.easing, function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); }; /*! * jQuery UI Effects Highlight 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/highlight-effect/ */ var effectHighlight = $.effects.effect.highlight = function( o, done ) { var elem = $( this ), props = [ "backgroundImage", "backgroundColor", "opacity" ], mode = $.effects.setMode( elem, o.mode || "show" ), animation = { backgroundColor: elem.css( "backgroundColor" ) }; if (mode === "hide") { animation.opacity = 0; } $.effects.save( elem, props ); elem .show() .css({ backgroundImage: "none", backgroundColor: o.color || "#ffff99" }) .animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { elem.hide(); } $.effects.restore( elem, props ); done(); } }); }; /*! * jQuery UI Effects Size 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/size-effect/ */ var effectSize = $.effects.effect.size = function( o, done ) { // Create element var original, baseline, factor, el = $( this ), props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], // Always restore props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], // Copy for children props2 = [ "width", "height", "overflow" ], cProps = [ "fontSize" ], vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], // Set options mode = $.effects.setMode( el, o.mode || "effect" ), restore = o.restore || mode !== "effect", scale = o.scale || "both", origin = o.origin || [ "middle", "center" ], position = el.css( "position" ), props = restore ? props0 : props1, zero = { height: 0, width: 0, outerHeight: 0, outerWidth: 0 }; if ( mode === "show" ) { el.show(); } original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }; if ( o.mode === "toggle" && mode === "show" ) { el.from = o.to || zero; el.to = o.from || original; } else { el.from = o.from || ( mode === "show" ? zero : original ); el.to = o.to || ( mode === "hide" ? zero : original ); } // Set scaling factor factor = { from: { y: el.from.height / original.height, x: el.from.width / original.width }, to: { y: el.to.height / original.height, x: el.to.width / original.width } }; // Scale the css box if ( scale === "box" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( vProps ); el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { props = props.concat( hProps ); el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); } } // Scale the content if ( scale === "content" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( cProps ).concat( props2 ); el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); } } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); el.css( "overflow", "hidden" ).css( el.from ); // Adjust if (origin) { // Calculate baseline shifts baseline = $.effects.getBaseline( origin, original ); el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; } el.css( el.from ); // set top & left // Animate if ( scale === "content" || scale === "both" ) { // Scale the children // Add margins/font-size vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); hProps = hProps.concat([ "marginLeft", "marginRight" ]); props2 = props0.concat(vProps).concat(hProps); el.find( "*[width]" ).each( function() { var child = $( this ), c_original = { height: child.height(), width: child.width(), outerHeight: child.outerHeight(), outerWidth: child.outerWidth() }; if (restore) { $.effects.save(child, props2); } child.from = { height: c_original.height * factor.from.y, width: c_original.width * factor.from.x, outerHeight: c_original.outerHeight * factor.from.y, outerWidth: c_original.outerWidth * factor.from.x }; child.to = { height: c_original.height * factor.to.y, width: c_original.width * factor.to.x, outerHeight: c_original.height * factor.to.y, outerWidth: c_original.width * factor.to.x }; // Vertical props scaling if ( factor.from.y !== factor.to.y ) { child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); } // Animate children child.css( child.from ); child.animate( child.to, o.duration, o.easing, function() { // Restore children if ( restore ) { $.effects.restore( child, props2 ); } }); }); } // Animate el.animate( el.to, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( el.to.opacity === 0 ) { el.css( "opacity", el.from.opacity ); } if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); if ( !restore ) { // we need to calculate our new positioning based on the scaling if ( position === "static" ) { el.css({ position: "relative", top: el.to.top, left: el.to.left }); } else { $.each([ "top", "left" ], function( idx, pos ) { el.css( pos, function( _, str ) { var val = parseInt( str, 10 ), toRef = idx ? el.to.left : el.to.top; // if original was "auto", recalculate the new value from wrapper if ( str === "auto" ) { return toRef + "px"; } return val + toRef + "px"; }); }); } } $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Scale 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/scale-effect/ */ var effectScale = $.effects.effect.scale = function( o, done ) { // Create element var el = $( this ), options = $.extend( true, {}, o ), mode = $.effects.setMode( el, o.mode || "effect" ), percent = parseInt( o.percent, 10 ) || ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), direction = o.direction || "both", origin = o.origin, original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }, factor = { y: direction !== "horizontal" ? (percent / 100) : 1, x: direction !== "vertical" ? (percent / 100) : 1 }; // We are going to pass this effect to the size effect: options.effect = "size"; options.queue = false; options.complete = done; // Set default origin and restore for show/hide if ( mode !== "effect" ) { options.origin = origin || [ "middle", "center" ]; options.restore = true; } options.from = o.from || ( mode === "show" ? { height: 0, width: 0, outerHeight: 0, outerWidth: 0 } : original ); options.to = { height: original.height * factor.y, width: original.width * factor.x, outerHeight: original.outerHeight * factor.y, outerWidth: original.outerWidth * factor.x }; // Fade option to support puff if ( options.fade ) { if ( mode === "show" ) { options.from.opacity = 0; options.to.opacity = 1; } if ( mode === "hide" ) { options.from.opacity = 1; options.to.opacity = 0; } } // Animate el.effect( options ); }; /*! * jQuery UI Effects Puff 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/puff-effect/ */ var effectPuff = $.effects.effect.puff = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "hide" ), hide = mode === "hide", percent = parseInt( o.percent, 10 ) || 150, factor = percent / 100, original = { height: elem.height(), width: elem.width(), outerHeight: elem.outerHeight(), outerWidth: elem.outerWidth() }; $.extend( o, { effect: "scale", queue: false, fade: true, mode: mode, complete: done, percent: hide ? percent : 100, from: hide ? original : { height: original.height * factor, width: original.width * factor, outerHeight: original.outerHeight * factor, outerWidth: original.outerWidth * factor } }); elem.effect( o ); }; /*! * jQuery UI Effects Pulsate 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/pulsate-effect/ */ var effectPulsate = $.effects.effect.pulsate = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "show" ), show = mode === "show", hide = mode === "hide", showhide = ( show || mode === "hide" ), // showing or hiding leaves of the "last" animation anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), duration = o.duration / anims, animateTo = 0, queue = elem.queue(), queuelen = queue.length, i; if ( show || !elem.is(":visible")) { elem.css( "opacity", 0 ).show(); animateTo = 1; } // anims - 1 opacity "toggles" for ( i = 1; i < anims; i++ ) { elem.animate({ opacity: animateTo }, duration, o.easing ); animateTo = 1 - animateTo; } elem.animate({ opacity: animateTo }, duration, o.easing); elem.queue(function() { if ( hide ) { elem.hide(); } done(); }); // We just queued up "anims" animations, we need to put them next in the queue if ( queuelen > 1 ) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } elem.dequeue(); }; /*! * jQuery UI Effects Shake 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/shake-effect/ */ var effectShake = $.effects.effect.shake = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "effect" ), direction = o.direction || "left", distance = o.distance || 20, times = o.times || 3, anims = times * 2 + 1, speed = Math.round( o.duration / anims ), ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), animation = {}, animation1 = {}, animation2 = {}, i, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Animation animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; // Animate el.animate( animation, speed, o.easing ); // Shakes for ( i = 1; i < times; i++ ) { el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); } el .animate( animation1, speed, o.easing ) .animate( animation, speed / 2, o.easing ) .queue(function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; /*! * jQuery UI Effects Slide 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/slide-effect/ */ var effectSlide = $.effects.effect.slide = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "width", "height" ], mode = $.effects.setMode( el, o.mode || "show" ), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {}; // Adjust $.effects.save( el, props ); el.show(); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); $.effects.createWrapper( el ).css({ overflow: "hidden" }); if ( show ) { el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); } // Animation animation[ ref ] = ( show ? ( positiveMotion ? "+=" : "-=") : ( positiveMotion ? "-=" : "+=")) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Transfer 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/transfer-effect/ */ var effectTransfer = $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop, left: endPosition.left - fixLeft, height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop, left: startPosition.left - fixLeft, height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; }));
oposso-team/oposso
layout/scripts/jquery-ui.js
JavaScript
agpl-3.0
418,655
package io.hops.hopsworks.admin.project; import io.hops.hopsworks.admin.lims.ClientSessionState; import io.hops.hopsworks.admin.lims.MessagesController; import io.hops.hopsworks.common.dao.project.team.ProjectTeamFacade; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import io.hops.hopsworks.common.dao.user.activity.ActivityFacade; import io.hops.hopsworks.common.dao.user.Users; @ManagedBean @ViewScoped public class ProjectTeamController implements Serializable { private static final Logger logger = Logger.getLogger( ProjectTeamController.class.getName()); private String toRemoveEmail; private String toRemoveName; @EJB private ProjectTeamFacade teamFacade; @EJB private ActivityFacade activityFacade; @ManagedProperty(value = "#{clientSessionState}") private ClientSessionState sessionState; public void setToRemove(String email, String name) { this.toRemoveEmail = email; this.toRemoveName = name; } public void clearToRemove() { this.toRemoveEmail = null; this.toRemoveName = null; } public String getToRemoveEmail() { return toRemoveEmail; } public String getToRemoveName() { return toRemoveName; } public synchronized void deleteMemberFromTeam() { try { Users user = this.teamFacade.findUserByEmail(toRemoveEmail); teamFacade.removeProjectTeam(sessionState.getActiveProject(), user); activityFacade.persistActivity(ActivityFacade.REMOVED_MEMBER + toRemoveEmail, sessionState.getActiveProject(), sessionState. getLoggedInUsername()); } catch (EJBException ejb) { MessagesController.addErrorMessage("Deleting team member failed."); logger.log(Level.WARNING, "Failed to remove team member " + toRemoveEmail + "from project " + sessionState.getActiveProjectname(), ejb); return; } MessagesController.addInfoMessage("Member removed", "Team member " + toRemoveEmail + " deleted from project " + sessionState.getActiveProjectname()); clearToRemove(); } public void setSessionState(ClientSessionState sessionState) { this.sessionState = sessionState; } }
FilotasSiskos/hopsworks
hopsworks-admin/src/main/java/io/hops/hopsworks/admin/project/ProjectTeamController.java
Java
agpl-3.0
2,402
<?php /** * Doctrine ORM * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE. This license can also be viewed * at http://hobodave.com/license.txt * * @category DoctrineExtensions * @package DoctrineExtensions\Paginate * @author David Abdemoulaie <dave@hobodave.com> * @copyright Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/) * @license http://hobodave.com/license.txt New BSD License */ namespace Doctrine\ORM\Tools\Pagination; use Doctrine\ORM\Query\AST\ArithmeticExpression; use Doctrine\ORM\Query\AST\ConditionalExpression; use Doctrine\ORM\Query\AST\ConditionalFactor; use Doctrine\ORM\Query\AST\ConditionalPrimary; use Doctrine\ORM\Query\AST\ConditionalTerm; use Doctrine\ORM\Query\AST\InExpression; use Doctrine\ORM\Query\AST\InputParameter; use Doctrine\ORM\Query\AST\NullComparisonExpression; use Doctrine\ORM\Query\AST\PathExpression; use Doctrine\ORM\Query\AST\SelectStatement; use Doctrine\ORM\Query\AST\SimpleArithmeticExpression; use Doctrine\ORM\Query\AST\WhereClause; use Doctrine\ORM\Query\TreeWalkerAdapter; /** * Replaces the whereClause of the AST with a WHERE id IN (:foo_1, :foo_2) equivalent. * * @category DoctrineExtensions * @package DoctrineExtensions\Paginate * @author David Abdemoulaie <dave@hobodave.com> * @copyright Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/) * @license http://hobodave.com/license.txt New BSD License */ class WhereInWalker extends TreeWalkerAdapter { /** * ID Count hint name. */ const HINT_PAGINATOR_ID_COUNT = 'doctrine.id.count'; /** * Primary key alias for query. */ const PAGINATOR_ID_ALIAS = 'dpid'; /** * Replaces the whereClause in the AST. * * Generates a clause equivalent to WHERE IN (:dpid_1, :dpid_2, ...) * * The parameter namespace (dpid) is defined by * the PAGINATOR_ID_ALIAS * * The total number of parameters is retrieved from * the HINT_PAGINATOR_ID_COUNT query hint. * * @param SelectStatement $AST * * @return void * * @throws \RuntimeException */ public function walkSelectStatement( SelectStatement $AST ) { $queryComponents = $this->_getQueryComponents(); // Get the root entity and alias from the AST fromClause $from = $AST->fromClause->identificationVariableDeclarations; if (count( $from ) > 1) { throw new \RuntimeException( "Cannot count query which selects two FROM components, cannot make distinction" ); } $fromRoot = reset( $from ); $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; $rootClass = $queryComponents[$rootAlias]['metadata']; $identifierFieldName = $rootClass->getSingleIdentifierFieldName(); $pathType = PathExpression::TYPE_STATE_FIELD; if (isset( $rootClass->associationMappings[$identifierFieldName] )) { $pathType = PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION; } $pathExpression = new PathExpression( PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $rootAlias, $identifierFieldName ); $pathExpression->type = $pathType; $count = $this->_getQuery()->getHint( self::HINT_PAGINATOR_ID_COUNT ); if ($count > 0) { $arithmeticExpression = new ArithmeticExpression(); $arithmeticExpression->simpleArithmeticExpression = new SimpleArithmeticExpression( array( $pathExpression ) ); $expression = new InExpression( $arithmeticExpression ); $expression->literals[] = new InputParameter( ":".self::PAGINATOR_ID_ALIAS ); } else { $expression = new NullComparisonExpression( $pathExpression ); $expression->not = false; } $conditionalPrimary = new ConditionalPrimary; $conditionalPrimary->simpleConditionalExpression = $expression; if ($AST->whereClause) { if ($AST->whereClause->conditionalExpression instanceof ConditionalTerm) { $AST->whereClause->conditionalExpression->conditionalFactors[] = $conditionalPrimary; } elseif ($AST->whereClause->conditionalExpression instanceof ConditionalPrimary) { $AST->whereClause->conditionalExpression = new ConditionalExpression( array( new ConditionalTerm( array( $AST->whereClause->conditionalExpression, $conditionalPrimary ) ) ) ); } elseif ($AST->whereClause->conditionalExpression instanceof ConditionalExpression || $AST->whereClause->conditionalExpression instanceof ConditionalFactor ) { $tmpPrimary = new ConditionalPrimary; $tmpPrimary->conditionalExpression = $AST->whereClause->conditionalExpression; $AST->whereClause->conditionalExpression = new ConditionalTerm( array( $tmpPrimary, $conditionalPrimary ) ); } } else { $AST->whereClause = new WhereClause( new ConditionalExpression( array( new ConditionalTerm( array( $conditionalPrimary ) ) ) ) ); } } }
KWZwickau/KREDA-Sphere
Library/MOC-V/Component/Database/Vendor/Doctrine2ORM/2.5-Master/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php
PHP
agpl-3.0
5,531
/* Layout */ body, nav, header, aside, figure, section, footer, article { margin: 0; padding: 5px; display: block; } #branding { float: left; clear: left; width: 211px; } #sidebar { float: left; clear: left; width: 211px; } #container { width: 1000px; margin-left: 225px; } #bigfooter { clear: both; margin-bottom: 20px; } #site { background-color: #fcc; } #sidebar { background-color: #cfc; } #container { background-color: #ffd; } #bigfooter { background-color: #ccf; } /* Logo */ #branding h1 { display: block; width: 201px; height: 186px; } #branding h1 a { display: block; text-indent: -9999em; width: 100%; height: 100%; } /* Nav */ #site ul { display: inline; width: 100%; } #site li { display: inline; padding: 5px 10px; list-style: none; } #site li:hover { background-color: #faa; } #site form { float: right; } /* Footer */ #bigfooter > div { display: inline-block; height: 100%; width: 24%; vertical-align: top; } #bigfooter li:hover { background-color: #aaf; } /* Contenus */ #container article { background-color: #f33; border: 1px solid; -moz-border-radius: 15px; margin: 10px; padding: 0px; } #container article header, #container article footer { background-color: #c33; padding: 1px 5px:; } #container article header { -moz-border-radius-topleft: 15px; -moz-border-radius-topright: 15px; } #container article footer { -moz-border-radius-bottomleft: 15px; -moz-border-radius-bottomright: 15px; } #container article figure { float: left; } /* Diffs */ ins.diffins, ins.diffmod { background-color: #3f3; } del.diffdel, del.diffmod { background-color: #f33; } /* Comments */ .comment { border: 1px solid black; } .new-comment h3 { border: 1px solid red; } .fold { display:none; } .avatar { float:left; margin: 5px 10px; } /* Toolbar */ #toolbar { position: fixed; overflow: hidden; bottom: 0; left: 20px; right: 20px; padding: 2px; color: #333; background-color: #dfd6d1; border: 1px solid #baa; } #toolbar-items { float: right; } /* Divers et variés */ a img { border: none; } h2 { color: #333; } #sidebar .login p { font-weight: bold; } #tracker .fix a, #tracker .invalid a, .tracker.fix a, .tracker.invalid a { text-decoration: line-through; } .misspelled { border-bottom:1px dashed red; }
julienXX/linuxfr.org
public/stylesheets/contrib/red.css
CSS
agpl-3.0
2,226
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc4.impl; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import cn.dlb.bim.models.ifc4.Ifc4Package; import cn.dlb.bim.models.ifc4.IfcApproval; import cn.dlb.bim.models.ifc4.IfcApprovalRelationship; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Approval Relationship</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc4.impl.IfcApprovalRelationshipImpl#getRelatingApproval <em>Relating Approval</em>}</li> * <li>{@link cn.dlb.bim.models.ifc4.impl.IfcApprovalRelationshipImpl#getRelatedApprovals <em>Related Approvals</em>}</li> * </ul> * * @generated */ public class IfcApprovalRelationshipImpl extends IfcResourceLevelRelationshipImpl implements IfcApprovalRelationship { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcApprovalRelationshipImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc4Package.Literals.IFC_APPROVAL_RELATIONSHIP; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IfcApproval getRelatingApproval() { return (IfcApproval) eGet(Ifc4Package.Literals.IFC_APPROVAL_RELATIONSHIP__RELATING_APPROVAL, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRelatingApproval(IfcApproval newRelatingApproval) { eSet(Ifc4Package.Literals.IFC_APPROVAL_RELATIONSHIP__RELATING_APPROVAL, newRelatingApproval); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") public EList<IfcApproval> getRelatedApprovals() { return (EList<IfcApproval>) eGet(Ifc4Package.Literals.IFC_APPROVAL_RELATIONSHIP__RELATED_APPROVALS, true); } } //IfcApprovalRelationshipImpl
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/impl/IfcApprovalRelationshipImpl.java
Java
agpl-3.0
2,695
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_131) on Fri Jul 07 10:42:39 CEST 2017 --> <title>Uses of Class de.hebis.it.hds.gnd.out.AutorityRecordFileWriter</title> <meta name="date" content="2017-07-07"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class de.hebis.it.hds.gnd.out.AutorityRecordFileWriter"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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><a href="../../../../../../../de/hebis/it/hds/gnd/out/AutorityRecordFileWriter.html" title="class in de.hebis.it.hds.gnd.out">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?de/hebis/it/hds/gnd/out/class-use/AutorityRecordFileWriter.html" target="_top">Frames</a></li> <li><a href="AutorityRecordFileWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class de.hebis.it.hds.gnd.out.AutorityRecordFileWriter" class="title">Uses of Class<br>de.hebis.it.hds.gnd.out.AutorityRecordFileWriter</h2> </div> <div class="classUseContainer">No usage of de.hebis.it.hds.gnd.out.AutorityRecordFileWriter</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.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><a href="../../../../../../../de/hebis/it/hds/gnd/out/AutorityRecordFileWriter.html" title="class in de.hebis.it.hds.gnd.out">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?de/hebis/it/hds/gnd/out/class-use/AutorityRecordFileWriter.html" target="_top">Frames</a></li> <li><a href="AutorityRecordFileWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
HeBIS-VZ/GndAuthorityRecords
doc/de/hebis/it/hds/gnd/out/class-use/AutorityRecordFileWriter.html
HTML
agpl-3.0
4,606
Title: Cherrypy 使用手冊 Date: 2016-05-14 12:00 Category: Cherrypy Tags: Python3, web-based Author: kmol Cherrypy 相關功能介紹 <!-- PELICAN_END_SUMMARY --> ## CherryPy 模組安裝: pip install cherrypy ## CherryPy 程式架構 最簡單的 CherryPy 程式: <pre class="brush: python"> #coding: utf-8 # 最簡單的 CherryPy 程式 # 導入 cherrypy 與 os 模組 import cherrypy,os # 建立 HelloWorld 類別物件 class HelloWorld(object): # 定義一個會內建呼叫的 index 方法 def index(self): # 傳回字串 return "Hello World!" # 可以從外部以 index 連結呼叫此方法 index.exposed = True # 利用 os.system() 執行 chrome.exe, 直接以瀏覽器開啟 cherrypy 伺服器 os.system("V:/Chrome/chrome.exe http://localhost:8083") # 設定 cherrypy 的連結埠號為 8083 cherrypy.server.socket_port = 8083 # 設定 cherrypy 的啟動 IP 為 127.0.0.1 cherrypy.server.socket_host = '127.0.0.1' # 以 HelloWorld() 物件啟動 cherrypy cherrypy.quickstart(HelloWorld()) </pre> 從上面的程式執行, 可以了解 CherryPy 的基本架構, 主要利用 HelloWorld() 物件中的方法來進行呼叫執行, 而且一旦啟動, 會自動呼叫 index() 方法, 而使用者也可以自行建立其他方法. <pre class="brush: python"> import cherrypy,os class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True def mymethod(self): return "This is my method!" mymethod.exposed = True os.system("V:/Chrome/chrome.exe http://localhost:8083/mymethod") cherrypy.server.socket_port = 8083 cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> 下一個範例, 特別將 mymethod.exposed = True 蓋去, 表示使用者無法直接利用瀏覽器呼叫, 而只能以 self.mymethod() 的方式, 由其他可以直接呼叫的方法中執行, 下列程式執行後, http://localhost:8083 與 http://localhost:8083/index 結果相同, 但是卻無法直接呼叫 mymethod(). <pre class="brush: python"> import cherrypy,os class HelloWorld(object): def index(self): #return "Hello World!" return self.mymethod() index.exposed = True def mymethod(self): return "This is my method!" #mymethod.exposed = True os.system("V:/Chrome/chrome.exe http://localhost:8083") os.system("V:/Chrome/chrome.exe http://localhost:8083/index") os.system("V:/Chrome/chrome.exe http://localhost:8083/mymethod") cherrypy.server.socket_port = 8083 cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> Python3 程式與 Javascript 程式交換變數, 使用者呼叫時, 由 URL 連結中輸入變數值, 然後交由 Python3 傳給 Javascript 程式. <pre class="brush: python"> import cherrypy,os class HelloWorld(object): def index(self,var1=None): outString = ''' <script> ''' outString += "document.write('"+var1+"');" outString += ''' </script> ''' return outString index.exposed = True os.system("V:/Chrome/chrome.exe http://localhost:8083?var1=123") os.system("V:/Chrome/chrome.exe http://localhost:8083?var1=Hello") cherrypy.server.socket_port = 8083 cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> 利用 cherrypy.request.method 來判定變數取值的方法, 這裡透過 GET 取得變數值, 另外以表單取變數值的方法稱為 POST. <pre class="brush: python"> import cherrypy,os class HelloWorld(object): def index(self,var1=None): outString = ''' <script> ''' outString += "document.write('"+var1+"');" outString += ''' </script> ''' outString += cherrypy.request.method return outString index.exposed = True os.system("V:/Chrome/chrome.exe http://localhost:8083?var1=123") cherrypy.server.socket_port = 8083 cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> ## CherryPy 與 session <pre class="brush: python"> import cherrypy,os class HelloWorld(object): # cherrypy 執行的設定檔案, 以 dictionay 資料格式設定 _cp_config = { # 配合 utf-8 格式之表單內容 # 若沒有 utf-8 encoding 設定,則表單不可輸入中文 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', 'tools.sessions.locking' : 'explicit', 'tools.sessions.storage_path' : 'v:/tmp', 'tools.sessions.timeout' : 60 } def index(self,var1=None): outString = ''' <script> ''' if var1 != None: outString += "document.write('"+var1+"');" else: outString += "document.write('no var1 value');" outString += ''' </script> ''' outString += cherrypy.request.method count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count outString += " count is now:"+str(count) return outString index.exposed = True def reset_session(self): # delete all session data #cherrypy.session.delete() # only delete 'count' session del cherrypy.session['count'] return "count is deleted" reset_session.exposed = True os.system("V:/Chrome/chrome.exe http://localhost:8083?var1=123") cherrypy.server.socket_port = 8083 cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> 再加上客製化錯誤訊息: <pre class="brush: python"> #coding: utf-8 import cherrypy,os class HelloWorld(object): # cherrypy 執行的設定檔案, 以 dictionay 資料格式設定 _cp_config = { # 配合 utf-8 格式之表單內容 # 若沒有 utf-8 encoding 設定,則表單不可輸入中文 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', 'tools.sessions.locking' : 'explicit', 'tools.sessions.storage_path' : 'v:/tmp', 'tools.sessions.timeout' : 60 } def index(self,**var): outString = ''' <script> ''' try: if var['var1'] != None: outString += "document.write('"+var['var1']+"');" else: outString += "document.write('no var1 value');" outString += ''' </script> ''' except: outString += ''' </script> ''' pass outString += cherrypy.request.method count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count outString += " count is now:"+str(count) return outString index.exposed = True def reset_session(self): # delete all session data #cherrypy.session.delete() # only delete 'count' session del cherrypy.session['count'] return "count is deleted" reset_session.exposed = True # 客製化的 error 402 函式 def error_page_402(status, message, traceback, version): return "Error %s - 抱歉! 發生 402 錯誤!" % status cherrypy.config.update({'error_page.402': error_page_402}) def error_page_404(status, message, traceback, version): return "Error %s - 抱歉! 發生 404 錯誤!" % status cherrypy.config.update({'error_page.404': error_page_404}) os.system("V:/Chrome/chrome.exe http://localhost:8083?var1=123") cherrypy.server.socket_port = 8083 cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> ## CherryPy 以 https 啟動 CherryPy 程式以 http 及 https 模式啟動 <pre class="brush: python"> #coding: utf-8 import cherrypy,os class HelloWorld(object): # cherrypy 執行的設定檔案, 以 dictionay 資料格式設定 _cp_config = { # 配合 utf-8 格式之表單內容 # 若沒有 utf-8 encoding 設定,則表單不可輸入中文 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', 'tools.sessions.locking' : 'explicit', 'tools.sessions.storage_path' : 'v:/tmp', 'tools.sessions.timeout' : 60 } def index(self,**var): outString = ''' <script> ''' try: if var['var1'] != None: outString += "document.write('"+var['var1']+"');" else: outString += "document.write('no var1 value');" outString += ''' </script> ''' except: outString += ''' </script> ''' pass outString += cherrypy.request.method count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count outString += " count is now:"+str(count) return outString index.exposed = True def reset_session(self): # delete all session data #cherrypy.session.delete() # only delete 'count' session del cherrypy.session['count'] return "count is deleted" reset_session.exposed = True # 客製化的 error 402 函式 def error_page_402(status, message, traceback, version): return "Error %s - 抱歉! 發生 402 錯誤!" % status cherrypy.config.update({'error_page.402': error_page_402}) def error_page_404(status, message, traceback, version): return "Error %s - 抱歉! 發生 404 錯誤!" % status cherrypy.config.update({'error_page.404': error_page_404}) os.system("V:/Chrome/chrome.exe http://localhost:8083?var1=123") os.system("V:/Chrome/chrome.exe https://localhost:8093?var1=123") cherrypy.config.update({'server.socket_port': 8083, 'server.socket_host': '127.0.0.1'}) from cherrypy._cpserver import Server server = Server() server.socket_port = 8093 server.socket_host = '127.0.0.1' server.ssl_certificate = 'v:/ssl_cert.pem' server.ssl_private_key = 'v:/ssl_cert.pem' server.subscribe() #cherrypy.server.socket_port = 8083 #cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> 僅使用 https 模式啟動上述 CherryPy 程式: <pre class="brush: python"> #coding: utf-8 import cherrypy,os class HelloWorld(object): # cherrypy 執行的設定檔案, 以 dictionay 資料格式設定 _cp_config = { # 配合 utf-8 格式之表單內容 # 若沒有 utf-8 encoding 設定,則表單不可輸入中文 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', 'tools.sessions.locking' : 'explicit', 'tools.sessions.storage_path' : 'v:/tmp', 'tools.sessions.timeout' : 60 } def index(self,**var): outString = ''' <script> ''' try: if var['var1'] != None: outString += "document.write('"+var['var1']+"');" else: outString += "document.write('no var1 value');" outString += ''' </script> ''' except: outString += ''' </script> ''' pass outString += cherrypy.request.method count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count outString += " count is now:"+str(count) return outString index.exposed = True def reset_session(self): # delete all session data #cherrypy.session.delete() # only delete 'count' session del cherrypy.session['count'] return "count is deleted" reset_session.exposed = True # 客製化的 error 402 函式 def error_page_402(status, message, traceback, version): return "Error %s - 抱歉! 發生 402 錯誤!" % status cherrypy.config.update({'error_page.402': error_page_402}) def error_page_404(status, message, traceback, version): return "Error %s - 抱歉! 發生 404 錯誤!" % status cherrypy.config.update({'error_page.404': error_page_404}) os.system("V:/Chrome/chrome.exe https://localhost:8093?var1=123") cherrypy.config.update({'server.socket_port': 8093, 'server.socket_host': '127.0.0.1', 'server.ssl_certificate': 'v:/ssl_cert.pem', 'server.ssl_private_key': 'v:/ssl_cert.pem'}) #cherrypy.server.socket_port = 8083 #cherrypy.server.socket_host = '127.0.0.1' cherrypy.quickstart(HelloWorld()) </pre> 也可以採用下列方式, 將 CherryPy 程式以 https 模式啟動: <pre class="brush: python"> #coding: utf-8 import cherrypy,os class HelloWorld(object): # cherrypy 執行的設定檔案, 以 dictionay 資料格式設定 _cp_config = { # 配合 utf-8 格式之表單內容 # 若沒有 utf-8 encoding 設定,則表單不可輸入中文 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', 'tools.sessions.locking' : 'explicit', 'tools.sessions.storage_path' : 'v:/tmp', 'tools.sessions.timeout' : 60 } def index(self,**var): outString = ''' <script> ''' try: if var['var1'] != None: outString += "document.write('"+var['var1']+"');" else: outString += "document.write('no var1 value');" outString += ''' </script> ''' except: outString += ''' </script> ''' pass outString += cherrypy.request.method count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count outString += " count is now:"+str(count) return outString index.exposed = True def reset_session(self): # delete all session data #cherrypy.session.delete() # only delete 'count' session del cherrypy.session['count'] return "count is deleted" reset_session.exposed = True # 客製化的 error 402 函式 def error_page_402(status, message, traceback, version): return "Error %s - 抱歉! 發生 402 錯誤!" % status cherrypy.config.update({'error_page.402': error_page_402}) def error_page_404(status, message, traceback, version): return "Error %s - 抱歉! 發生 404 錯誤!" % status cherrypy.config.update({'error_page.404': error_page_404}) os.system("V:/Chrome/chrome.exe https://localhost:8093?var1=123") cherrypy.server.socket_port = 8093 cherrypy.server.socket_host = '127.0.0.1' cherrypy.server.ssl_certificate = 'v:/ssl_cert.pem' cherrypy.server.ssl_private_key = 'v:/ssl_cert.pem' cherrypy.quickstart(HelloWorld()) </pre> CherryPy 的虛擬主機 (Virtual Hosting) 設定方法: <pre class="brush: python"> #coding: utf-8 import cherrypy,os ''' CherryPy 的虛擬主機對應 1. 修改 Windows C:\WINDOWS\system32\drivers\etc\hosts 檔案 127.0.0.1 server1.my.domain 127.0.0.1 server2.my.domain 2. 以下設定將可透過 https://server1.my.domain:8093 https://server2.my.domain:8093 連結到同一 CherryPy 網際程式的不同對應物件方法 ''' class Root(object): def __init__(self): self.server1 = HelloWorld1() self.server2 = HelloWorld2() class HelloWorld1(object): # cherrypy 執行的設定檔案, 以 dictionay 資料格式設定 _cp_config = { # 配合 utf-8 格式之表單內容 # 若沒有 utf-8 encoding 設定,則表單不可輸入中文 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', 'tools.sessions.locking' : 'explicit', 'tools.sessions.storage_path' : 'v:/tmp', 'tools.sessions.timeout' : 60 } def index(self,**var): outString = '''這是 server1.my.domain <script> ''' try: if var['var1'] != None: outString += "document.write('"+var['var1']+"');" else: outString += "document.write('no var1 value');" outString += ''' </script> ''' except: outString += ''' </script> ''' pass outString += cherrypy.request.method count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count outString += " count is now:"+str(count) return outString index.exposed = True def reset_session(self): # delete all session data #cherrypy.session.delete() # only delete 'count' session del cherrypy.session['count'] return "count is deleted" reset_session.exposed = True # 客製化的 error 402 函式 def error_page_402(status, message, traceback, version): return "Error %s - 抱歉! 發生 402 錯誤!" % status cherrypy.config.update({'error_page.402': error_page_402}) def error_page_404(status, message, traceback, version): return "Error %s - 抱歉! 發生 404 錯誤!" % status cherrypy.config.update({'error_page.404': error_page_404}) class HelloWorld2(object): # cherrypy 執行的設定檔案, 以 dictionay 資料格式設定 _cp_config = { # 配合 utf-8 格式之表單內容 # 若沒有 utf-8 encoding 設定,則表單不可輸入中文 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', 'tools.sessions.locking' : 'explicit', 'tools.sessions.storage_path' : 'v:/tmp', 'tools.sessions.timeout' : 60 } def index(self,**var): outString = '''這是 server2.my.domain <script> ''' try: if var['var1'] != None: outString += "document.write('"+var['var1']+"');" else: outString += "document.write('no var1 value');" outString += ''' </script> ''' except: outString += ''' </script> ''' pass outString += cherrypy.request.method count = cherrypy.session.get('count', 0) + 1 cherrypy.session['count'] = count outString += " count is now:"+str(count) return outString index.exposed = True def reset_session(self): # delete all session data #cherrypy.session.delete() # only delete 'count' session del cherrypy.session['count'] return "count is deleted" reset_session.exposed = True # 客製化的 error 402 函式 def error_page_402(status, message, traceback, version): return "Error %s - 抱歉! 發生 402 錯誤!" % status cherrypy.config.update({'error_page.402': error_page_402}) def error_page_404(status, message, traceback, version): return "Error %s - 抱歉! 發生 404 錯誤!" % status cherrypy.config.update({'error_page.404': error_page_404}) os.system("V:/Chrome/chrome.exe https://server1.my.domain:8093?var1=123") os.system("V:/Chrome/chrome.exe https://server2.my.domain:8093?var1=123") hostmap = { 'server1.my.domain:8093': '/server1', 'server2.my.domain:8093': '/server2', } config = { 'request.dispatch': cherrypy.dispatch.VirtualHost(**hostmap) } cherrypy.server.socket_port = 8093 cherrypy.server.socket_host = '127.0.0.1' cherrypy.server.ssl_certificate = 'v:/ssl_cert.pem' cherrypy.server.ssl_private_key = 'v:/ssl_cert.pem' #cherrypy.quickstart(HelloWorld()) cherrypy.quickstart(Root(), '/', {'/': config}) </pre> 以下則為 CherryPy 網際留言簿程式範例: <pre class="brush: python"> #coding: utf-8 # # note.py CherryPy 應用範例程式 ''' 本程式在展示 CherryPy 程式的: 1. session 用法 2. 靜態內容引用方法 3. 全域設定與靜態內容設定方法 4. 自動處理數列頁面內容的用法 5. 表單列印與資料處理方法 6. 重新導向用法 以及 Python3 程式的: 1. 重新定義物件 __str__ 字串傳回方法 2. 留言時間資料的字串轉換處理 3. 數列資料的反向排序與附加 ''' # # 導入 Python 標準模組 import os, time # 導入 cherrypy 模組 import cherrypy # 確定程式檔案所在目錄 _curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) # _notes 為一全域數列變數, 主要利用記憶體儲存使用者的留言內容 _notes = [] # 相關超文件變數 _header = """ <html> <head> <title>留言簿</title> <link rel="stylesheet" type="text/css" href="/style.css"></link> </head> <body> <div class="container">""" _footer = """ </div> </body> </html>""" _note_form = """ <div class="form"> <form method="post" action="post" class="form"> <input type="text" value="請在此留言..." name="text" size="60"></input> <input type="submit" value="Add"></input> </form> </div>""" _author_form = """ <div class="form"> <form method="post" action="set"> <input type="text" name="name"></input> <input type="submit" value="Switch"></input> </form> </div>""" _note_view = """ <br /> <div> %s <div class="info">%s - %s <a href="/note/%d">(%d)</a></div> </div>""" ############################################################### # 唯一的 domain object (也可稱為 Model) ############################################################### class Note(object): def __init__(self, author, note): self.id = None self.author = author self.note = note self.timestamp = time.gmtime(time.time()) # 改寫物件字串資料列出的傳回內容 def __str__(self): return self.note ############################################################### # Note 應用程式的主要進入點 ############################################################### class NoteApp: """ 打算用 CherryPy 啟動的程式物件 """ # 啟動 session 工具 # 採用 utf-8 編碼 _cp_config = {'tools.sessions.on': True, # 若無 utf-8 編碼指定, 無法處理中文 'tools.encode.encoding': 'utf-8' } def _render_note(self, note): """將 note 轉為頁面的 html 內容, 輸入為 3 個字串與兩個數字""" return _note_view % (note, note.author, # 依照格式列出留言時間 time.strftime("%a, %d %b %Y %H:%M:%S", note.timestamp), note.id, note.id) # 這是前置指令用法, 與 index.exposed = True 功能相同 @cherrypy.expose def index(self): # 取出存在 session 的作者名稱, 若無資料則將 author 設為 None author = cherrypy.session.get('author', None) # 頁面數列先放入超文件標頭 page = [_header] # 若有作者資料則附加在 page 數列, 否則要求輸入 if author: page.append(""" <div><span>您好 %s, 請輸入留言. <a href="author">更改作者代號</a>.</span></div>""" % (author,)) page.append(_note_form) else: page.append("""<div><a href="author">設定作者代號</a></span></div>""") # 以反向排列將 notes 附加到 page notes = _notes[:] notes.reverse() for note in notes: page.append(self._render_note(note)) # 在頁面最後附上 _footer page.append(_footer) # CherryPy 會自動處理所傳回的 page 數列資料 return page @cherrypy.expose def note(self, id): # 根據代號取出留言 try: note = _notes[int(id)] except: # 若為無效 id, 則傳回找不到資料之訊息 raise cherrypy.NotFound return [_header, self._render_note(note), _footer] @cherrypy.expose def post(self, text): author = cherrypy.session.get('author', None) # 若 session 無作者資料, 則導向設定作者代號頁面 if not author: raise cherrypy.HTTPRedirect('/author') # Note 為 domain object Note 的一個案例 note = Note(author, text) _notes.append(note) note.id = _notes.index(note) raise cherrypy.HTTPRedirect('/') class Author(object): @cherrypy.expose def index(self): return [_header, _author_form, _footer] @cherrypy.expose def set(self, name): cherrypy.session['author'] = name return [_header, """ %s 歡迎蒞臨! 請留言 <a href="/" title="Home">留言</a>. """ % (name,), _footer] if __name__ == '__main__': # 全域設定 global_conf = { 'global': { 'autoreload.on': False, 'server.socket_host': '127.0.0.1', 'server.socket_port': 8083, 'server.protocol_version': 'HTTP/1.1' }} application_conf = { '/style.css': { 'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(_curdir, 'style.css'), } } # 更新 CherryPy 的全域設定 cherrypy.config.update(global_conf) # 建立一個應用案例 note_app = NoteApp() # 附加一個作者類別案例到主應用案例中的 author 屬性 note_app.author = Author() # 以 chrome 開啟網頁 os.system("V:/Chrome/chrome.exe http://localhost:8083") # 以 application_conf 中的設定啟動 note_app cherrypy.quickstart(note_app, config = application_conf) # 以下為 style.css 檔案內容 ''' html, body { background-color: #DEDEDE; padding: 0px; marging: 0px; height: 100%; } .container { border-color: #A1A1A1; border-style: solid; border-width: 1px; background-color: #FFF; margin: 10px 150px 10px 150px; height: 100%; width: 400px; } a:link { text-decoration: none; color: #A1A1A1; } a:visited { text-decoration: none; color: #A1A1A1; } a:hover { text-decoration: underline; } input { border: 1px solid #A1A1A1; } .form { margin: 5px 5px 5px 5px; } .info { font-size: 70%; color: #A1A1A1; } ''' </pre>
cad-lab/manual
content/admin-20160514.md
Markdown
agpl-3.0
26,312
class CreateJourneyPattern < ActiveRecord::Migration def self.up create_table :journey_patterns do |t| t.integer :route_id t.string :destination t.timestamps end add_column :route_segments, :journey_pattern_id, :integer add_column :route_segments, :segment_order, :integer end def self.down drop_table :journey_patterns remove_column :route_segments, :journey_pattern_id remove_column :route_segments, :segment_order end end
mysociety/fixmytransport
db/migrate/20110309102438_create_journey_pattern.rb
Ruby
agpl-3.0
480
<?php require_once 'invalidparameterexception.php'; require_once 'Validate.php'; require_once 'helper.php'; /** * OMB Notice representation * * This class represents an OMB notice. * * PHP version 5 * * LICENSE: This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package OMB * @author Adrian Lang <mail@adrianlang.de> * @copyright 2009 Adrian Lang * @license http://www.gnu.org/licenses/agpl.html GNU AGPL 3.0 **/ class OMB_Notice { protected $author; protected $uri; protected $content; protected $url; protected $license_url; protected $seealso_url; protected $seealso_disposition; protected $seealso_mediatype; protected $seealso_license_url; /* The notice as OMB param array. Cached and rebuild on usage. false while outdated. */ protected $param_array; /** * Constructor for OMB_Notice * * Initializes the OMB_Notice object with author, uri and content. * These parameters are mandatory for postNotice. * * @param object $author An OMB_Profile object representing the author of the * notice. * @param string $uri The notice URI as defined by the OMB. A unique and * unchanging identifier for a notice. * @param string $content The content of the notice. 140 chars recommended, but * there is no limit. * * @access public */ public function __construct($author, $uri, $content) { $this->content = $content; if (is_null($author)) { throw new OMB_InvalidParameterException('', 'notice', 'omb_listenee'); } $this->author = $author; if (!Validate::uri($uri)) { throw new OMB_InvalidParameterException($uri, 'notice', 'omb_notice'); } $this->uri = $uri; $this->param_array = false; } /** * Returns the notice as array * * The method returns an array which contains the whole notice as array. The * array is cached and only rebuilt on changes of the notice. * * @access public * @returns array The notice as parameter array */ public function asParameters() { if ($this->param_array !== false) { return $this->param_array; } $this->param_array = array( 'omb_notice' => $this->uri, 'omb_notice_content' => $this->content); if (!is_null($this->url)) $this->param_array['omb_notice_url'] = $this->url; if (!is_null($this->license_url)) $this->param_array['omb_notice_license'] = $this->license_url; if (!is_null($this->seealso_url)) { $this->param_array['omb_seealso'] = $this->seealso_url; /* This is actually a free interpretation of the OMB standard. We assume that additional seealso parameters are not of any use if seealso itself is not set. */ if (!is_null($this->seealso_disposition)) $this->param_array['omb_seealso_disposition'] = $this->seealso_disposition; if (!is_null($this->seealso_mediatype)) $this->param_array['omb_seealso_mediatype'] = $this->seealso_mediatype; if (!is_null($this->seealso_license)) $this->param_array['omb_seealso_license_url'] = $this->seealso_license; } return $this->param_array; } /** * Builds an OMB_Notice object from array * * The method builds an OMB_Notice object from the passed parameters array. The * array MUST provide a notice URI and content. The array fields HAVE TO be named * according to the OMB standard, i. e. omb_notice_* and omb_seealso_*. * * @param object $author An OMB_Profile object representing the author of the * notice. * @param string $parameters An array containing the notice parameters. * * @access public * * @returns OMB_Notice The built OMB_Notice. */ public static function fromParameters($author, $parameters) { $notice = new OMB_Notice($author, $parameters['omb_notice'], $parameters['omb_notice_content']); if (isset($parameters['omb_notice_url'])) { $notice->setURL($parameters['omb_notice_url']); } if (isset($parameters['omb_notice_license'])) { $notice->setLicenseURL($parameters['omb_notice_license']); } if (isset($parameters['omb_seealso'])) { $notice->setSeealsoURL($parameters['omb_seealso']); } if (isset($parameters['omb_seealso_disposition'])) { $notice->setSeealsoDisposition($parameters['omb_seealso_disposition']); } if (isset($parameters['omb_seealso_mediatype'])) { $notice->setSeealsoMediatype($parameters['omb_seealso_mediatype']); } if (isset($parameters['omb_seealso_license'])) { $notice->setSeealsoLicenseURL($parameters['omb_seealso_license']); } return $notice; } public function getAuthor() { return $this->author; } public function getIdentifierURI() { return $this->uri; } public function getContent() { return $this->content; } public function getURL() { return $this->url; } public function getLicenseURL() { return $this->license_url; } public function getSeealsoURL() { return $this->seealso_url; } public function getSeealsoDisposition() { return $this->seealso_disposition; } public function getSeealsoMediatype() { return $this->seealso_mediatype; } public function getSeealsoLicenseURL() { return $this->seealso_license_url; } public function setURL($url) { if (!OMB_Helper::validateURL($url)) { throw new OMB_InvalidParameterException($url, 'notice', 'omb_notice_url'); } $this->url = $url; $this->param_array = false; } public function setLicenseURL($license_url) { if (!OMB_Helper::validateURL($license_url)) { throw new OMB_InvalidParameterException($license_url, 'notice', 'omb_notice_license'); } $this->license_url = $license_url; $this->param_array = false; } public function setSeealsoURL($seealso_url) { if (!OMB_Helper::validateURL($seealso_url)) { throw new OMB_InvalidParameterException($seealso_url, 'notice', 'omb_seealso'); } $this->seealso_url = $seealso_url; $this->param_array = false; } public function setSeealsoDisposition($seealso_disposition) { if ($seealso_disposition !== 'link' && $seealso_disposition !== 'inline') { throw new OMB_InvalidParameterException($seealso_disposition, 'notice', 'omb_seealso_disposition'); } $this->seealso_disposition = $seealso_disposition; $this->param_array = false; } public function setSeealsoMediatype($seealso_mediatype) { if (!OMB_Helper::validateMediaType($seealso_mediatype)) { throw new OMB_InvalidParameterException($seealso_mediatype, 'notice', 'omb_seealso_mediatype'); } $this->seealso_mediatype = $seealso_mediatype; $this->param_array = false; } public function setSeealsoLicenseURL($seealso_license_url) { if (!OMB_Helper::validateURL($seealso_license_url)) { throw new OMB_InvalidParameterException($seealso_license_url, 'notice', 'omb_seealso_license'); } $this->seealso_license_url = $seealso_license_url; $this->param_array = false; } } ?>
singpolyma/mnw
extlib/libomb/notice.php
PHP
agpl-3.0
7,783
#include "Plater/PlaterObject.hpp" #include "Geometry.hpp" #include "ExPolygon.hpp" #include "libslic3r.h" #include "Log.hpp" #include "misc_ui.hpp" namespace Slic3r { namespace GUI { Slic3r::ExPolygonCollection& PlaterObject::make_thumbnail(std::shared_ptr<Slic3r::Model> model, int obj_idx) { // make method idempotent this->thumbnail.expolygons.clear(); auto mesh {model->objects[obj_idx]->raw_mesh()}; auto model_instance {model->objects[obj_idx]->instances[0]}; // Apply any x/y rotations and scaling vector if this came from a 3MF object. mesh.rotate_x(model_instance->x_rotation); mesh.rotate_y(model_instance->y_rotation); mesh.scale(model_instance->scaling_vector); if (mesh.facets_count() <= 5000) { auto area_threshold {scale_(1.0)}; ExPolygons tmp {}; for (auto p : mesh.horizontal_projection()) { if (p.area() >= area_threshold) tmp.push_back(p); } // return all polys bigger than the area this->thumbnail.append(tmp); this->thumbnail.simplify(0.5); } else { auto convex_hull {Slic3r::ExPolygon(mesh.convex_hull())}; this->thumbnail.append(convex_hull); } return this->thumbnail; } Slic3r::ExPolygonCollection& PlaterObject::transform_thumbnail(std::shared_ptr<Slic3r::Model> model, int obj_idx) { if (this->thumbnail.expolygons.size() == 0) return this->thumbnail; const auto& model_object {model->objects[obj_idx] }; const auto& model_instance {model_object->instances[0]}; // the order of these transformations MUST be the same everywhere, including // in Slic3r::Print->add_model_object() auto t {this->thumbnail}; t.rotate(model_instance->rotation, Slic3r::Point(0,0)); t.scale(model_instance->scaling_factor); this->transformed_thumbnail = t; return this->transformed_thumbnail; } bool PlaterObject::instance_contains(Slic3r::Point point) const { return std::any_of(this->instance_thumbnails.cbegin(), this->instance_thumbnails.cend(), [point](const ExPolygonCollection ep) { return ep.contains(point); }); } PlaterObject& PlaterObject::operator=(const PlaterObject& other) { if (&other == this) return *this; this->name = std::string(other.name); this->identifier = other.identifier; this->input_file = std::string(other.input_file); this->input_file_obj_idx = other.input_file_obj_idx; this->selected = false; this->selected_instance = -1; this->thumbnail = Slic3r::ExPolygonCollection(other.thumbnail); this->transformed_thumbnail = Slic3r::ExPolygonCollection(other.transformed_thumbnail); this->instance_thumbnails = std::vector<Slic3r::ExPolygonCollection>(other.instance_thumbnails); return *this; } PlaterObject& PlaterObject::operator=(PlaterObject&& other) { this->name = std::string(other.name); this->identifier = other.identifier; this->input_file = std::string(other.input_file); this->input_file_obj_idx = other.input_file_obj_idx; this->selected = std::move(other.selected); this->selected_instance = std::move(other.selected); this->thumbnail = Slic3r::ExPolygonCollection(other.thumbnail); this->transformed_thumbnail = Slic3r::ExPolygonCollection(other.transformed_thumbnail); this->instance_thumbnails = std::vector<Slic3r::ExPolygonCollection>(other.instance_thumbnails); return *this; } } } // Namespace Slic3r::GUI
lordofhyphens/Slic3r
src/GUI/Plater/PlaterObject.cpp
C++
agpl-3.0
3,464
<?php /** * layer for input data */ abstract class BaseInputData { /** * @param string $name * @param string $type * @param string $method * @return mixed */ abstract public function getValue($name, $type = null, $method = null); /** * @access protected * * @param string $var * @param string $type * @return string */ protected function _cleanValue($var, $type = null) { if (!is_null($type)) { if (!settype($var, $type)) { return null; } } return $var; } }
eliasrosa/webmail
pub/core/base/base_input_data.php
PHP
agpl-3.0
625
begin require 'sass' rescue LoadError require 'rubygems' require 'sass' end
anuragsolanki/ofri-Haus
vendor/gems/compass-0.10.5/lib/compass/dependencies.rb
Ruby
agpl-3.0
82
/* * Copyright (c) 2005 University of Utah and the Flux Group. * * {{{EMULAB-LICENSE * * This file is part of the Emulab network testbed software. * * This file is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This file is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this file. If not, see <http://www.gnu.org/licenses/>. * * }}} */ /** * @file test_path.c * * Path planning testing tool. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "log.h" #include "obstacles.h" #include "pathPlanning.h" int debug = 0; #if defined(SIMPLE_PATH) #include "simple_path.c" #elif defined(MULTI_PATH) #include "multi_path.c" #else #error "No bounds/obstacles/robots defined!" #endif static void usage(const char *progname) { fprintf(stderr, "Usage: %s [OPTIONS]\n" "\n" "Use the path planner to move a robot from the first position\n" "to the second position and back again.\n" "\n" "Options:\n" " -h\t\tPrint this message\n" " -d\t\tIncrease debugging level and do not daemonize\n" " -i iter\tMaximum number of iterations\n" " -x float\tFirst X position for the robot\n" " -y float\tFirst Y position for the robot\n" " -u float\tSecond X position for the robot\n" " -v float\tSecond Y position for the robot\n", progname); } int main(int argc, char *argv[]) { int c, lpc, iterations = 50, retval = EXIT_SUCCESS; struct path_plan pp_init, pp; loginit(0, NULL); ob_init(); for (lpc = 0; obstacles[lpc].id != 0; lpc++) { ob_add_obstacle(&obstacles[lpc]); } pp_data.ppd_bounds = bounds; pp_data.ppd_bounds_len = 1; pp_data.ppd_max_distance = 10; memset(&pp_init, 0, sizeof(pp)); pp_init.pp_robot = &robots[0]; pp_init.pp_speed = 0.2; while ((c = getopt(argc, argv, "di:x:y:u:v:")) != -1) { switch (c) { case 'd': debug += 1; break; case 'i': sscanf(optarg, "%d", &iterations); break; case 'x': sscanf(optarg, "%f", &pp_init.pp_actual_pos.x); break; case 'y': sscanf(optarg, "%f", &pp_init.pp_actual_pos.y); break; case 'u': sscanf(optarg, "%f", &pp_init.pp_goal_pos.x); break; case 'v': sscanf(optarg, "%f", &pp_init.pp_goal_pos.y); break; case 'h': default: usage(argv[0]); exit(0); break; } } if ((pp_init.pp_actual_pos.x == pp_init.pp_goal_pos.x) && (pp_init.pp_actual_pos.y == pp_init.pp_goal_pos.y)) { usage(argv[0]); exit(0); } pp = pp_init; for (lpc = 0; (lpc < iterations) && ((pp.pp_actual_pos.x != pp.pp_goal_pos.x) || (pp.pp_actual_pos.y != pp.pp_goal_pos.y)); lpc++) { switch (pp_plot_waypoint(&pp)) { case PPC_WAYPOINT: case PPC_NO_WAYPOINT: pp.pp_actual_pos = pp.pp_waypoint; break; case PPC_BLOCKED: case PPC_GOAL_IN_OBSTACLE: lpc = iterations; break; } } info("-reverse-\n"); pp = pp_init; pp.pp_actual_pos = pp_init.pp_goal_pos; pp.pp_goal_pos = pp_init.pp_actual_pos; for (lpc = 0; (lpc < iterations) && ((pp.pp_actual_pos.x != pp.pp_goal_pos.x) || (pp.pp_actual_pos.y != pp.pp_goal_pos.y)); lpc++) { switch (pp_plot_waypoint(&pp)) { case PPC_WAYPOINT: case PPC_NO_WAYPOINT: pp.pp_actual_pos = pp.pp_waypoint; break; case PPC_BLOCKED: case PPC_GOAL_IN_OBSTACLE: lpc = iterations; break; } } return retval; }
nmc-probe/emulab-nome
robots/rmcd/test_path.c
C
agpl-3.0
3,941
<!DOCTYPE html> <html> <head> <style type="text/css"> {% include "includes/office/pdf_style.css" %} </style> </head> <body> {% include "includes/office/pdf_header.html" %} <h1 class="headline">L'entreprise <span class="company-name">{{ company.name }}</span> est recommandée (*) par La Bonne Boite</h1> {% include "includes/office/info_table.html" %} <h2>La voie du succès pour travailler chez <span class="company-name">{{ company.name }}</span></h2> <table class="planning"> <tr> <th style="width: 15%;" class="bigcell">Etape</th> <th style="width: 35%;" class="bigcell">Action</th> <th style="width: 15%;" class="bigcell">Réalisé</th> <th style="width: 35%;" class="bigcell">Commentaire</th> </tr> <tr> <td class="done bigcell">1</td> <td class="done">Trouver une entreprise qui embauche via <img src="{{ url_for('static',filename='images/logo-lbb-vertical.jpg') }}" width="128"></td> <td class="done"></td> <td class="done" style="color: #19c158;"><b>Bravo, vous avez déjà réussi la première étape !</b></td> </tr> {% for stage in stages %} <tr> <td class="bigcell">{{ loop.index + 1 }}</td> <td>{{ stage }}</td> <td>.................</td> <td>.................</td> </tr> {% endfor %} </table> <div>* : En effet, nos données indiquent des possibilités d'embauche dans les 6 prochains mois. Attention, il ne s'agit pas d'une garantie d'emploi et vous devez faire le nécessaire pour convaincre cette entreprise de vous embaucher.</div> <div style="text-align: center;">Avez-vous une question ou une suggestion pour La Bonne Boite ? Consultez notre <a href="{{ url_for('root.faq', _external=True) }}">F.A.Q</a>.</div> </body> </html>
StartupsPoleEmploi/labonneboite
labonneboite/web/templates/office/pdf_detail.html
HTML
agpl-3.0
1,868
import domObject = CKEDITOR.dom.domObject; import editor = CKEDITOR.editor; export class AntragsgruenEditor { private editor: editor; private $el: JQuery; private static ckeditor_strip(html: string): string { let tmp = document.createElement("div"); tmp.innerHTML = html; if (tmp.textContent == '' && typeof tmp.innerText == 'undefined') { return ''; } return tmp.textContent || tmp.innerText; } private static ckeditor_charcount(text: string): number { let normalizedText = text.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "").replace("&nbsp;", ""); normalizedText = AntragsgruenEditor.ckeditor_strip(normalizedText).replace(/^([\s\t\r\n]*)$/, ""); return normalizedText.length; } private $currCounter: JQuery; private $warning: JQuery; private $submit: JQuery; private maxLen: number; private maxLenSoft: boolean; private maxLenOnChange() { let currLen = AntragsgruenEditor.ckeditor_charcount(this.editor.getData()); this.$currCounter.text(currLen); if (currLen > this.maxLen) { this.$warning.removeClass('hidden'); if (!this.maxLenSoft) { this.$submit.prop("disabled", true); } } else { this.$warning.addClass('hidden'); if (!this.maxLenSoft) { this.$submit.prop("disabled", false); } } } private initMaxLen() { let $fieldset = this.$el.parents(".wysiwyg-textarea").first(); if (!$fieldset.data("max-len")) { return; } this.maxLen = $fieldset.data("max-len"); this.maxLenSoft = false; this.$warning = $fieldset.find('.maxLenTooLong'); this.$submit = this.$el.parents("form").first().find("button[type=submit]"); this.$currCounter = $fieldset.find(".maxLenHint .counter"); if (this.maxLen < 0) { this.maxLenSoft = true; this.maxLen = -1 * this.maxLen; } this.editor.on('change', this.maxLenOnChange.bind(this)); this.maxLenOnChange(); } private static createConfig(title: string, noStrike: boolean, trackChanged: boolean, allowDiffFormattings: boolean, autocolorize: boolean, enterMode: any): any { let ckeditorConfig = { coreStyles_strike: { element: 'span', attributes: {'class': 'strike'}, overrides: 'strike' }, coreStyles_underline: { element: 'span', attributes: {'class': 'underline'} }, toolbarGroups: [ {name: 'tools'}, {name: 'document', groups: ['mode', 'document', 'doctools']}, //{name: 'clipboard', groups: ['clipboard', 'undo']}, //{name: 'editing', groups: ['find', 'selection', 'spellchecker']}, //{name: 'forms'}, {name: 'basicstyles', groups: ['basicstyles', 'cleanup']}, {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi']}, {name: 'links'}, {name: 'insert'}, {name: 'styles'}, {name: 'colors'}, {name: 'autocolorize'}, {name: 'others'} ], removePlugins: 'stylescombo,save,showblocks,specialchar,about,preview,pastetext,magicline,liststyle', extraPlugins: 'tabletools,listitemstyle', scayt_sLang: 'de_DE', title: title, enterMode: enterMode, shiftEnterMode: (enterMode === CKEDITOR.ENTER_BR ? CKEDITOR.ENTER_P : CKEDITOR.ENTER_BR), }; let strikeEl = (noStrike ? '' : ' s'), strikeClass = (noStrike ? '' : ',strike'), autocolorizeClass = (autocolorize ? ',adminTyped' : ''), allowedContent = ''; if (trackChanged || allowDiffFormattings) { allowedContent = 'strong' + strikeEl + ' em u sub sup;' + 'h1 h2 h3 h4(ice-ins,ice-del,ice-cts,appendHint,appendedCollision,moved);' + 'ol[start,data-*](ice-ins,ice-del,ice-cts,appendHint,appendedCollision,moved,decimalDot,decimalCircle,lowerAlpha,upperAlpha);' + 'li[value,data-*](ice-ins,ice-del,ice-cts,appendHint,appendedCollision,moved);' + 'ul[data-*](ice-ins,ice-del,ice-cts,appendHint,appendedCollision,moved);' + //'table tr td th tbody thead caption [border] {margin,padding,width,height,border,border-spacing,border-collapse,align,cellspacing,cellpadding};' + 'div [data-*](collidingParagraph,hasCollisions,moved);' + 'p blockquote [data-*](ice-ins,ice-del,ice-cts,appendHint,appendedCollision,collidingParagraphHead,moved){border,margin,padding};' + 'span[data-*](ice-ins,ice-del,ice-cts,appendHint,appendedCollision,underline' + strikeClass + ',subscript,superscript' + autocolorizeClass + ');' + 'a[href,data-*](ice-ins,ice-del,ice-cts,appendHint,appendedCollision);' + 'br ins del[data-*](ice-ins,ice-del,ice-cts,appendHint,appendedCollision);'; } else { allowedContent = 'strong' + strikeEl + ' em u sub sup;' + 'ul;' + 'ol[start](decimalDot,decimalCircle,lowerAlpha,upperAlpha);' + 'li[value];' + 'h2 h3 h4;' + //'table tr td th tbody thead caption [border] {margin,padding,width,height,border,border-spacing,border-collapse,align,cellspacing,cellpadding};' + 'p blockquote {border,margin,padding};' + 'span(underline' + strikeClass + ',subscript,superscript' + autocolorizeClass + ');' + 'a[href];'; } if (trackChanged) { ckeditorConfig.extraPlugins += ',lite'; ckeditorConfig['lite'] = {tooltips: false}; // Undo and Track changes are incompatible // https://github.com/CatoTH/antragsgruen/issues/224 // http://dev.ckeditor.com/ticket/14854 ckeditorConfig['removePlugins'] += ',undo'; } else { ckeditorConfig['removePlugins'] += ',lite'; } if (autocolorize) { ckeditorConfig['extraPlugins'] += ',autocolorize'; } ckeditorConfig['allowedContent'] = allowedContent; // ckeditorConfig.pasteFilter = allowedContent; // Seems to break copy/pasting some <strong> formatting in 4.5.11 return ckeditorConfig } public getEditor(): editor { return this.editor; } public static destroyInstanceById(id: string) { let editor = CKEDITOR.instances[id]; editor.destroy(); let $el: JQuery = $("#" + id); $el.data("ckeditor_initialized", "0"); $el.attr("contenteditable", "false"); } constructor(id) { this.$el = $("#" + id); let initialized = this.$el.data("ckeditor_initialized"); if (typeof (initialized) != "undefined" && initialized == "1") { console.error("Already initialized: " + id); return; } this.$el.data("ckeditor_initialized", "1"); this.$el.attr("contenteditable", "true"); let ckeditorConfig = AntragsgruenEditor.createConfig( this.$el.attr("title"), (this.$el.data("no-strike") == '1'), (this.$el.data('track-changed') == '1'), (this.$el.data('allow-diff-formattings') == '1'), (this.$el.data('autocolorize') == '1'), (this.$el.data('enter-mode') == 'br' ? CKEDITOR.ENTER_BR : CKEDITOR.ENTER_P) ); // This prevents strange behavior in chrome: after switching from the WYSIWYG editor field to a regular input, // the focus of the new input field was lost after 200ms let focusManager: any = CKEDITOR.focusManager; focusManager._.blurDelay = 0; this.editor = CKEDITOR.inline(id, ckeditorConfig); this.initMaxLen(); } }
CatoTH/antragsgruen
web/typescript/shared/AntragsgruenEditor.ts
TypeScript
agpl-3.0
8,141
/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Implementation of QGCLinkConfiguration * @author Gus Grubba <mavlink@grubba.com> */ #include "SettingsDialog.h" #include "QGCLinkConfiguration.h" #include "ui_QGCLinkConfiguration.h" #include "QGCCommConfiguration.h" #include "QGCMessageBox.h" QGCLinkConfiguration::QGCLinkConfiguration(QWidget *parent) : QWidget(parent), _ui(new Ui::QGCLinkConfiguration) { // Stop automatic link updates while this UI is up LinkManager::instance()->suspendConfigurationUpdates(true); _ui->setupUi(this); _viewModel = new LinkViewModel; _ui->linkView->setModel(_viewModel); _ui->connectLinkButton->setEnabled(false); _ui->delLinkButton->setEnabled(false); _ui->editLinkButton->setEnabled(false); } QGCLinkConfiguration::~QGCLinkConfiguration() { if(_viewModel) delete _viewModel; if(_ui) delete _ui; // Resume automatic link updates LinkManager::instance()->suspendConfigurationUpdates(false); } void QGCLinkConfiguration::on_delLinkButton_clicked() { QModelIndex index = _ui->linkView->currentIndex(); if(index.row() >= 0) { LinkConfiguration* config = _viewModel->getConfiguration(index.row()); if(config) { // Ask user if they are sure QMessageBox::StandardButton button = QGCMessageBox::question( tr("Delete Link Configuration"), tr("Are you sure you want to delete %1?\nDeleting a configuration will also disconnect it if connected.").arg(config->name()), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (button == QMessageBox::Yes) { // Get link attached to this configuration (if any) LinkInterface* iface = config->getLink(); if(iface) { // Disconnect it (if connected) LinkManager::instance()->disconnectLink(iface); } _viewModel->beginChange(); // Remove configuration LinkManager::instance()->removeLinkConfiguration(config); // Save list LinkManager::instance()->saveLinkConfigurationList(); _viewModel->endChange(); } } } _updateButtons(); } void QGCLinkConfiguration::on_linkView_clicked(const QModelIndex&) { _updateButtons(); } void QGCLinkConfiguration::on_connectLinkButton_clicked() { QModelIndex index = _ui->linkView->currentIndex(); if(index.row() >= 0) { LinkConfiguration* config = _viewModel->getConfiguration(index.row()); if(config) { LinkInterface* link = config->getLink(); if(link) { // Disconnect Link if (link->isConnected()) { LinkManager::instance()->disconnectLink(link); } } else { LinkInterface* link = LinkManager::instance()->createConnectedLink(config); if(link) { // Now go hunting for the parent so we can shut this down QWidget* pQw = parentWidget(); while(pQw) { SettingsDialog* pDlg = dynamic_cast<SettingsDialog*>(pQw); if(pDlg) { pDlg->accept(); break; } pQw = pQw->parentWidget(); } } } } } _updateButtons(); } void QGCLinkConfiguration::on_editLinkButton_clicked() { QModelIndex index = _ui->linkView->currentIndex(); _editLink(index.row()); } void QGCLinkConfiguration::_fixUnnamed(LinkConfiguration* config) { Q_ASSERT(config != NULL); //-- Check for "Unnamed" if (config->name() == tr("Unnamed")) { switch(config->type()) { #ifndef __ios__ case LinkConfiguration::TypeSerial: { QString tname = dynamic_cast<SerialConfiguration*>(config)->portName(); #ifdef Q_OS_WIN32 tname.replace("\\\\.\\", ""); #else tname.replace("/dev/cu.", ""); tname.replace("/dev/", ""); #endif config->setName(QString("Serial Device on %1").arg(tname)); break; } #endif case LinkConfiguration::TypeUdp: config->setName( QString("UDP Link on Port %1").arg(dynamic_cast<UDPConfiguration*>(config)->localPort())); break; case LinkConfiguration::TypeTcp: { TCPConfiguration* tconfig = dynamic_cast<TCPConfiguration*>(config); if(tconfig) { config->setName( QString("TCP Link %1:%2").arg(tconfig->address().toString()).arg((int)tconfig->port())); } } break; #ifdef QT_DEBUG case LinkConfiguration::TypeMock: config->setName( QString("Mock Link")); break; #endif } } } void QGCLinkConfiguration::on_addLinkButton_clicked() { QGCCommConfiguration* commDialog = new QGCCommConfiguration(this); if(commDialog->exec() == QDialog::Accepted) { // Save changes (if any) LinkConfiguration* config = commDialog->getConfig(); if(config) { _fixUnnamed(config); _viewModel->beginChange(); LinkManager::instance()->addLinkConfiguration(commDialog->getConfig()); LinkManager::instance()->saveLinkConfigurationList(); _viewModel->endChange(); } } _updateButtons(); } void QGCLinkConfiguration::on_linkView_doubleClicked(const QModelIndex &index) { _editLink(index.row()); } void QGCLinkConfiguration::_editLink(int row) { if(row >= 0) { LinkConfiguration* config = _viewModel->getConfiguration(row); if(config) { LinkConfiguration* tmpConfig = LinkConfiguration::duplicateSettings(config); QGCCommConfiguration* commDialog = new QGCCommConfiguration(this, tmpConfig); if(commDialog->exec() == QDialog::Accepted) { // Save changes (if any) if(commDialog->getConfig()) { _fixUnnamed(tmpConfig); _viewModel->beginChange(); config->copyFrom(tmpConfig); // Save it LinkManager::instance()->saveLinkConfigurationList(); _viewModel->endChange(); // Tell link about changes (if any) config->updateSettings(); } } // Discard temporary duplicate if(commDialog->getConfig()) delete commDialog->getConfig(); } } _updateButtons(); } void QGCLinkConfiguration::_updateButtons() { LinkConfiguration* config = NULL; QModelIndex index = _ui->linkView->currentIndex(); bool enabled = (index.row() >= 0); bool deleteEnabled = true; if(enabled) { config = _viewModel->getConfiguration(index.row()); if(config) { // Can't delete a dynamic link if(config->isDynamic()) { deleteEnabled = false; } LinkInterface* link = config->getLink(); if(link) { _ui->connectLinkButton->setText("Disconnect"); } else { _ui->connectLinkButton->setText("Connect"); } } } _ui->connectLinkButton->setEnabled(enabled); _ui->delLinkButton->setEnabled(config != NULL && deleteEnabled); _ui->editLinkButton->setEnabled(config != NULL); } LinkViewModel::LinkViewModel(QObject *parent) : QAbstractListModel(parent) { Q_UNUSED(parent); } int LinkViewModel::rowCount( const QModelIndex & parent) const { Q_UNUSED(parent); QList<LinkConfiguration*> cfgList = LinkManager::instance()->getLinkConfigurationList(); int count = cfgList.count(); return count; } QVariant LinkViewModel::data( const QModelIndex & index, int role) const { QList<LinkConfiguration*> cfgList = LinkManager::instance()->getLinkConfigurationList(); if (role == Qt::DisplayRole && index.row() < cfgList.count()) { QString name(cfgList.at(index.row())->name()); return name; } return QVariant(); } LinkConfiguration* LinkViewModel::getConfiguration(int row) { QList<LinkConfiguration*> cfgList = LinkManager::instance()->getLinkConfigurationList(); if(row < cfgList.count()) { return cfgList.at(row); } return NULL; }
TheIronBorn/qgroundcontrol
src/ui/QGCLinkConfiguration.cc
C++
agpl-3.0
9,677
package xyz.gupton.nickolas.beepsky.music.commands; import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import discord4j.core.object.VoiceState; import discord4j.core.object.entity.Guild; import discord4j.core.object.entity.Member; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.core.object.entity.channel.VoiceChannel; import discord4j.rest.util.Color; import java.util.regex.Pattern; import reactor.core.publisher.Mono; import xyz.gupton.nickolas.beepsky.BotUtils; import xyz.gupton.nickolas.beepsky.Command; import xyz.gupton.nickolas.beepsky.music.GuildMusicManager; import xyz.gupton.nickolas.beepsky.music.MusicHelper; public class QueueCommand implements Command { /** * Checks if the message was sent in a Guild * and if the command matches the requirements to queue the song. * * @param guild Guild, guild the message was received from, can be null for PM's. * @param author User, the author of the message. * @param channel MessageChannel, channel the message was received in. * @param message String, the contents of the message received. * @return boolean, true if the commands should be executed. */ @Override public boolean shouldExecute(Guild guild, User author, MessageChannel channel, String message) { String[] split = message.split(" ", 2); if (guild == null) { return false; } if (message.toLowerCase().startsWith(BotUtils.PREFIX + "queue") || message.toLowerCase().startsWith(BotUtils.PREFIX + "q")) { // If no track info is provided don't continue. if (split.length == 1) { BotUtils.sendMessage(channel, author, "Error queueing track:", "No track specified.", Color.RED); return false; } return true; } return false; } /** * Queue's the song provided by the message for the Guild provided, * and joins the authors VoiceChannel. * * @param guild Guild, guild the message was received from, can be null for PM's. * @param author User, the author of the message. * @param channel MessageChannel, channel the message was received in. * @param message String, the contents of the message received. */ @Override public void execute(Guild guild, User author, MessageChannel channel, String message) { // Setup variables String song = message.split(" ", 2)[1]; GuildMusicManager musicManager = MusicHelper.getGuildMusicManager(guild.getId()); final String track; // If the song matches a search string or a video URL its good to go, // otherwise prepend the ytsearch: string to it. if ((song.startsWith("ytsearch:") || song.startsWith("scsearch:")) // RegEx shamelessly copied from: // https://stackoverflow.com/questions/163360/regular-expression-to-match-urls-in-java && Pattern .compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]") .matcher(song).matches()) { track = song; } else { track = "ytsearch:" + song; } Member guildMember = guild.getMemberById(author.getId()).block(); if (guildMember == null) { BotUtils.sendMessage(channel, author, "Error queueing track:", "You do not exist.", Color.RED); return; } VoiceState guildMemberVoiceState = guildMember.getVoiceState().block(); if (guildMemberVoiceState == null) { BotUtils.sendMessage(channel, author, "Error queueing track:", "You are not in a voice channel.", Color.RED); return; } VoiceChannel userVoiceChannel = guildMemberVoiceState.getChannel().block(); if (userVoiceChannel == null) { BotUtils .sendMessage(channel, author, "Error queueing track:", "You are not in a voice channel.", Color.RED); return; } // If the bot is in a different voice channel than the user don't continue. Member self = guild.getMemberById(BotUtils.GATEWAY.getSelfId()).block(); if (self == null) { BotUtils.sendMessage(channel, author, "Error queueing track:", "I do not exist.", Color.RED); return; } VoiceState selfVoiceState = self.getVoiceState().block(); VoiceChannel botVoiceChannel = null; if (selfVoiceState != null) { botVoiceChannel = selfVoiceState.getChannel().block(); if (botVoiceChannel != null && !botVoiceChannel.getId().equals(userVoiceChannel.getId())) { BotUtils.sendMessage(channel, author, "Error queueing track:", "Music player currently in use with another channel, " + "either join that one or wait for them to finish.", Color.RED); return; } } // Join the user if the bot is not already in there. if (botVoiceChannel == null) { musicManager.setBotVoiceConnection(userVoiceChannel.join(spec -> spec.setProvider(musicManager.getAudioProvider())).block()); } AudioSourceManagers.registerRemoteSources(MusicHelper.playerManager); AudioSourceManagers.registerLocalSource(MusicHelper.playerManager); MusicHelper.playerManager .loadItemOrdered(musicManager, track, new AudioLoadResultHandler() { @Override public void trackLoaded(AudioTrack track) { BotUtils.sendMessage(channel, author, "Adding to queue:", "[" + track.getInfo().title + "](" + track.getInfo().uri + ")" + " by " + track.getInfo().author, Color.GREEN); musicManager.getScheduler().queue(track); } @Override public void playlistLoaded(AudioPlaylist playlist) { // if it is a search vs an actual playlist if (track.startsWith("ytsearch:") || track.startsWith("scsearch:")) { BotUtils.sendMessage(channel, author, "Adding to queue:", playlist.getName() + "\n\n" + "[" + playlist.getTracks().get(0).getInfo().title + "](" + playlist.getTracks().get(0).getInfo().uri + ")" + " by " + playlist.getTracks().get(0).getInfo().author, Color.GREEN); musicManager.getScheduler().queue(playlist.getTracks().get(0)); } else { AudioTrack firstTrack = playlist.getSelectedTrack(); if (firstTrack == null) { firstTrack = playlist.getTracks().get(0); } musicManager.getScheduler().queue(firstTrack); // the queue for the playlist will start at the linked video for (int i = playlist.getTracks().indexOf(firstTrack) + 1; i < playlist.getTracks().size(); i++) { musicManager.getScheduler().queue(playlist.getTracks().get(i)); } String str = MusicHelper.queueToString(musicManager.getScheduler().getQueue()); // message with the first song BotUtils.sendMessage(channel, author, "Adding playlist to queue:", playlist.getName() + "\n\n" + "**First track:** " + "[" + firstTrack.getInfo().title + "](" + firstTrack.getInfo().uri + ")\n\n" + str, Color.GREEN); } } @Override public void noMatches() { BotUtils.sendMessage(channel, author, "Error queueing track:", "Nothing found at: " + track, Color.RED); } @Override public void loadFailed(FriendlyException exception) { BotUtils.sendMessage(channel, author, "Error queueing track:", "Could not play track: " + exception.getMessage(), Color.RED); } }); } /** * Returns the usage string for the QueueCommand. * * @param recipient User, who command is going to, used for permissions checking. * @return String, the correct usage for the command. */ @Override public String getCommand(User recipient) { return "`" + BotUtils.PREFIX + "queue <song>` or `" + BotUtils.PREFIX + "q <song>` - Song can be in the form of either a YouTube URL, " + "SoundCloud URL, or if it is not a URL it will search from YouTube."; } }
CorruptComputer/PolizziaHut
src/main/java/xyz/gupton/nickolas/beepsky/music/commands/QueueCommand.java
Java
agpl-3.0
8,513
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.gl; /** * This class contains the constants being used by various general ledger components */ public final class Constant { public static final String EMPTY_STRING = ""; public static final String EXCLUDE_CG_BEGINNING_BALANCE_ONLY_OPTION = "dummyBusinessObject.cgBeginningBalanceExcludeOption"; public static final String PENDING_ENTRY_OPTION = "dummyBusinessObject.pendingEntryOption"; public static final String APPROVED_PENDING_ENTRY = "Approved"; public static final String ALL_PENDING_ENTRY = "All"; public static final String NO_PENDING_ENTRY = "No"; public static final String CONSOLIDATION_OPTION = "dummyBusinessObject.consolidationOption"; public static final String CONSOLIDATION = "Consolidation"; public static final String DETAIL = "Detail"; public static final String EXCLUDE_SUBACCOUNTS = "Exclude Sub-Accounts"; public static final String AMOUNT_VIEW_OPTION = "dummyBusinessObject.amountViewOption"; public static final String MONTHLY = "Monthly"; public static final String ACCUMULATE = "Accumulate"; public static final String BLANK_LINE_OPTION = "dummyBusinessObject.blankLineOption"; public static final String SHOW_BLANK_LINE = "Yes"; public static final String NOT_SHOW_BLANK_LINE = "No"; public static final String COST_SHARE_OPTION = "dummyBusinessObject.costShareOption"; public static final String COST_SHARE_EXCLUDE = "Exclude"; public static final String COST_SHARE_INCLUDE = "Include"; public static final String DEBIT_CREDIT_OPTION = "dummyBusinessObject.debitCreditOption"; public static final String DEBIT_CREDIT_INCLUDE = "Include"; public static final String DEBIT_CREDIT_EXCLUDE = "Exclude"; public static final String ZERO_ENCUMBRANCE_OPTION = "dummyBusinessObject.zeroEncumbranceOption"; public static final String ZERO_ENCUMBRANCE_INCLUDE = "Include"; public static final String ZERO_ENCUMBRANCE_EXCLUDE = "Exclude"; public static final String SUB_ACCOUNT_OPTION = "subAccountNumber"; public static final String DOCUMENT_APPROVED_CODE_APPROVED = "A"; public static final String DOCUMENT_APPROVED_CODE_PENDING = "N"; public static final String DOCUMENT_APPROVED_CODE_PROCESSED = "X"; public static final String BALANCE_TYPE_PE = "PE"; public static final String BALANCE_TYPE_CB = "CB"; public static final String CONSOLIDATED_SUB_ACCOUNT_NUMBER = "*ALL*"; public static final String CONSOLIDATED_SUB_OBJECT_CODE = "*ALL*"; public static final String CONSOLIDATED_OBJECT_TYPE_CODE = "*ALL*"; public static final String GL_LOOKUPABLE_ACCOUNT_BALANCE = "glAccountBalanceLookupable"; public static final String GL_LOOKUPABLE_ACCOUNT_BALANCE_BY_CONSOLIDATION = "glAccountBalanceByConsolidationLookupable"; public static final String GL_LOOKUPABLE_ACCOUNT_BALANCE_BY_LEVEL = "glAccountBalanceByLevelLookupable"; public static final String GL_LOOKUPABLE_ACCOUNT_BALANCE_BY_OBJECT = "glAccountBalanceByObjectLookupable"; public static final String GL_LOOKUPABLE_BALANCE = "glBalanceLookupable"; public static final String GL_LOOKUPABLE_CASH_BALANCE = "glCashBalanceLookupable"; public static final String GL_LOOKUPABLE_ENCUMBRANCE = "glEncumbranceLookupable"; public static final String GL_LOOKUPABLE_ENTRY = "glEntryLookupable"; public static final String GL_LOOKUPABLE_PENDING_ENTRY = "glPendingEntryLookupable"; public static final String RETURN_LOCATION_VALUE = "portal.do"; public static final String LOOKUP_BUTTON_VALUE = "Drill Down"; public static final String TOTAL_ACCOUNT_BALANCE_INCOME = "Income"; public static final String TOTAL_ACCOUNT_BALANCE_EXPENSE_GROSS = "Expense (Gross)"; public static final String TOTAL_ACCOUNT_BALANCE_EXPENSE_IN = "Expense (Net Transfer In)"; public static final String TOTAL_ACCOUNT_BALANCE_AVAILABLE = "Avaliable Balance"; public static final String SEARCH_RESULTS = "searchResults"; public enum DocumentApprovedCode { APPROVED(DOCUMENT_APPROVED_CODE_APPROVED, "APPROVED"), PENDING(DOCUMENT_APPROVED_CODE_PENDING, "PENDING"), PROCESSED(DOCUMENT_APPROVED_CODE_PROCESSED, "PROCESSED"); public String code; public String description; private DocumentApprovedCode(String code, String description) { this.code = code; this.description = description; } public static String getDescription(String code) { for (DocumentApprovedCode approvedCode : DocumentApprovedCode.values()) { if (approvedCode.code.equals(code)) { return approvedCode.description; } } return null; } } }
quikkian-ua-devops/will-financials
kfs-core/src/main/java/org/kuali/kfs/gl/Constant.java
Java
agpl-3.0
5,576
<?php /* Author: Lee Braiden Author URI: http://www.kintassa.com Copyright: Copyright (c) 2011 Kintassa. License: All rights reserved. Contact Kintassa should you wish to license this product. */ ?> <div id="<?php echo $unique_id; ?>-wrapper" <?php echo $wrapper_cls . " " . $companion_sty; ?>> <div id="<?php echo $unique_id; ?>" <?php echo $cls . " " . $sty; ?>> <p><?php echo $not_avail_msg; ?></p> </div> </div>
lee-b/lb-galleries
templates/applet_invalid__render.php
PHP
agpl-3.0
420
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package api import ( "github.com/mattermost/platform/model" "github.com/mattermost/platform/store" "github.com/mattermost/platform/utils" "net/http" "strings" "testing" "time" ) func TestCreateChannel(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam Client.Must(Client.Logout()) team2 := th.CreateTeam(th.BasicClient) th.LoginBasic() th.BasicClient.SetTeamId(team.Id) channel := model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} rchannel, err := Client.CreateChannel(&channel) if err != nil { t.Fatal(err) } if rchannel.Data.(*model.Channel).Name != channel.Name { t.Fatal("full name didn't match") } rget := Client.Must(Client.GetChannels("")).Data.(*model.ChannelList) nameMatch := false for _, c := range rget.Channels { if c.Name == channel.Name { nameMatch = true } } if !nameMatch { t.Fatal("Did not create channel with correct name") } if _, err := Client.CreateChannel(rchannel.Data.(*model.Channel)); err == nil { t.Fatal("Cannot create an existing") } savedId := rchannel.Data.(*model.Channel).Id rchannel.Data.(*model.Channel).Id = "" if _, err := Client.CreateChannel(rchannel.Data.(*model.Channel)); err != nil { if err.Message != "A channel with that URL already exists" { t.Fatal(err) } } if _, err := Client.DoApiPost(Client.GetTeamRoute()+"/channels/create", "garbage"); err == nil { t.Fatal("should have been an error") } Client.DeleteChannel(savedId) if _, err := Client.CreateChannel(rchannel.Data.(*model.Channel)); err != nil { if err.Message != "A channel with that URL was previously created" { t.Fatal(err) } } channel = model.Channel{DisplayName: "Channel on Different Team", Name: "aaaa" + model.NewId() + "abbb", Type: model.CHANNEL_OPEN, TeamId: team2.Id} if _, err := Client.CreateChannel(&channel); err.StatusCode != http.StatusForbidden { t.Fatal(err) } channel = model.Channel{DisplayName: "Test API Name", Name: model.NewId() + "__" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team.Id} if _, err := Client.CreateChannel(&channel); err == nil { t.Fatal("Should have errored out on invalid '__' character") } channel = model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_DIRECT, TeamId: team.Id} if _, err := Client.CreateChannel(&channel); err == nil { t.Fatal("Should have errored out on direct channel type") } } func TestCreateDirectChannel(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient user := th.BasicUser user2 := th.BasicUser2 rchannel, err := Client.CreateDirectChannel(th.BasicUser2.Id) if err != nil { t.Fatal(err) } channelName := "" if user2.Id > user.Id { channelName = user.Id + "__" + user2.Id } else { channelName = user2.Id + "__" + user.Id } if rchannel.Data.(*model.Channel).Name != channelName { t.Fatal("channel name didn't match") } if rchannel.Data.(*model.Channel).Type != model.CHANNEL_DIRECT { t.Fatal("channel type was not direct") } // don't fail on direct channels already existing if _, err := Client.CreateDirectChannel(th.BasicUser2.Id); err != nil { t.Fatal(err) } if _, err := Client.CreateDirectChannel("junk"); err == nil { t.Fatal("should have failed with bad user id") } if _, err := Client.CreateDirectChannel("12345678901234567890123456"); err == nil { t.Fatal("should have failed with non-existent user") } } func TestUpdateChannel(t *testing.T) { th := Setup().InitSystemAdmin() Client := th.SystemAdminClient team := th.SystemAdminTeam sysAdminUser := th.SystemAdminUser user := th.CreateUser(Client) LinkUserToTeam(user, team) user2 := th.CreateUser(Client) LinkUserToTeam(user2, team) Client.Login(user.Email, user.Password) channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) Client.AddChannelMember(channel1.Id, user.Id) header := "a" + model.NewId() + "a" purpose := "a" + model.NewId() + "a" upChannel1 := &model.Channel{Id: channel1.Id, Header: header, Purpose: purpose} upChannel1 = Client.Must(Client.UpdateChannel(upChannel1)).Data.(*model.Channel) if upChannel1.Header != header { t.Fatal("Channel admin failed to update header") } if upChannel1.Purpose != purpose { t.Fatal("Channel admin failed to update purpose") } if upChannel1.DisplayName != channel1.DisplayName { t.Fatal("Channel admin failed to skip displayName") } rget := Client.Must(Client.GetChannels("")) data := rget.Data.(*model.ChannelList) for _, c := range data.Channels { if c.Name == model.DEFAULT_CHANNEL { c.Header = "new header" c.Name = "pseudo-square" if _, err := Client.UpdateChannel(c); err == nil { t.Fatal("should have errored on updating default channel name") } break } } Client.Login(user2.Email, user2.Password) if _, err := Client.UpdateChannel(upChannel1); err == nil { t.Fatal("Standard User should have failed to update") } Client.Must(Client.JoinChannel(channel1.Id)) UpdateUserToTeamAdmin(user2, team) Client.Logout() Client.Login(user2.Email, user2.Password) Client.SetTeamId(team.Id) if _, err := Client.UpdateChannel(upChannel1); err != nil { t.Fatal(err) } Client.Login(sysAdminUser.Email, sysAdminUser.Password) Client.Must(Client.JoinChannel(channel1.Id)) if _, err := Client.UpdateChannel(upChannel1); err != nil { t.Fatal(err) } Client.Must(Client.DeleteChannel(channel1.Id)) if _, err := Client.UpdateChannel(upChannel1); err == nil { t.Fatal("should have failed - channel deleted") } } func TestUpdateChannelHeader(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) data := make(map[string]string) data["channel_id"] = channel1.Id data["channel_header"] = "new header" var upChannel1 *model.Channel if result, err := Client.UpdateChannelHeader(data); err != nil { t.Fatal(err) } else { upChannel1 = result.Data.(*model.Channel) } if upChannel1.Header != data["channel_header"] { t.Fatal("Failed to update header") } data["channel_id"] = "junk" if _, err := Client.UpdateChannelHeader(data); err == nil { t.Fatal("should have errored on junk channel id") } data["channel_id"] = "12345678901234567890123456" if _, err := Client.UpdateChannelHeader(data); err == nil { t.Fatal("should have errored on non-existent channel id") } data["channel_id"] = channel1.Id data["channel_header"] = strings.Repeat("a", 1050) if _, err := Client.UpdateChannelHeader(data); err == nil { t.Fatal("should have errored on bad channel header") } rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser2.Id)).Data.(*model.Channel) data["channel_id"] = rchannel.Id data["channel_header"] = "new header" var upChanneld *model.Channel if result, err := Client.UpdateChannelHeader(data); err != nil { t.Fatal(err) } else { upChanneld = result.Data.(*model.Channel) } if upChanneld.Header != data["channel_header"] { t.Fatal("Failed to update header") } th.LoginBasic2() data["channel_id"] = channel1.Id data["channel_header"] = "new header" if _, err := Client.UpdateChannelHeader(data); err == nil { t.Fatal("should have errored non-channel member trying to update header") } } func TestUpdateChannelPurpose(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) data := make(map[string]string) data["channel_id"] = channel1.Id data["channel_purpose"] = "new purpose" var upChannel1 *model.Channel if result, err := Client.UpdateChannelPurpose(data); err != nil { t.Fatal(err) } else { upChannel1 = result.Data.(*model.Channel) } if upChannel1.Purpose != data["channel_purpose"] { t.Fatal("Failed to update purpose") } data["channel_id"] = "junk" if _, err := Client.UpdateChannelPurpose(data); err == nil { t.Fatal("should have errored on junk channel id") } data["channel_id"] = "12345678901234567890123456" if _, err := Client.UpdateChannelPurpose(data); err == nil { t.Fatal("should have errored on non-existent channel id") } data["channel_id"] = channel1.Id data["channel_purpose"] = strings.Repeat("a", 150) if _, err := Client.UpdateChannelPurpose(data); err == nil { t.Fatal("should have errored on bad channel purpose") } th.LoginBasic2() data["channel_id"] = channel1.Id data["channel_purpose"] = "new purpose" if _, err := Client.UpdateChannelPurpose(data); err == nil { t.Fatal("should have errored non-channel member trying to update purpose") } } func TestGetChannel(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam team2 := th.CreateTeam(Client) channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel) rget := Client.Must(Client.GetChannels("")) data := rget.Data.(*model.ChannelList) if data.Channels[0].DisplayName != channel1.DisplayName { t.Fatal("full name didn't match") } if data.Channels[1].DisplayName != channel2.DisplayName { t.Fatal("full name didn't match") } // test etag caching if cache_result, err := Client.GetChannels(rget.Etag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelList) != nil { t.Log(cache_result.Data) t.Fatal("cache should be empty") } if _, err := Client.UpdateLastViewedAt(channel2.Id); err != nil { t.Fatal(err) } if resp, err := Client.GetChannel(channel1.Id, ""); err != nil { t.Fatal(err) } else { data := resp.Data.(*model.ChannelData) if data.Channel.DisplayName != channel1.DisplayName { t.Fatal("name didn't match") } // test etag caching if cache_result, err := Client.GetChannel(channel1.Id, resp.Etag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelData) != nil { t.Log(cache_result.Data) t.Fatal("cache should be empty") } } if _, err := Client.GetChannel("junk", ""); err == nil { t.Fatal("should have failed - bad channel id") } Client.SetTeamId(team2.Id) if _, err := Client.GetChannel(channel2.Id, ""); err == nil { t.Fatal("should have failed - wrong team") } } func TestGetMoreChannel(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel) th.LoginBasic2() rget := Client.Must(Client.GetMoreChannels("")) data := rget.Data.(*model.ChannelList) if data.Channels[0].DisplayName != channel1.DisplayName { t.Fatal("full name didn't match") } if data.Channels[1].DisplayName != channel2.DisplayName { t.Fatal("full name didn't match") } // test etag caching if cache_result, err := Client.GetMoreChannels(rget.Etag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelList) != nil { t.Log(cache_result.Data) t.Fatal("cache should be empty") } } func TestGetChannelCounts(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel) if result, err := Client.GetChannelCounts(""); err != nil { t.Fatal(err) } else { counts := result.Data.(*model.ChannelCounts) if len(counts.Counts) != 5 { t.Fatal("wrong number of channel counts") } if len(counts.UpdateTimes) != 5 { t.Fatal("wrong number of channel update times") } if cache_result, err := Client.GetChannelCounts(result.Etag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelCounts) != nil { t.Log(cache_result.Data) t.Fatal("result data should be empty") } } } func TestJoinChannelById(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id} channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel) th.LoginBasic2() Client.Must(Client.JoinChannel(channel1.Id)) if _, err := Client.JoinChannel(channel3.Id); err == nil { t.Fatal("shouldn't be able to join secret group") } rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id)).Data.(*model.Channel) user3 := th.CreateUser(th.BasicClient) LinkUserToTeam(user3, team) Client.Must(Client.Login(user3.Email, "Password1")) if _, err := Client.JoinChannel(rchannel.Id); err == nil { t.Fatal("shoudn't be able to join direct channel") } th.LoginBasic() if _, err := Client.JoinChannel(channel1.Id); err != nil { t.Fatal("should be able to join public channel that we're a member of") } if _, err := Client.JoinChannel(channel3.Id); err != nil { t.Fatal("should be able to join private channel that we're a member of") } if _, err := Client.JoinChannel(rchannel.Id); err != nil { t.Fatal("should be able to join direct channel that we're a member of") } } func TestJoinChannelByName(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id} channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel) th.LoginBasic2() Client.Must(Client.JoinChannelByName(channel1.Name)) if _, err := Client.JoinChannelByName(channel3.Name); err == nil { t.Fatal("shouldn't be able to join secret group") } rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id)).Data.(*model.Channel) user3 := th.CreateUser(th.BasicClient) LinkUserToTeam(user3, team) Client.Must(Client.Login(user3.Email, "Password1")) if _, err := Client.JoinChannelByName(rchannel.Name); err == nil { t.Fatal("shoudn't be able to join direct channel") } th.LoginBasic() if _, err := Client.JoinChannelByName(channel1.Name); err != nil { t.Fatal("should be able to join public channel that we're a member of") } if _, err := Client.JoinChannelByName(channel3.Name); err != nil { t.Fatal("should be able to join private channel that we're a member of") } if _, err := Client.JoinChannelByName(rchannel.Name); err != nil { t.Fatal("should be able to join direct channel that we're a member of") } } func TestLeaveChannel(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id} channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel) th.LoginBasic2() Client.Must(Client.JoinChannel(channel1.Id)) // Cannot leave a the private group if you are the only member if _, err := Client.LeaveChannel(channel3.Id); err == nil { t.Fatal("should have errored, cannot leave private group if only one member") } rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id)).Data.(*model.Channel) if _, err := Client.LeaveChannel(rchannel.Id); err == nil { t.Fatal("should have errored, cannot leave direct channel") } rget := Client.Must(Client.GetChannels("")) cdata := rget.Data.(*model.ChannelList) for _, c := range cdata.Channels { if c.Name == model.DEFAULT_CHANNEL { if _, err := Client.LeaveChannel(c.Id); err == nil { t.Fatal("should have errored on leaving default channel") } break } } } func TestDeleteChannel(t *testing.T) { th := Setup().InitSystemAdmin() Client := th.SystemAdminClient team := th.SystemAdminTeam userSystemAdmin := th.SystemAdminUser userTeamAdmin := th.CreateUser(Client) LinkUserToTeam(userTeamAdmin, team) user2 := th.CreateUser(Client) LinkUserToTeam(user2, team) Client.Login(user2.Email, user2.Password) channelMadeByCA := &model.Channel{DisplayName: "C Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channelMadeByCA = Client.Must(Client.CreateChannel(channelMadeByCA)).Data.(*model.Channel) Client.AddChannelMember(channelMadeByCA.Id, userTeamAdmin.Id) Client.Login(userTeamAdmin.Email, "pwd") channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel) if _, err := Client.DeleteChannel(channel1.Id); err != nil { t.Fatal(err) } if _, err := Client.DeleteChannel(channelMadeByCA.Id); err != nil { t.Fatal("Team admin failed to delete Channel Admin's channel") } post1 := &model.Post{ChannelId: channel1.Id, Message: "a" + model.NewId() + "a"} if _, err := Client.CreatePost(post1); err == nil { t.Fatal("should have failed to post to deleted channel") } userStd := th.CreateUser(Client) LinkUserToTeam(userStd, team) Client.Login(userStd.Email, userStd.Password) if _, err := Client.JoinChannel(channel1.Id); err == nil { t.Fatal("should have failed to join deleted channel") } Client.Must(Client.JoinChannel(channel2.Id)) if _, err := Client.DeleteChannel(channel2.Id); err == nil { t.Fatal("should have failed to delete channel you're not an admin of") } rget := Client.Must(Client.GetChannels("")) cdata := rget.Data.(*model.ChannelList) for _, c := range cdata.Channels { if c.Name == model.DEFAULT_CHANNEL { if _, err := Client.DeleteChannel(c.Id); err == nil { t.Fatal("should have errored on deleting default channel") } break } } UpdateUserToTeamAdmin(userStd, team) Client.Logout() Client.Login(userStd.Email, userStd.Password) Client.SetTeamId(team.Id) if _, err := Client.DeleteChannel(channel2.Id); err != nil { t.Fatal(err) } channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel) Client.Login(userSystemAdmin.Email, userSystemAdmin.Password) Client.Must(Client.JoinChannel(channel3.Id)) if _, err := Client.DeleteChannel(channel3.Id); err != nil { t.Fatal(err) } if _, err := Client.DeleteChannel(channel3.Id); err == nil { t.Fatal("should have failed - channel already deleted") } } func TestGetChannelExtraInfo(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) rget := Client.Must(Client.GetChannelExtraInfo(channel1.Id, -1, "")) data := rget.Data.(*model.ChannelExtra) if data.Id != channel1.Id { t.Fatal("couldnt't get extra info") } else if len(data.Members) != 1 { t.Fatal("got incorrect members") } else if data.MemberCount != 1 { t.Fatal("got incorrect member count") } // // Testing etag caching // currentEtag := rget.Etag if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelExtra) != nil { t.Log(cache_result.Data) t.Fatal("response should be empty") } else { currentEtag = cache_result.Etag } Client2 := model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress) user2 := &model.User{Email: "success+" + model.NewId() + "@simulator.amazonses.com", Nickname: "Tester 2", Password: "pwd"} user2 = Client2.Must(Client2.CreateUser(user2, "")).Data.(*model.User) LinkUserToTeam(user2, team) Client2.SetTeamId(team.Id) store.Must(Srv.Store.User().VerifyEmail(user2.Id)) Client2.Login(user2.Email, "pwd") Client2.Must(Client2.JoinChannel(channel1.Id)) if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelExtra) == nil { t.Log(cache_result.Data) t.Fatal("response should not be empty") } else { currentEtag = cache_result.Etag } if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelExtra) != nil { t.Log(cache_result.Data) t.Fatal("response should be empty") } else { currentEtag = cache_result.Etag } Client2.Must(Client2.LeaveChannel(channel1.Id)) if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelExtra) == nil { t.Log(cache_result.Data) t.Fatal("response should not be empty") } else { currentEtag = cache_result.Etag } if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelExtra) != nil { t.Log(cache_result.Data) t.Fatal("response should be empty") } else { currentEtag = cache_result.Etag } Client2.Must(Client2.JoinChannel(channel1.Id)) if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 2, currentEtag); err != nil { t.Fatal(err) } else if extra := cache_result.Data.(*model.ChannelExtra); extra == nil { t.Fatal("response should not be empty") } else if len(extra.Members) != 2 { t.Fatal("should've returned 2 members") } else if extra.MemberCount != 2 { t.Fatal("should've returned member count of 2") } else { currentEtag = cache_result.Etag } if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 1, currentEtag); err != nil { t.Fatal(err) } else if extra := cache_result.Data.(*model.ChannelExtra); extra == nil { t.Fatal("response should not be empty") } else if len(extra.Members) != 1 { t.Fatal("should've returned only 1 member") } else if extra.MemberCount != 2 { t.Fatal("should've returned member count of 2") } else { currentEtag = cache_result.Etag } if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 1, currentEtag); err != nil { t.Fatal(err) } else if cache_result.Data.(*model.ChannelExtra) != nil { t.Log(cache_result.Data) t.Fatal("response should be empty") } else { currentEtag = cache_result.Etag } } func TestAddChannelMember(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam user2 := th.BasicUser2 user3 := th.CreateUser(Client) channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) if _, err := Client.AddChannelMember(channel1.Id, user2.Id); err != nil { t.Fatal(err) } if _, err := Client.AddChannelMember(channel1.Id, "dsgsdg"); err == nil { t.Fatal("Should have errored, bad user id") } if _, err := Client.AddChannelMember(channel1.Id, "12345678901234567890123456"); err == nil { t.Fatal("Should have errored, bad user id") } if _, err := Client.AddChannelMember(channel1.Id, user2.Id); err != nil { t.Fatal(err) } if _, err := Client.AddChannelMember("sgdsgsdg", user2.Id); err == nil { t.Fatal("Should have errored, bad channel id") } channel2 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel) th.LoginBasic2() if _, err := Client.AddChannelMember(channel2.Id, user2.Id); err == nil { t.Fatal("Should have errored, user not in channel") } th.LoginBasic() Client.Must(Client.DeleteChannel(channel2.Id)) if _, err := Client.AddChannelMember(channel2.Id, user2.Id); err == nil { t.Fatal("Should have errored, channel deleted") } if _, err := Client.AddChannelMember(channel1.Id, user3.Id); err == nil { t.Fatal("Should have errored, user not on team") } } func TestRemoveChannelMember(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam user2 := th.BasicUser2 UpdateUserToTeamAdmin(user2, team) channelMadeByCA := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channelMadeByCA = Client.Must(Client.CreateChannel(channelMadeByCA)).Data.(*model.Channel) Client.Must(Client.AddChannelMember(channelMadeByCA.Id, user2.Id)) th.LoginBasic2() channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) userStd := th.CreateUser(th.BasicClient) LinkUserToTeam(userStd, team) Client.Must(Client.AddChannelMember(channel1.Id, userStd.Id)) Client.Must(Client.AddChannelMember(channelMadeByCA.Id, userStd.Id)) if _, err := Client.RemoveChannelMember(channel1.Id, "dsgsdg"); err == nil { t.Fatal("Should have errored, bad user id") } if _, err := Client.RemoveChannelMember("sgdsgsdg", userStd.Id); err == nil { t.Fatal("Should have errored, bad channel id") } if _, err := Client.RemoveChannelMember(channel1.Id, userStd.Id); err != nil { t.Fatal(err) } if _, err := Client.RemoveChannelMember(channelMadeByCA.Id, userStd.Id); err != nil { t.Fatal("Team Admin failed to remove member from Channel Admin's channel") } channel2 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel) Client.Login(userStd.Email, userStd.Password) if _, err := Client.RemoveChannelMember(channel2.Id, userStd.Id); err == nil { t.Fatal("Should have errored, user not channel admin") } th.LoginBasic2() Client.Must(Client.AddChannelMember(channel2.Id, userStd.Id)) Client.Must(Client.DeleteChannel(channel2.Id)) if _, err := Client.RemoveChannelMember(channel2.Id, userStd.Id); err == nil { t.Fatal("Should have errored, channel deleted") } } func TestUpdateNotifyProps(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam user := th.BasicUser user2 := th.BasicUser2 channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel) data := make(map[string]string) data["channel_id"] = channel1.Id data["user_id"] = user.Id data["desktop"] = model.CHANNEL_NOTIFY_MENTION timeBeforeUpdate := model.GetMillis() time.Sleep(100 * time.Millisecond) // test updating desktop if result, err := Client.UpdateNotifyProps(data); err != nil { t.Fatal(err) } else if notifyProps := result.Data.(map[string]string); notifyProps["desktop"] != model.CHANNEL_NOTIFY_MENTION { t.Fatal("NotifyProps[\"desktop\"] did not update properly") } else if notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_ALL { t.Fatalf("NotifyProps[\"mark_unread\"] changed to %v", notifyProps["mark_unread"]) } rget := Client.Must(Client.GetChannels("")) rdata := rget.Data.(*model.ChannelList) if len(rdata.Members) == 0 || rdata.Members[channel1.Id].NotifyProps["desktop"] != data["desktop"] { t.Fatal("NotifyProps[\"desktop\"] did not update properly") } else if rdata.Members[channel1.Id].LastUpdateAt <= timeBeforeUpdate { t.Fatal("LastUpdateAt did not update") } // test an empty update delete(data, "desktop") if result, err := Client.UpdateNotifyProps(data); err != nil { t.Fatal(err) } else if notifyProps := result.Data.(map[string]string); notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_ALL { t.Fatalf("NotifyProps[\"mark_unread\"] changed to %v", notifyProps["mark_unread"]) } else if notifyProps["desktop"] != model.CHANNEL_NOTIFY_MENTION { t.Fatalf("NotifyProps[\"desktop\"] changed to %v", notifyProps["desktop"]) } // test updating mark unread data["mark_unread"] = model.CHANNEL_MARK_UNREAD_MENTION if result, err := Client.UpdateNotifyProps(data); err != nil { t.Fatal(err) } else if notifyProps := result.Data.(map[string]string); notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_MENTION { t.Fatal("NotifyProps[\"mark_unread\"] did not update properly") } else if notifyProps["desktop"] != model.CHANNEL_NOTIFY_MENTION { t.Fatalf("NotifyProps[\"desktop\"] changed to %v", notifyProps["desktop"]) } // test updating both data["desktop"] = model.CHANNEL_NOTIFY_NONE data["mark_unread"] = model.CHANNEL_MARK_UNREAD_MENTION if result, err := Client.UpdateNotifyProps(data); err != nil { t.Fatal(err) } else if notifyProps := result.Data.(map[string]string); notifyProps["desktop"] != model.CHANNEL_NOTIFY_NONE { t.Fatal("NotifyProps[\"desktop\"] did not update properly") } else if notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_MENTION { t.Fatal("NotifyProps[\"mark_unread\"] did not update properly") } // test error cases data["user_id"] = "junk" if _, err := Client.UpdateNotifyProps(data); err == nil { t.Fatal("Should have errored - bad user id") } data["user_id"] = "12345678901234567890123456" if _, err := Client.UpdateNotifyProps(data); err == nil { t.Fatal("Should have errored - bad user id") } data["user_id"] = user.Id data["channel_id"] = "junk" if _, err := Client.UpdateNotifyProps(data); err == nil { t.Fatal("Should have errored - bad channel id") } data["channel_id"] = "12345678901234567890123456" if _, err := Client.UpdateNotifyProps(data); err == nil { t.Fatal("Should have errored - bad channel id") } data["desktop"] = "junk" data["mark_unread"] = model.CHANNEL_MARK_UNREAD_ALL if _, err := Client.UpdateNotifyProps(data); err == nil { t.Fatal("Should have errored - bad desktop notify level") } data["desktop"] = model.CHANNEL_NOTIFY_ALL data["mark_unread"] = "junk" if _, err := Client.UpdateNotifyProps(data); err == nil { t.Fatal("Should have errored - bad mark unread level") } th.LoginBasic2() data["channel_id"] = channel1.Id data["user_id"] = user2.Id data["desktop"] = model.CHANNEL_NOTIFY_MENTION data["mark_unread"] = model.CHANNEL_MARK_UNREAD_MENTION if _, err := Client.UpdateNotifyProps(data); err == nil { t.Fatal("Should have errored - user not in channel") } } func TestFuzzyChannel(t *testing.T) { th := Setup().InitBasic() Client := th.BasicClient team := th.BasicTeam // Strings that should pass as acceptable channel names var fuzzyStringsPass = []string{ "*", "?", ".", "}{][)(><", "{}[]()<>", "qahwah ( قهوة)", "שָׁלוֹם עֲלֵיכֶם", "Ramen チャーシュー chāshū", "言而无信", "Ṫ͌ó̍ ̍͂̓̍̍̀i̊ͯ͒", "&amp; &lt; &qu", "' or '1'='1' -- ", "' or '1'='1' ({ ", "' or '1'='1' /* ", "1;DROP TABLE users", "<b><i><u><strong><em>", "sue@thatmightbe", "sue@thatmightbe.", "sue@thatmightbe.c", "sue@thatmightbe.co", "su+san@thatmightbe.com", "a@b.中国", "1@2.am", "a@b.co.uk", "a@b.cancerresearch", "local@[127.0.0.1]", } for i := 0; i < len(fuzzyStringsPass); i++ { channel := model.Channel{DisplayName: fuzzyStringsPass[i], Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} _, err := Client.CreateChannel(&channel) if err != nil { t.Fatal(err) } } }
42wim/platform
api/channel_test.go
GO
agpl-3.0
33,742
class CreateInfos < ActiveRecord::Migration def change create_table :infos do |t| t.string :name t.string :permalink t.text :content t.timestamps end add_index :infos, :permalink end end
adejoux/djouxblog
db/migrate/20130721124001_create_infos.rb
Ruby
agpl-3.0
228
<?php class DSRoute extends sfObjectRoute implements InterfaceTiersRoute { protected $ds = null; protected function getObjectForParameters($parameters) { $matches = array(); if (preg_match('/^DS-(C?[0-9]{10})-([0-9]{4}[0-9]{2})-([0-9]{3})$/',$parameters['id'],$matches)) { $identifiant = $matches[1]; $periode = $matches[2]; $lieu_stockage = $matches[3]; } else { throw new InvalidArgumentException(sprintf('The DS "%s" is not valid.', $this->pattern, $parameters['id'])); } $this->ds = DSClient::getInstance()->findByIdentifiantPeriodeAndLieuStockage($identifiant, $periode, $lieu_stockage); if (!$this->ds) { throw new sfError404Exception(sprintf('No DS found with the id "%s" and the periode "%s".', $identifiant, $periode)); } return $this->ds; } protected function doConvertObjectToArray($object) { $parameters = array("id" => $object->_id); return $parameters; } public function getDS() { if (!$this->ds) { $this->getObject(); } return $this->ds; } public function getEtablissement() { return $this->getDS()->getEtablissement(); } public function getTiers() { return $this->getEtablissement(); } }
24eme/CIVA
project/plugins/acVinDSPlugin/lib/routing/DSRoute.class.php
PHP
agpl-3.0
1,341
// Copyright (C) 2013 - 2021 Tim Düsterhus // Copyright (C) 2021 Maximilian Mader // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // SPDX-License-Identifier: AGPL-3.0-or-later use crate::http::{ error::{Error, Error::FileNotFound}, header::not_modified, }; use actix_web::{ get, http::header::{CacheControl, CacheDirective, ETag}, web, HttpRequest, HttpResponse, Responder, }; #[get("/favicon.ico")] pub async fn favicon(req: HttpRequest) -> impl Responder { serve_asset(req, "favicon.ico") } #[get("/static/{filename:.+}")] pub async fn assets(req: HttpRequest, filename: web::Path<String>) -> impl Responder { serve_asset(req, &filename) } fn serve_asset(req: HttpRequest, filename: &str) -> Result<impl Responder, Error> { let file = format!("assets/static/{}", filename); crate::SOURCE_FILES .get(file.as_str()) .map(|source_file| { let etag = ETag::from(source_file); if not_modified(&req, Some(&etag), None) { return HttpResponse::NotModified() .insert_header(etag) .insert_header(CacheControl(vec![CacheDirective::Public])) .body(()); // None } let content_type = if filename.ends_with(".js.map") { "application/json".to_owned() } else { mime_guess::from_path(filename) .first_or_octet_stream() .to_string() }; HttpResponse::Ok() .insert_header(etag) .insert_header(CacheControl(vec![CacheDirective::Public])) .content_type(content_type) .body(source_file.contents) }) .ok_or(FileNotFound(req, file)) }
wbbaddons/Tims-PackageServer
src/http/routes/assets.rs
Rust
agpl-3.0
2,408
<!DOCTYPE html> <html lang="en" > <head> <title>About - 40423125上課報告</title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="canonical" href="../../pages/about/"> <meta name="author" content="40423125" /> <meta name="description" content="2017Spring 機械設計工程系網際內容管理 課程倉儲: http://github.com/mdecourse/2017springwcm 課程投影片: http://mdecourse.github.io/2017springwcm 課程網誌: http://mdecourse.github.io/2017springwcm/blog" /> <meta property="og:site_name" content="40423125上課報告" /> <meta property="og:type" content="article"/> <meta property="og:title" content="About"/> <meta property="og:url" content="../../pages/about/"/> <meta property="og:description" content="2017Spring 機械設計工程系網際內容管理 課程倉儲: http://github.com/mdecourse/2017springwcm 課程投影片: http://mdecourse.github.io/2017springwcm 課程網誌: http://mdecourse.github.io/2017springwcm/blog" /> <!-- Bootstrap --> <link rel="stylesheet" href="../../theme/css/bootstrap.united.min.css" type="text/css"/> <link href="../../theme/css/font-awesome.min.css" rel="stylesheet"> <link href="../../theme/css/pygments/monokai.css" rel="stylesheet"> <link href="../../theme/tipuesearch/tipuesearch.css" rel="stylesheet"> <link rel="stylesheet" href="../../theme/css/style.css" type="text/css"/> <link href="../../feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="40423125上課報告 ATOM Feed"/> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shCore.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushJScript.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushJava.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushPython.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushSql.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushXml.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushPhp.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCpp.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCss.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCSharp.js"></script> <script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushBash.js"></script> <script type='text/javascript'> (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = "https://chiamingyen.github.io/kmolab_data/files/syntaxhighlighter/css/shCore.css"; if ( corecss.setAttribute ) { corecss.setAttribute( "rel", "stylesheet" ); corecss.setAttribute( "type", "text/css" ); corecss.setAttribute( "href", corecssurl ); } else { corecss.rel = "stylesheet"; corecss.href = corecssurl; } document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") ); var themecssurl = "https://chiamingyen.github.io/kmolab_data/files/syntaxhighlighter/css/shThemeDefault.css?ver=3.0.9b"; if ( themecss.setAttribute ) { themecss.setAttribute( "rel", "stylesheet" ); themecss.setAttribute( "type", "text/css" ); themecss.setAttribute( "href", themecssurl ); } else { themecss.rel = "stylesheet"; themecss.href = themecssurl; } //document.getElementById("syntaxhighlighteranchor").appendChild(themecss); document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['pad-line-numbers'] = false; SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); </script> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="../../" class="navbar-brand"> 40423125上課報告 </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="../../pages/about/"> About </a></li> <li > <a href="../../category/course.html">Course</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li><span> <form class="navbar-search" action="../../search.html"> <input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required> </form></span> </li> <li><a href="../../archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content" class="body"> <h1 class="entry-title">About</h1> <div class="entry-content"> <h2>2017Spring 機械設計工程系網際內容管理</h2> <p>課程倉儲: <a href="http://github.com/mdecourse/2017springwcm">http://github.com/mdecourse/2017springwcm</a></p> <p>課程投影片: <a href="http://mdecourse.github.io/2017springwcm">http://mdecourse.github.io/2017springwcm</a></p> <p>課程網誌: <a href="http://mdecourse.github.io/2017springwcm/blog">http://mdecourse.github.io/2017springwcm/blog</a></p> </div> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4> <ul class="list-group" id="recentposts"> <li class="list-group-item"> <a href="../../wcm19.html"> 期末分組專題-仿生獸ONSHAPE與VREP完成 </a> </li> <li class="list-group-item"> <a href="../../wcm17.html"> 期末協同查驗與自評 </a> </li> <li class="list-group-item"> <a href="../../wcm18.html"> 期末分組專題-仿生獸初部構想 </a> </li> <li class="list-group-item"> <a href="../../wcm15.html"> W15 練習 </a> </li> <li class="list-group-item"> <a href="../../wcm14.html"> 20170518增加一個齒輪 </a> </li> </ul> </li> <li class="list-group-item"><a href="../../categories.html"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Categories</span></h4></a> <ul class="list-group" id="categories"> <li class="list-group-item"> <a href="../../category/course.html"> <i class="fa fa-folder-open fa-lg"></i> Course </a> </li> </ul> </li> <li class="list-group-item"><a href="../../tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a> <ul class="list-group list-inline tagcloud" id="tags"> </ul> </li> <li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4> <ul class="list-group" id="links"> <li class="list-group-item"> <a href="https://github.com/40423125/2017springcd_hw/wiki" target="_blank"> Github Wiki </a> </li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2017 40423125 &middot; Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="../../theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="../../theme/js/bootstrap.min.js"></script> <!-- for https://github.com/jsor/lity lightbox video popup --> <link href="../../theme/css/lity.css" rel="stylesheet"> <script src="../../theme/js/lity.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="../../theme/js/respond.min.js"></script> </body> </html>
40423125/2017springcd_hw
blog/pages/about/index.html
HTML
agpl-3.0
10,975
/***************************************************************************** @(#) $RCSfile: slpmod.c,v $ $Name: $($Revision: 1.1.2.3 $) $Date: 2011-09-02 08:46:55 $ ----------------------------------------------------------------------------- Copyright (c) 2008-2011 Monavacon Limited <http://www.monavacon.com/> Copyright (c) 2001-2008 OpenSS7 Corporation <http://www.openss7.com/> Copyright (c) 1997-2001 Brian F. G. Bidulock <bidulock@openss7.org> All Rights Reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>, or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ----------------------------------------------------------------------------- U.S. GOVERNMENT RESTRICTED RIGHTS. If you are licensing this Software on behalf of the U.S. Government ("Government"), the following provisions apply to you. If the Software is supplied by the Department of Defense ("DoD"), it is classified as "Commercial Computer Software" under paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition Regulations ("DFARS") (or any successor regulations) and the Government is acquiring only the license rights granted herein (the license rights customarily provided to non-Government users). If the Software is supplied to any unit or agency of the Government other than DoD, it is classified as "Restricted Computer Software" and the Government's rights in the Software are defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR") (or any successor regulations) or, in the cases of NASA, in paragraph 18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). ----------------------------------------------------------------------------- Commercial licensing and support of this software is available from OpenSS7 Corporation at a fee. See http://www.openss7.com/ ----------------------------------------------------------------------------- Last Modified $Date: 2011-09-02 08:46:55 $ by $Author: brian $ ----------------------------------------------------------------------------- $Log: slpmod.c,v $ Revision 1.1.2.3 2011-09-02 08:46:55 brian - sync up lots of repo and build changes from git Revision 1.1.2.2 2010-11-28 14:22:06 brian - remove #ident, protect _XOPEN_SOURCE Revision 1.1.2.1 2009-06-21 11:40:35 brian - added files to new distro *****************************************************************************/ static char const ident[] = "$RCSfile: slpmod.c,v $ $Name: $($Revision: 1.1.2.3 $) $Date: 2011-09-02 08:46:55 $"; /* * This is SLPMOD, an SL module that is pushed over a pipe end to form an internal * pseudo-signalling link. Service primitives on the SL interface at one end of the pipe are * translated into Service primitives on the SL interface at the other end of the pipe. Although * the primaly purpose of such as link is testing, it also has the abilty to provide internal * signalling links for building virtual SS7 networks within a host. */ #define _SVR4_SOURCE 1 #define _MPS_SOURCE 1 #define _SUN_SOURCE 1 #include <sys/os7/compat.h> #include <ss7/lmi.h> #include <ss7/lmi_ioctl.h> #include <ss7/sdli.h> #include <ss7/sdli_ioctl.h> #include <ss7/sdti.h> #include <ss7/sdti_ioctl.h> #include <ss7/sli.h> #include <ss7/sli_ioctl.h> #define SL_DESCRIP "Signalling Link (SL) Pipe Module (SLPMOD) STREAMS Module" #define SL_EXTRA "Part of the OpenSS7 SS7 Stack for Linux Fast-STREAMS" #define SL_REVISION "OpenSS7 $RCSfile: slpmod.c,v $ $Name: $($Revision: 1.1.2.3 $) $Date: 2011-09-02 08:46:55 $" #define SL_COPYRIGHT "Copyright (c) 2008-2011 Monavacon Limited. All Rights Reserved." #define SL_DEVICE "Part of the OpenSS7 Stack for Linux Fast-STREAMS." #define SL_CONTACT "Brian Bidulock <bidulock@openss7.org>" #define SL_LICENSE "GPL" #define SL_BANNER SL_DESCRIP "\n" \ SL_EXTRA "\n" \ SL_REVISION "\n" \ SL_COPYRIGHT "\n" \ SL_DEVICE "\n" \ SL_CONTACT "\n" #define SL_SPLASH SL_DESCRIP " - " \ SL_REVISION "\n" #ifdef LINUX MODULE_AUTHOR(SL_CONTACT); MODULE_DESCRIPTION(SL_DESCRIP); MODULE_SUPPORTED_DEVICE(SL_DEVICE); #ifdef MODULE_LICENSE MODULE_LICENSE(SL_LICENSE); #endif /* MODULE_LICENSE */ #ifdef MODULE_ALIAS MODULE_ALIAS("streams-slpmod"); #endif /* MODULE_ALIAS */ #ifdef MODULE_VERSION MODULE_VERSION(PACKAGE_ENVR); #endif #endif /* LINUX */ #define SLPMOD_MOD_ID CONFIG_STREAMS_SLPMOD_MODID #define SLPMOD_MOD_NAME CONFIG_STREAMS_SLPMOD_NAME #ifndef SLPMOD_MOD_NAME #define SLPMOD_MOD_NAME "sl-pmod" #endif /* SLPMOD_MOD_NAME */ #ifndef SLPMOD_MOD_ID #define SLPMOD_MOD_ID 0 #endif /* SLPMOD_MOD_ID */ /* * ========================================================================= * * STREAMS DEFINITIONS * * ========================================================================= */ #define MOD_ID SLPMOD_MOD_ID #define MOD_NAME SLPMOD_MOD_NAME #ifdef MODULE #define MOD_BANNER SL_BANNER #else /* MODULE */ #define MOD_BANNER SL_SPLASH #endif /* MODULE */ static struct module_info sl_minfo = { .mi_idnum = MOD_ID, /* Module ID number */ .mi_idname = MOD_NAME, /* Module name */ .mi_minpsz = STRMINPSZ, /* Min packet size accepted */ .mi_maxpsz = STRMAXPSZ, /* Max packet size accepted */ .mi_hiwat = STRHIGH, /* Hi water mark */ .mi_lowat = STRLOW, /* Lo water mark */ }; static struct module_stat sl_rstat __attribute__ ((__aligned__(SMP_CACHE_BYTES))); static struct module_stat sl_wstat __attribute__ ((__aligned__(SMP_CACHE_BYTES))); /* * ========================================================================= * * PRIVATE STRUCTURE * * ========================================================================= */ struct st { int l_state; /* local management state */ int i_state; /* interface state */ int i_flags; /* interface flags */ }; struct sl_pair; struct sl { struct sl_pair *pair; /* thread pointer to pair */ struct sl *other; /* other private structure in pair */ queue_t *oq; /* output queue for this side */ uint max_sdu; /* maximum SDU size */ uint min_sdu; /* minimum SDU size */ uint header_len; /* size of Level 1 header */ uint ppa_style; /* PPA style */ struct st state, oldstate; mblk_t *t1; bufq_t tb; bufq_t rb; struct lmi_option option; /* LMI protocol and variant options */ struct { struct sdl_config config; /* SDL configuration options */ struct sdl_notify notify; /* SDL notification options */ struct sdl_statem statem; /* SDL state machine variables */ struct sdl_stats statsp; /* SDL statistics periods */ struct sdl_stats stats; /* SDL statistics */ } sdl; struct { struct sdt_config config; /* SDT configuration */ struct sdt_notify notify; /* SDT events */ struct sdt_statem statem; /* SDT state machine */ struct sdt_stats statsp; /* SDT statistics periods */ struct sdt_stats stats; /* SDT statistics */ } sdt; struct { struct sl_config config; /* SL configuration */ struct sl_notify notify; /* SL events */ struct sl_statem statem; /* SL state machine */ struct sl_stats statsp; /* SL statistics periods */ struct sl_stats stats; /* SL statistics */ } sl; }; struct sl_pair { struct sl r_priv; struct sl w_priv; }; #define PRIV(q) ((struct sl_pair *)(q)->q_ptr) #define SL_PRIV(q) (((q)->q_flag & QREADR) ? &PRIV(q)->r_priv : &PRIV(q)->w_priv) #define STRLOGERR 0 /* log error information */ #define STRLOGNO 0 /* log notice information */ #define STRLOGST 1 /* log state transitions */ #define STRLOGTO 2 /* log timeouts */ #define STRLOGRX 3 /* log primitives received */ #define STRLOGTX 4 /* log primitives issued */ #define STRLOGTE 5 /* log timer events */ #define STRLOGIO 6 /* log additional data */ #define STRLOGDA 7 /* log data */ /** * sdt_iocname: display SDT ioctl command name * @cmd: ioctl command */ static const char * sl_iocname(int cmd) { switch (_IOC_TYPE(cmd)) { #if 1 case SL_IOC_MAGIC: switch (_IOC_NR(cmd)) { case _IOC_NR(SL_IOCGCONFIG): return ("SL_IOCGCONFIG"); case _IOC_NR(SL_IOCSCONFIG): return ("SL_IOCSCONFIG"); case _IOC_NR(SL_IOCTCONFIG): return ("SL_IOCTCONFIG"); case _IOC_NR(SL_IOCCCONFIG): return ("SL_IOCCCONFIG"); case _IOC_NR(SL_IOCGSTATEM): return ("SL_IOCGSTATEM"); case _IOC_NR(SL_IOCCMRESET): return ("SL_IOCCMRESET"); case _IOC_NR(SL_IOCGSTATSP): return ("SL_IOCGSTATSP"); case _IOC_NR(SL_IOCSSTATSP): return ("SL_IOCSSTATSP"); case _IOC_NR(SL_IOCGSTATS): return ("SL_IOCGSTATS"); case _IOC_NR(SL_IOCCSTATS): return ("SL_IOCCSTATS"); case _IOC_NR(SL_IOCGNOTIFY): return ("SL_IOCGNOTIFY"); case _IOC_NR(SL_IOCSNOTIFY): return ("SL_IOCSNOTIFY"); case _IOC_NR(SL_IOCCNOTIFY): return ("SL_IOCCNOTIFY"); default: return ("(unknown ioctl)"); } #endif #if 1 case SDT_IOC_MAGIC: switch (_IOC_NR(cmd)) { case _IOC_NR(SDT_IOCGCONFIG): return ("SDT_IOCGCONFIG"); case _IOC_NR(SDT_IOCSCONFIG): return ("SDT_IOCSCONFIG"); case _IOC_NR(SDT_IOCTCONFIG): return ("SDT_IOCTCONFIG"); case _IOC_NR(SDT_IOCCCONFIG): return ("SDT_IOCCCONFIG"); case _IOC_NR(SDT_IOCGSTATEM): return ("SDT_IOCGSTATEM"); case _IOC_NR(SDT_IOCCMRESET): return ("SDT_IOCCMRESET"); case _IOC_NR(SDT_IOCGSTATSP): return ("SDT_IOCGSTATSP"); case _IOC_NR(SDT_IOCSSTATSP): return ("SDT_IOCSSTATSP"); case _IOC_NR(SDT_IOCGSTATS): return ("SDT_IOCGSTATS"); case _IOC_NR(SDT_IOCCSTATS): return ("SDT_IOCCSTATS"); case _IOC_NR(SDT_IOCGNOTIFY): return ("SDT_IOCGNOTIFY"); case _IOC_NR(SDT_IOCSNOTIFY): return ("SDT_IOCSNOTIFY"); case _IOC_NR(SDT_IOCCNOTIFY): return ("SDT_IOCCNOTIFY"); default: return ("(unknown ioctl)"); } #endif case SDL_IOC_MAGIC: switch (_IOC_NR(cmd)) { case _IOC_NR(SDL_IOCGCONFIG): return ("SDL_IOCGCONFIG"); case _IOC_NR(SDL_IOCSCONFIG): return ("SDL_IOCSCONFIG"); case _IOC_NR(SDL_IOCTCONFIG): return ("SDL_IOCTCONFIG"); case _IOC_NR(SDL_IOCCCONFIG): return ("SDL_IOCCCONFIG"); case _IOC_NR(SDL_IOCGSTATEM): return ("SDL_IOCGSTATEM"); case _IOC_NR(SDL_IOCCMRESET): return ("SDL_IOCCMRESET"); case _IOC_NR(SDL_IOCGSTATSP): return ("SDL_IOCGSTATSP"); case _IOC_NR(SDL_IOCSSTATSP): return ("SDL_IOCSSTATSP"); case _IOC_NR(SDL_IOCGSTATS): return ("SDL_IOCGSTATS"); case _IOC_NR(SDL_IOCCSTATS): return ("SDL_IOCCSTATS"); case _IOC_NR(SDL_IOCGNOTIFY): return ("SDL_IOCGNOTIFY"); case _IOC_NR(SDL_IOCSNOTIFY): return ("SDL_IOCSNOTIFY"); case _IOC_NR(SDL_IOCCNOTIFY): return ("SDL_IOCCNOTIFY"); default: return ("(unknown ioctl)"); } case LMI_IOC_MAGIC: switch (_IOC_NR(cmd)) { case _IOC_NR(LMI_IOCGOPTIONS): return ("LMI_IOCGOPTIONS"); case _IOC_NR(LMI_IOCSOPTIONS): return ("LMI_IOCSOPTIONS"); default: return ("(unknown ioctl)"); } default: return ("(unknown ioctl)"); } } /** * sl_primname: display SL primitive name * @prim: the primtitive to display */ static const char * sl_primname(sl_ulong prim) { switch (prim) { case LMI_INFO_REQ: return ("LMI_INFO_REQ"); case LMI_ATTACH_REQ: return ("LMI_ATTACH_REQ"); case LMI_DETACH_REQ: return ("LMI_DETACH_REQ"); case LMI_ENABLE_REQ: return ("LMI_ENABLE_REQ"); case LMI_DISABLE_REQ: return ("LMI_DISABLE_REQ"); case LMI_OPTMGMT_REQ: return ("LMI_OPTMGMT_REQ"); case LMI_INFO_ACK: return ("LMI_INFO_ACK"); case LMI_OK_ACK: return ("LMI_OK_ACK"); case LMI_ERROR_ACK: return ("LMI_ERROR_ACK"); case LMI_ENABLE_CON: return ("LMI_ENABLE_CON"); case LMI_DISABLE_CON: return ("LMI_DISABLE_CON"); case LMI_OPTMGMT_ACK: return ("LMI_OPTMGMT_ACK"); case LMI_ERROR_IND: return ("LMI_ERROR_IND"); case LMI_STATS_IND: return ("LMI_STATS_IND"); case LMI_EVENT_IND: return ("LMI_EVENT_IND"); #if 0 case SDL_BITS_FOR_TRANSMISSION_REQ: return ("SDL_BITS_FOR_TRANSMISSION_REQ"); case SDL_CONNECT_REQ: return ("SDL_CONNECT_REQ"); case SDL_DISCONNECT_REQ: return ("SDL_DISCONNECT_REQ"); case SDL_RECEIVED_BITS_IND: return ("SDL_RECEIVED_BITS_IND"); case SDL_DISCONNECT_IND: return ("SDL_DISCONNECT_IND"); #endif #if 0 case SDT_DAEDT_TRANSMISSION_REQ: return ("SDT_DAEDT_TRANSMISSION_REQ"); case SDT_DAEDT_START_REQ: return ("SDT_DAEDT_START_REQ"); case SDT_DAEDR_START_REQ: return ("SDT_DAEDR_START_REQ"); case SDT_AERM_START_REQ: return ("SDT_AERM_START_REQ"); case SDT_AERM_STOP_REQ: return ("SDT_AERM_STOP_REQ"); case SDT_AERM_SET_TI_TO_TIN_REQ: return ("SDT_AERM_SET_TI_TO_TIN_REQ"); case SDT_AERM_SET_TI_TO_TIE_REQ: return ("SDT_AERM_SET_TI_TO_TIE_REQ"); case SDT_SUERM_START_REQ: return ("SDT_SUERM_START_REQ"); case SDT_SUERM_STOP_REQ: return ("SDT_SUERM_STOP_REQ"); case SDT_RC_SIGNAL_UNIT_IND: return ("SDT_RC_SIGNAL_UNIT_IND"); case SDT_RC_CONGESTION_ACCEPT_IND: return ("SDT_RC_CONGESTION_ACCEPT_IND"); case SDT_RC_CONGESTION_DISCARD_IND: return ("SDT_RC_CONGESTION_DISCARD_IND"); case SDT_RC_NO_CONGESTION_IND: return ("SDT_RC_NO_CONGESTION_IND"); case SDT_IAC_CORRECT_SU_IND: return ("SDT_IAC_CORRECT_SU_IND"); case SDT_IAC_ABORT_PROVING_IND: return ("SDT_IAC_ABORT_PROVING_IND"); case SDT_LSC_LINK_FAILURE_IND: return ("SDT_LSC_LINK_FAILURE_IND"); case SDT_TXC_TRANSMISSION_REQUEST_IND: return ("SDT_TXC_TRANSMISSION_REQUEST_IND"); #endif #if 1 case SL_PDU_REQ: return ("SL_PDU_REQ"); case SL_EMERGENCY_REQ: return ("SL_EMERGENCY_REQ"); case SL_EMERGENCY_CEASES_REQ: return ("SL_EMERGENCY_CEASES_REQ"); case SL_START_REQ: return ("SL_START_REQ"); case SL_STOP_REQ: return ("SL_STOP_REQ"); case SL_RETRIEVE_BSNT_REQ: return ("SL_RETRIEVE_BSNT_REQ"); case SL_RETRIEVAL_REQUEST_AND_FSNC_REQ: return ("SL_RETRIEVAL_REQUEST_AND_FSNC_REQ"); case SL_CLEAR_BUFFERS_REQ: return ("SL_CLEAR_BUFFERS_REQ"); case SL_CLEAR_RTB_REQ: return ("SL_CLEAR_RTB_REQ"); case SL_CONTINUE_REQ: return ("SL_CONTINUE_REQ"); case SL_LOCAL_PROCESSOR_OUTAGE_REQ: return ("SL_LOCAL_PROCESSOR_OUTAGE_REQ"); case SL_RESUME_REQ: return ("SL_RESUME_REQ"); case SL_CONGESTION_DISCARD_REQ: return ("SL_CONGESTION_DISCARD_REQ"); case SL_CONGESTION_ACCEPT_REQ: return ("SL_CONGESTION_ACCEPT_REQ"); case SL_NO_CONGESTION_REQ: return ("SL_NO_CONGESTION_REQ"); case SL_POWER_ON_REQ: return ("SL_POWER_ON_REQ"); case SL_OPTMGMT_REQ: return ("SL_OPTMGMT_REQ"); case SL_NOTIFY_REQ: return ("SL_NOTIFY_REQ"); case SL_PDU_IND: return ("SL_PDU_IND"); case SL_LINK_CONGESTED_IND: return ("SL_LINK_CONGESTED_IND"); case SL_LINK_CONGESTION_CEASED_IND: return ("SL_LINK_CONGESTION_CEASED_IND"); case SL_RETRIEVED_MESSAGE_IND: return ("SL_RETRIEVED_MESSAGE_IND"); case SL_RETRIEVAL_COMPLETE_IND: return ("SL_RETRIEVAL_COMPLETE_IND"); case SL_RB_CLEARED_IND: return ("SL_RB_CLEARED_IND"); case SL_BSNT_IND: return ("SL_BSNT_IND"); case SL_IN_SERVICE_IND: return ("SL_IN_SERVICE_IND"); case SL_OUT_OF_SERVICE_IND: return ("SL_OUT_OF_SERVICE_IND"); case SL_REMOTE_PROCESSOR_OUTAGE_IND: return ("SL_REMOTE_PROCESSOR_OUTAGE_IND"); case SL_REMOTE_PROCESSOR_RECOVERED_IND: return ("SL_REMOTE_PROCESSOR_RECOVERED_IND"); case SL_RTB_CLEARED_IND: return ("SL_RTB_CLEARED_IND"); case SL_RETRIEVAL_NOT_POSSIBLE_IND: return ("SL_RETRIEVAL_NOT_POSSIBLE_IND"); case SL_BSNT_NOT_RETRIEVABLE_IND: return ("SL_BSNT_NOT_RETRIEVABLE_IND"); case SL_OPTMGMT_ACK: return ("SL_OPTMGMT_ACK"); case SL_NOTIFY_IND: return ("SL_NOTIFY_IND"); case SL_LOCAL_PROCESSOR_OUTAGE_IND: return ("SL_LOCAL_PROCESSOR_OUTAGE_IND"); case SL_LOCAL_PROCESSOR_RECOVERED_IND: return ("SL_LOCAL_PROCESSOR_RECOVERED_IND"); #endif default: return ("(unknown primitive)"); } } /** * sl_l_state_name: display LMI state name * @state: the state value to display */ static const char * sl_l_state_name(int state) { switch (state) { case LMI_UNATTACHED: return ("LMI_UNATTACHED"); case LMI_ATTACH_PENDING: return ("LMI_ATTACH_PENDING"); case LMI_UNUSABLE: return ("LMI_UNUSABLE"); case LMI_DISABLED: return ("LMI_DISABLED"); case LMI_ENABLE_PENDING: return ("LMI_ENABLE_PENDING"); case LMI_ENABLED: return ("LMI_ENABLED"); case LMI_DISABLE_PENDING: return ("LMI_DISABLE_PENDING"); case LMI_DETACH_PENDING: return ("LMI_DETACH_PENDING"); default: return ("LMI_????"); } } static const char * sl_i_state_name(int state) { switch (state) { case SLS_POWER_OFF: return ("SLS_POWER_OFF"); case SLS_OUT_OF_SERVICE: return ("SLS_OUT_OF_SERVICE"); case SLS_NOT_ALIGNED: return ("SLS_NOT_ALIGNED"); case SLS_INITIAL_ALIGNMENT: return ("SLS_INITIAL_ALIGNMENT"); case SLS_PROVING: return ("SLS_PROVING"); case SLS_ALIGNED_READY: return ("SLS_ALIGNED_READY"); case SLS_ALIGNED_NOT_READY: return ("SLS_ALIGNED_NOT_READY"); case SLS_IN_SERVICE: return ("SLS_IN_SERVICE"); case SLS_PROCESSOR_OUTAGE: return ("SLS_PROCESSOR_OUTAGE"); default: return ("SL_????"); } } static const char * sl_flags_set(int mask) { switch (mask & (SLF_LOC_PROC_OUT | SLF_REM_PROC_OUT | SLF_EMERGENCY)) { case 0: return (""); case SLF_LOC_PROC_OUT: return ("(LOC)"); case SLF_REM_PROC_OUT: return ("(REM)"); case SLF_EMERGENCY: return ("(EMERG)"); case SLF_LOC_PROC_OUT | SLF_REM_PROC_OUT: return ("(LOC|REM)"); case SLF_LOC_PROC_OUT | SLF_EMERGENCY: return ("(LOC|EMERG)"); case SLF_LOC_PROC_OUT | SLF_REM_PROC_OUT | SLF_EMERGENCY: return ("(LOC|REM|EMERG)"); default: return ("(error)"); } } /* * ========================================================================== * STATE TRANSITIONS * ========================================================================== */ /** * sl_get_l_state: - get management state for private structure * @sl: private structure */ static int sl_get_l_state(struct sl *sl) { return (sl->state.l_state); } /** * sl_set_l_state: - set management state for private structure * @sl: private structure * @newstate: new state */ static int sl_set_l_state(struct sl *sl, int newstate) { int oldstate = sl->state.l_state; if (newstate != oldstate) { sl->state.l_state = newstate; mi_strlog(sl->oq, STRLOGST, SL_TRACE, "%s <- %s", sl_l_state_name(newstate), sl_l_state_name(oldstate)); } return (newstate); } static int sl_save_l_state(struct sl *sl) { return ((sl->oldstate.l_state = sl_get_l_state(sl))); } static int sl_restore_l_state(struct sl *sl) { return sl_set_l_state(sl, sl->oldstate.l_state); } /** * sl_get_i_state: - get interface state for private structure * @sl: private structure */ static int sl_get_i_state(struct sl *sl) { return (sl->state.i_state); } /** * sl_set_i_state: - set interface state for private structure * @sl: private structure * @newstate: new state */ static int sl_set_i_state(struct sl *sl, int newstate) { int oldstate = sl_get_i_state(sl); if (newstate != oldstate) { sl->state.i_state = newstate; mi_strlog(sl->oq, STRLOGST, SL_TRACE, "%s <- %s", sl_i_state_name(newstate), sl_i_state_name(oldstate)); } return (newstate); } static int sl_save_i_state(struct sl *sl) { return ((sl->oldstate.l_state = sl_get_i_state(sl))); } static int sl_restore_i_state(struct sl *sl) { return sl_set_i_state(sl, sl->oldstate.l_state); } /** * sl_save_state: - reset state for private structure * @sl: private structure */ static void sl_save_state(struct sl *sl) { sl_save_l_state(sl); sl_save_i_state(sl); } /** * sl_restore_state: - reset state for private structure * @sl: private structure */ static int sl_restore_state(struct sl *sl) { sl_restore_i_state(sl); return sl_restore_l_state(sl); } /** * sl_get_flags: - get flags for private structure * @sl: private structure */ static int sl_get_flags(struct sl *sl) { return (sl->state.i_flags); } /** * sl_set_flags: - set flags for private structure * @sl: private structure * @newflags: new flags */ static int sl_set_flags(struct sl *sl, int mask) { int oldflags = sl_get_flags(sl), newflags = oldflags |= mask; if (oldflags != newflags) mi_strlog(sl->oq, STRLOGST, SL_TRACE, "%s", sl_flags_set((newflags ^ oldflags) & mask)); return (sl->state.i_flags = newflags); } static inline int sl_or_flags(struct sl *sl, int orflags) { return (sl->state.i_flags |= orflags); } static inline int sl_nand_flags(struct sl *sl, int nandflags) { return (sl->state.i_flags &= ~nandflags); } /** * sl_save_flags: - reset flags for private structure * @sl: private structure */ static void sl_save_flags(struct sl *sl) { sl->oldstate.i_flags = sl->state.i_flags; } /** * sl_restore_flags: - reset flags for private structure * @sl: private structure */ static int sl_restore_flags(struct sl *sl) { return sl_set_flags(sl, sl->oldstate.i_flags); } static void sl_save_total_state(struct sl *sl) { sl_save_flags(sl->other); sl_save_state(sl->other); sl_save_flags(sl); sl_save_state(sl); } static int sl_restore_total_state(struct sl *sl) { sl_restore_flags(sl->other); sl_restore_state(sl->other); sl_restore_flags(sl); return sl_restore_state(sl); } static inline int sl_clr_flags(struct sl *sl, int mask) { int oldflags = sl_get_flags(sl), newflags = oldflags &= ~mask; if (oldflags != newflags) mi_strlog(sl->oq, STRLOGST, SL_TRACE, "~%s", sl_flags_set((newflags ^ oldflags) & mask)); return (sl->state.i_flags = newflags); } static void sl_timer_start(struct sl *sl, int timer, unsigned long value) { switch (timer) { case 1: mi_timer(sl->oq, sl->t1, value); break; default: break; } } static void sl_timer_stop(struct sl *sl, int timer) { switch (timer) { case 1: mi_timer_cancel(sl->t1); break; default: break; } } /* * ========================================================================= * * ISSUED PRIMITIVES * * SL Provider -> SL User primitives. * * ========================================================================= */ #if 0 /** * m_error: - issue M_ERROR for stream * @s: private structure * @q: active queue * @msg: message to free upon success * @err: error to indicate */ static int m_error(struct sl *s, queue_t *q, mblk_t *msg, int err) { mblk_t *mp; if ((mp = mi_allocb(q, 2, BPRI_MED))) { DB_TYPE(mp) = M_ERROR; *(mp->b_wptr)++ = err < 0 ? -err : err; *(mp->b_wptr)++ = err < 0 ? -err : err; freemsg(msg); mi_strlog(s->oq, 0, SL_ERROR, "<- M_ERROR %d", err); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } #endif /** * lmi_info_ack: - issue LMI_INFO_ACK primitive * @s: private structure * @q: active queue (write queue) * @msg: message to free upon success */ static int lmi_info_ack(struct sl *s, queue_t *q, mblk_t *msg) { lmi_info_ack_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_INFO_ACK; p->lmi_version = LMI_CURRENT_VERSION; p->lmi_state = sl_get_l_state(s); p->lmi_max_sdu = s->max_sdu; p->lmi_min_sdu = s->min_sdu; p->lmi_header_len = s->header_len; p->lmi_ppa_style = LMI_STYLE1; p->lmi_ppa_length = 0; p->lmi_ppa_offset = sizeof(*p); p->lmi_prov_flags = s->state.i_flags; /* FIXME maintain provider flags */ p->lmi_prov_state = s->state.i_state; /* FIXME maintain provider state */ mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_INFO_ACK"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } /** * lmi_ok_ack: - issue LMI_OK_ACK primitive * @s: private structure * @q: active queue * @msg: message to free upon success * @prim: correct primitive */ static inline int lmi_ok_ack(struct sl *s, queue_t *q, mblk_t *msg, int prim) { lmi_ok_ack_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_OK_ACK; p->lmi_correct_primitive = prim; switch (sl_get_l_state(s)) { case LMI_ATTACH_PENDING: p->lmi_state = sl_set_l_state(s, LMI_DISABLED); break; case LMI_DETACH_PENDING: p->lmi_state = sl_set_l_state(s, LMI_UNATTACHED); break; default: /* FIXME: log error */ p->lmi_state = sl_get_l_state(s); break; } mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_OK_ACK"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } /** * lmi_error_ack: - issue LMI_ERROR_ACK primitive * @s: private structure * @q: active queue * @msg: message to free upon success * @prim: primitive in error * @error: error number */ static noinline fastcall __unlikely int lmi_error_ack(struct sl *s, queue_t *q, mblk_t *msg, int prim, int error) { lmi_error_ack_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_ERROR_ACK; p->lmi_errno = error < 0 ? LMI_SYSERR : error; p->lmi_reason = error < 0 ? -error : 0; p->lmi_error_primitive = prim; p->lmi_state = sl_restore_l_state(s); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_ERROR_ACK"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } /** * lmi_error_reply: - generate error acknolwegement as required * @s: private structure * @q: active queue * @msg: message to free upon success * @error: error to return (negative, put message back) (positive, error ack) */ static inline int lmi_error_reply(struct sl *s, queue_t *q, mblk_t *msg, int prim, int error) { if (error == 0) freemsg(msg); else if (error > 0) return lmi_error_ack(s, q, msg, prim, error); return (error); } /** * lmi_enable_con: - issue LMI_ENABLE_CON primitive * @s: private structure * @q: active queue * @msg: message to free upon success */ static int lmi_enable_con(struct sl *s, queue_t *q, mblk_t *msg) { lmi_enable_con_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_ENABLE_CON; p->lmi_state = sl_set_l_state(s, LMI_ENABLED); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_ENABLE_CON"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } /** * lmi_disable_con: - issue LMI_DISABLE_CON primitive * @s: private structure * @q: active queue * @msg: message to free upon success */ static int lmi_disable_con(struct sl *s, queue_t *q, mblk_t *msg) { lmi_disable_con_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_DISABLE_CON; p->lmi_state = sl_set_l_state(s, LMI_DISABLED); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_DISABLE_CON"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } /** * lmi_optmgmt_ack: - issue LMI_OPTMGMT_ACK primitive * @s: private structure * @q: active queue * @msg: message to free upon success * @opt_ptr: options pointer * @opt_len: options length * @flags: management flags */ static inline int lmi_optmgmt_ack(struct sl *s, queue_t *q, mblk_t *msg, caddr_t opt_ptr, size_t opt_len, uint flags) { lmi_optmgmt_ack_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p) + opt_len, BPRI_MED)))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_OPTMGMT_ACK; p->lmi_opt_length = opt_len; p->lmi_opt_offset = opt_len ? sizeof(*p) : 0; p->lmi_mgmt_flags = flags; mp->b_wptr += sizeof(*p); bcopy(opt_ptr, mp->b_wptr, opt_len); mp->b_wptr += opt_len; freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_OPTMGMT_ACK"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } /** * lmi_error_ind: - issue LMI_ERROR_IND primitive * @s: private structure * @q: active queue * @msg: message to free upon success * @error: error to indicate * @state: state after error indication */ static inline int lmi_error_ind(struct sl *s, queue_t *q, mblk_t *msg, int error, uint state) { lmi_error_ind_t *p; mblk_t *mp; if (canputnext(s->oq)) { if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_ERROR_IND; p->lmi_errno = error < 0 ? LMI_SYSERR : error; p->lmi_reason = error < 0 ? -error : 0; p->lmi_state = sl_set_l_state(s, state); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_ERROR_IND"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } return (-EBUSY); } /** * lmi_stats_ind: - issue LMI_STATS_IND primitive * @s: private structure * @q: active queue * @msg: message to free upon success */ static inline int lmi_stats_ind(struct sl *s, queue_t *q, mblk_t *msg, lmi_ulong itvl) { lmi_stats_ind_t *p; mblk_t *mp; if (bcanputnext(s->oq, 1)) { if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; mp->b_band = 1; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_STATS_IND; p->lmi_interval = itvl; p->lmi_timestamp = drv_hztomsec(jiffies); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_STATS_IND"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } return (-EBUSY); } /** * lmi_event_ind: - issue LMI_EVENT_IND primitive * @s: private structure * @q: active queue * @msg: message to free upon success * @oid: event object id * @level: severity * @inf_ptr: information pointer * @inf_len: information length */ static inline int lmi_event_ind(struct sl *s, queue_t *q, mblk_t *msg, uint oid, uint severity, caddr_t inf_ptr, size_t inf_len) { lmi_event_ind_t *p; mblk_t *mp; if (bcanputnext(s->oq, 1)) { if (likely(!!(mp = mi_allocb(q, sizeof(*p) + inf_len, BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; mp->b_band = 1; p = (typeof(p)) mp->b_wptr; p->lmi_primitive = LMI_EVENT_IND; p->lmi_objectid = oid; p->lmi_timestamp = drv_hztomsec(jiffies); p->lmi_severity = severity; mp->b_wptr += sizeof(*p); bcopy(inf_ptr, mp->b_wptr, inf_len); mp->b_wptr += inf_len; freemsg(msg); mi_strlog(s->oq, STRLOGTX, SL_TRACE, "<- LMI_EVENT_IND"); putnext(s->oq, mp); return (0); } return (-ENOBUFS); } return (-EBUSY); } /** * sl_pdu_ind: - issue SL_PDU_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success * @dp: user data */ static inline int sl_pdu_ind(struct sl *sl, queue_t *q, mblk_t *msg, sl_ulong pri, mblk_t *dp) { sl_pdu_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { if (likely(canputnext(sl->oq))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_PDU_IND; p->sl_mp = pri; mp->b_wptr += sizeof(*p); mp->b_cont = dp; freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_PDU_IND"); putnext(sl->oq, mp); return (0); } freeb(mp); return (-EBUSY); } return (-ENOBUFS); } /** * sl_link_congested_ind: - issue SL_LINK_CONGESTED_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static inline int sl_link_congested_ind(struct sl *sl, queue_t *q, mblk_t *msg, sl_ulong cong, sl_ulong disc) { sl_link_cong_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { if (bcanputnext(sl->oq, 1)) { DB_TYPE(mp) = M_PROTO; mp->b_band = 1; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_LINK_CONGESTED_IND; p->sl_timestamp = drv_hztomsec(jiffies); p->sl_cong_status = cong; p->sl_disc_status = disc; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_LINK_CONGESTED_IND"); putnext(sl->oq, mp); return (0); } freeb(mp); return (-EBUSY); } return (-ENOBUFS); } /** * sl_linK_congestion_ceased_ind: - issue SL_LINK_CONGESTION_CEASED_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static inline int sl_link_congestion_ceased_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_link_cong_ceased_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { if (bcanputnext(sl->oq, 1)) { DB_TYPE(mp) = M_PROTO; mp->b_band = 1; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_LINK_CONGESTION_CEASED_IND; p->sl_timestamp = drv_hztomsec(jiffies); p->sl_cong_status = 0; p->sl_disc_status = 0; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_LINK_CONGESTION_CEASED_IND"); putnext(sl->oq, mp); return (0); } freeb(mp); return (-EBUSY); } return (-ENOBUFS); } /** * sl_retrieved_message_ind: - issue SL_RETRIEVED_MESSAGE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_retrieved_message_ind(struct sl *sl, queue_t *q, mblk_t *msg, sl_ulong pri, mblk_t *dp) { sl_retrieved_msg_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_RETRIEVED_MESSAGE_IND; p->sl_mp = pri; mp->b_wptr += sizeof(*p); mp->b_cont = dp; if (msg && msg->b_cont == dp) msg->b_cont = NULL; freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_RETRIEVED_MESSAGE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_retrieval_complete_ind: - issue SL_RETRIEVAL_COMPLETE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_retrieval_complete_ind(struct sl *sl, queue_t *q, mblk_t *msg, sl_ulong pri, mblk_t *dp) { sl_retrieval_comp_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_RETRIEVAL_COMPLETE_IND; p->sl_mp = pri; mp->b_wptr += sizeof(*p); mp->b_cont = dp; freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_RETRIEVAL_COMPLETE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_rb_cleared_ind: - issue SL_RB_CLEARED_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_rb_cleared_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_rb_cleared_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_RB_CLEARED_IND; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_RB_CLEARED_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_bsnt_ind: - issue SL_BSNT_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static inline int sl_bsnt_ind(struct sl *sl, queue_t *q, mblk_t *msg, sl_ulong bsnt) { sl_bsnt_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_BSNT_IND; p->sl_bsnt = bsnt; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_BSNT_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_in_service_ind: - issue SL_IN_SERVICE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_in_service_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_in_service_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_IN_SERVICE_IND; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_IN_SERVICE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_out_of_service_ind: - issue SL_OUT_OF_SERVICE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_out_of_service_ind(struct sl *sl, queue_t *q, mblk_t *msg, sl_ulong reason) { sl_out_of_service_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_OUT_OF_SERVICE_IND; p->sl_timestamp = drv_hztomsec(jiffies); p->sl_reason = reason; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_OUT_OF_SERVICE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_remote_processor_outage_ind: - issue SL_REMOTE_PROCESSOR_OUTAGE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_remote_processor_outage_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_rem_proc_out_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_REMOTE_PROCESSOR_OUTAGE_IND; p->sl_timestamp = drv_hztomsec(jiffies); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_REMOTE_PROCESSOR_OUTAGE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_remote_processor_recovered_ind: - issue SL_REMOTE_PROCESSOR_RECOVERED_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_remote_processor_recovered_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_rem_proc_recovered_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_REMOTE_PROCESSOR_RECOVERED_IND; p->sl_timestamp = drv_hztomsec(jiffies); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_REMOTE_PROCESSOR_RECOVERED_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_rtb_cleared_ind: - issue SL_RTB_CLEARED_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_rtb_cleared_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_rtb_cleared_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_RTB_CLEARED_IND; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_RTB_CLEARED_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_retrieval_not_possible_ind: - issue SL_RETRIEVAL_NOT_POSSIBLE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_retrieval_not_possible_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_retrieval_not_poss_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_RETRIEVAL_NOT_POSSIBLE_IND; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_RETRIEVAL_NOT_POSSIBLE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_bsnt_not_retrievable_ind: - issue SL_BSNT_NOT_RETRIEVABLE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_bsnt_not_retrievable_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_bsnt_not_retr_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_BSNT_NOT_RETRIEVABLE_IND; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_BSNT_NOT_RETRIEVABLE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } #if 0 /** * sl_optmgmt_ack: - issue SL_OPTMGMT_ACK primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_optmgmt_ack(struct sl *sl, queue_t *q, mblk_t *msg) { sl_optmgmt_ack_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_OPTMGMT_ACK; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_OPTMGMT_ACK"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_notify_ind: - issue SL_NOTIFY_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static int sl_notify_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_notify_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_NOTIFY_IND; mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_NOTIFY_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } #endif /** * sl_local_processor_outage_ind: - issue SL_LOCAL_PROCESSOR_OUTAGE_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static inline int sl_local_processor_outage_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_loc_proc_out_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_LOCAL_PROCESSOR_OUTAGE_IND; p->sl_timestamp = drv_hztomsec(jiffies); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_LOCAL_PROCESSOR_OUTAGE_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /** * sl_local_processor_recovered_ind: - issue SL_LOCAL_PROCESSOR_RECOVERED_IND primitive * @sl: output signalling link * @q: active queue * @msg: message to free upon success */ static inline int sl_local_processor_recovered_ind(struct sl *sl, queue_t *q, mblk_t *msg) { sl_loc_proc_recovered_ind_t *p; mblk_t *mp; if (likely(!!(mp = mi_allocb(q, sizeof(*p), BPRI_MED)))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; p->sl_primitive = SL_LOCAL_PROCESSOR_RECOVERED_IND; p->sl_timestamp = drv_hztomsec(jiffies); mp->b_wptr += sizeof(*p); freemsg(msg); mi_strlog(sl->oq, STRLOGTX, SL_TRACE, "<- SL_LOCAL_PROCESSOR_RECOVERED_IND"); putnext(sl->oq, mp); return (0); } return (-ENOBUFS); } /* * ========================================================================= * * SL User -> SL Provider Primitives * * ========================================================================= */ /** * lmi_info_req: - process LMI_INFO_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the LMI_INFO_REQ primitive */ static int lmi_info_req(struct sl *sl, queue_t *q, mblk_t *mp) { return lmi_info_ack(sl, q, mp); } /** * lmi_attach_req: - process LMI_ATTACH_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the LMI_ATTACH_REQ primitive * * SL-PMOD is always an LMI_STYLE1 module. LMI_ATTACH_REQ is not supported. */ static int lmi_attach_req(struct sl *sl, queue_t *q, mblk_t *mp) { return lmi_error_ack(sl, q, mp, LMI_ATTACH_REQ, LMI_NOTSUPP); } /** * lmi_detach_req: - process LMI_DETACH_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the LMI_DETACH_REQ primitive * * SL-PMOD is always an LMI_STYLE1 module. LMI_DETACH_REQ is not supported. */ static int lmi_detach_req(struct sl *sl, queue_t *q, mblk_t *mp) { return lmi_error_ack(sl, q, mp, LMI_DETACH_REQ, LMI_NOTSUPP); } /** * lmi_enable_req: - process LMI_ENABLE_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the LMI_ENABLE_REQ primitive * * When requested, enable the local signalling link. */ static int lmi_enable_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_DISABLED) goto outstate; sl_set_l_state(sl, LMI_ENABLE_PENDING); return lmi_enable_con(sl, q, mp); outstate: return lmi_error_ack(sl, q, mp, LMI_ENABLE_REQ, LMI_OUTSTATE); } /** * lmi_disable_req: - process LMI_DISABLE_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the LMI_DISABLE_REQ primitive * * When requested, disable the local signalling link. */ static int lmi_disable_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; sl_set_l_state(sl, LMI_DISABLE_PENDING); return lmi_disable_con(sl, q, mp); outstate: return lmi_error_ack(sl, q, mp, LMI_DISABLE_REQ, LMI_OUTSTATE); } /** * lmi_optmgmt_req: - process LMI_OPTMGMT_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the LMI_OPTMGMT_REQ primitive * * Not supported for now. */ static int lmi_optmgmt_req(struct sl *sl, queue_t *q, mblk_t *mp) { return lmi_error_ack(sl, q, mp, LMI_OPTMGMT_REQ, LMI_NOTSUPP); } /** * sl_pdu_req: - process SDL_PDU_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SDL_PDU_REQ primitive * * Whenever the signalling link is not in service, simply put the message back on the queue, disable * the queue, and wait for some other event to happend. */ static int sl_pdu_req(struct sl *sl, queue_t *q, mblk_t *mp) { struct sl *so = sl->other; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; if (sl_get_i_state(sl) != SLS_IN_SERVICE) { bufq_queue(&sl->tb, mp); return (0); } if (bcanputnext(so->oq, mp->b_band)) { *(sl_ulong *) mp->b_rptr = SL_PDU_IND; putnext(so->oq, mp); return (0); } return (-EBUSY); outstate: return lmi_error_ack(sl, q, mp, SL_PDU_REQ, LMI_OUTSTATE); } /** * sl_emergency_req: - process SL_EMERGENCY_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_EMERGENCY_REQ primitive */ static int sl_emergency_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; sl_set_flags(sl, SLF_EMERGENCY); outstate: freemsg(mp); return (0); } /** * sl_emergency_ceases_req: - process SL_EMERGENCY_CEASES_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_EMERGENCY_CEASES_REQ primitive */ static int sl_emergency_ceases_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; sl_clr_flags(sl, SLF_EMERGENCY); outstate: freemsg(mp); return (0); } /** * sl_start_req: - process SL_START_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_START_REQ primitive */ static int sl_start_req(struct sl *sl, queue_t *q, mblk_t *mp) { struct sl *so = sl->other; int err; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; switch (sl_get_i_state(sl)) { case SLS_POWER_OFF: goto outstate; case SLS_OUT_OF_SERVICE: sl_set_i_state(sl, SLS_INITIAL_ALIGNMENT); sl_timer_start(sl, 1, 20000); switch (sl_get_i_state(so)) { case SLS_POWER_OFF: break; case SLS_INITIAL_ALIGNMENT: sl_timer_stop(sl, 1); if (sl_get_flags(sl) & (SLF_LOC_PROC_OUT | SLF_REM_PROC_OUT)) { sl_set_i_state(sl, SLS_ALIGNED_NOT_READY); if ((err = sl_remote_processor_outage_ind(so, q, mp))) return (err); } else { sl_set_i_state(sl, SLS_ALIGNED_READY); if ((err = sl_in_service_ind(so, q, mp))) return (err); } if (sl_get_flags(so) & (SLF_LOC_PROC_OUT | SLF_REM_PROC_OUT)) { sl_set_i_state(so, SLS_ALIGNED_NOT_READY); if ((err = sl_remote_processor_outage_ind(sl, q, mp))) return (err); } else { sl_set_i_state(so, SLS_ALIGNED_READY); if ((err = sl_in_service_ind(sl, q, mp))) return (err); } break; case SLS_ALIGNED_READY: case SLS_ALIGNED_NOT_READY: case SLS_IN_SERVICE: default: goto outstate; } break; case SLS_INITIAL_ALIGNMENT: case SLS_ALIGNED_READY: case SLS_ALIGNED_NOT_READY: case SLS_IN_SERVICE: goto discard; default: goto outstate; } discard: outstate: freemsg(mp); return (0); } /** * sl_stop_req: - process SL_STOP_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_STOP_REQ primitive */ static int sl_stop_req(struct sl *sl, queue_t *q, mblk_t *mp) { struct sl *so = sl->other; int err; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; switch (sl_get_i_state(sl)) { case SLS_POWER_OFF: goto discard; case SLS_OUT_OF_SERVICE: goto discard; case SLS_INITIAL_ALIGNMENT: case SLS_ALIGNED_READY: case SLS_ALIGNED_NOT_READY: case SLS_IN_SERVICE: default: sl_timer_stop(sl, 1); sl_set_i_state(sl, SLS_OUT_OF_SERVICE); switch (sl_get_i_state(so)) { case SLS_POWER_OFF: case SLS_OUT_OF_SERVICE: break; case SLS_INITIAL_ALIGNMENT: case SLS_ALIGNED_READY: case SLS_ALIGNED_NOT_READY: case SLS_IN_SERVICE: default: sl_timer_stop(so, 1); sl_set_i_state(so, SLS_OUT_OF_SERVICE); if ((err = sl_out_of_service_ind(so, q, mp, 0))) return (err); break; } break; } discard: outstate: freemsg(mp); return (0); } /** * sl_retrieve_bsnt_req: - process SL_RETRIEVE_BSNT_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_RETRIEVE_BSNT_REQ primitive */ static int sl_retrieve_bsnt_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; return sl_bsnt_not_retrievable_ind(sl, q, mp); outstate: return lmi_error_ack(sl, q, mp, SL_RETRIEVE_BSNT_REQ, LMI_OUTSTATE); } /** * sl_retrieval_request_and_fsnc_req: - process SL_RETRIEVAL_REQUEST_AND_FSNC_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_RETRIEVAL_REQUEST_AND_FSNC_REQ primitive * * Because there is no retranmission buffer in this implemetnation, the FSNC * can be ignored. We do, however, have a transmission buffer, the contents * of which can be retrieved. */ static int sl_retrieval_request_and_fsnc_req(struct sl *sl, queue_t *q, mblk_t *mp) { mblk_t *bp; int err; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; if ((bp = bufq_head(&sl->tb))) { while ((bp = bufq_dequeue(&sl->tb))) { sl_pdu_req_t *p = (typeof(p)) bp->b_rptr; if ((err = sl_retrieved_message_ind(sl, q, bp, p->sl_mp, bp->b_cont))) { bufq_queue_head(&sl->tb, bp); return (err); } } return sl_retrieval_complete_ind(sl, q, mp, 0, NULL); } return sl_retrieval_not_possible_ind(sl, q, mp); outstate: return lmi_error_ack(sl, q, mp, SL_RETRIEVAL_REQUEST_AND_FSNC_REQ, LMI_OUTSTATE); } /** * sl_clear_buffers_req: - process SL_CLEAR_BUFFERS_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_CLEAR_BUFFERS_REQ primitive */ static int sl_clear_buffers_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; bufq_purge(&sl->tb); /* purge the transmission buffer */ bufq_purge(&sl->rb); /* purge the receive buffer */ return sl_rb_cleared_ind(sl, q, mp); outstate: return lmi_error_ack(sl, q, mp, SL_CLEAR_BUFFERS_REQ, LMI_OUTSTATE); } /** * sl_clear_rtb_req: - process SL_CLEAR_RTB_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_CLEAR_RTB_REQ primitive */ static int sl_clear_rtb_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; /* do not have a retransmission buffer */ return sl_rtb_cleared_ind(sl, q, mp); outstate: return lmi_error_ack(sl, q, mp, SL_CLEAR_RTB_REQ, LMI_OUTSTATE); } /** * sl_continue_req: - process SL_CONTINUE_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_CONTINUE_REQ primitive */ static int sl_continue_req(struct sl *sl, queue_t *q, mblk_t *mp) { struct sl *so = sl->other; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; if (!(sl_get_flags(sl) & SLF_LOC_PROC_OUT)) goto discard; sl_clr_flags(sl, SLF_LOC_PROC_OUT); if (sl_get_i_state(sl) == SLS_ALIGNED_NOT_READY) { sl_set_i_state(sl, SLS_IN_SERVICE); if (sl_get_i_state(so) == SLS_ALIGNED_READY) { sl_set_i_state(so, SLS_IN_SERVICE); return sl_in_service_ind(so, q, mp); } } return sl_remote_processor_recovered_ind(so, q, mp); discard: freemsg(mp); return (0); outstate: return lmi_error_ack(sl, q, mp, SL_CONTINUE_REQ, LMI_OUTSTATE); } /** * sl_local_processor_outage_req: - process SL_LOCAL_PROCESSOR_OUTAGE_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_LOCAL_PROCESSOR_OUTAGE_REQ primitive */ static int sl_local_processor_outage_req(struct sl *sl, queue_t *q, mblk_t *mp) { struct sl *so = sl->other; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; if ((sl_get_flags(sl) & SLF_LOC_PROC_OUT)) goto discard; sl_set_flags(sl, SLF_LOC_PROC_OUT); sl_set_flags(so, SLF_REM_PROC_OUT); return sl_remote_processor_outage_ind(so, q, mp); discard: freemsg(mp); return (0); outstate: return lmi_error_ack(sl, q, mp, SL_LOCAL_PROCESSOR_OUTAGE_REQ, LMI_OUTSTATE); } /** * sl_resume_req: - process SL_RESUME_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_RESUME_REQ primitive */ static int sl_resume_req(struct sl *sl, queue_t *q, mblk_t *mp) { struct sl *so = sl->other; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; if (!(sl_get_flags(sl) & SLF_LOC_PROC_OUT)) goto discard; sl_clr_flags(sl, SLF_LOC_PROC_OUT); if (sl_get_i_state(sl) == SLS_ALIGNED_NOT_READY) { sl_set_i_state(sl, SLS_IN_SERVICE); if (sl_get_i_state(so) == SLS_ALIGNED_READY) { sl_set_i_state(so, SLS_IN_SERVICE); return sl_in_service_ind(so, q, mp); } } return sl_remote_processor_recovered_ind(so, q, mp); discard: freemsg(mp); return (0); outstate: return lmi_error_ack(sl, q, mp, SL_RESUME_REQ, LMI_OUTSTATE); } /** * sl_congestion_discard_req: - process SL_CONGESTION_DISCARD_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_CONGESTION_DISCARD_REQ primitive */ static int sl_congestion_discard_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; sl_set_flags(sl, SLF_CONG_DISCARD); freemsg(mp); return (0); outstate: return lmi_error_ack(sl, q, mp, SL_CONGESTION_DISCARD_REQ, LMI_OUTSTATE); } /** * sl_congestion_accept_req: - process SL_CONGESTION_ACCEPT_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_CONGESTION_ACCEPT_REQ primitive */ static int sl_congestion_accept_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; sl_set_flags(sl, SLF_CONG_ACCEPT); freemsg(mp); return (0); outstate: return lmi_error_ack(sl, q, mp, SL_CONGESTION_ACCEPT_REQ, LMI_OUTSTATE); } /** * sl_no_congestion_req: - process SL_NO_CONGESTION_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_NO_CONGESTION_REQ primitive */ static int sl_no_congestion_req(struct sl *sl, queue_t *q, mblk_t *mp) { struct sl *so = sl->other; if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; sl_clr_flags(sl, (SLF_CONG_DISCARD | SLF_CONG_ACCEPT)); canenable(so->oq); qenable(so->oq); freemsg(mp); return (0); outstate: return lmi_error_ack(sl, q, mp, SL_NO_CONGESTION_REQ, LMI_OUTSTATE); } /** * sl_power_on_req: - process SL_POWER_ON_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_POWER_ON_REQ primitive */ static int sl_power_on_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; if (sl_get_i_state(sl) != SLS_POWER_OFF) goto outstate; sl_set_i_state(sl, SLS_OUT_OF_SERVICE); freemsg(mp); return (0); outstate: return lmi_error_ack(sl, q, mp, SL_POWER_ON_REQ, LMI_OUTSTATE); } /** * sl_optmgmt_req: - process SL_OPTMGMT_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_OPTMGMT_REQ primitive */ static int sl_optmgmt_req(struct sl *sl, queue_t *q, mblk_t *mp) { freemsg(mp); return (0); } /** * sl_notify_req: - process SL_NOTIFY_REQ primitive * @sl: input signalling link * @q: active queue * @mp: the SL_NOTIFY_REQ primitive */ static int sl_notify_req(struct sl *sl, queue_t *q, mblk_t *mp) { freemsg(mp); return (0); } /** * lmi_other_req: - process unrecognized primitive * @sl: input signalling link * @q: active queue * @mp: the unrecognized primitive */ static int lmi_other_req(struct sl *sl, queue_t *q, mblk_t *mp) { if (pcmsg(DB_TYPE(mp)) || bcanputnext(q, mp->b_band)) { putnext(q, mp); return (0); } return (-EBUSY); } /* * ========================================================================= * * TIMEOUTS * * ========================================================================= */ static int sl_t1_timeout(struct sl *sl, queue_t *q) { if (sl_get_l_state(sl) != LMI_ENABLED) goto outstate; if (sl_get_i_state(sl) != SLS_INITIAL_ALIGNMENT) goto outstate; sl_set_i_state(sl, SLS_OUT_OF_SERVICE); return sl_out_of_service_ind(sl, q, NULL, 0); outstate: return (0); } /* * ========================================================================= * * INPUT OUTPUT CONTROLS * * ========================================================================= */ /** * lmi_testoption: - test LMI options for validity * @s: (locked) private structure * @arg: options to test */ static int lmi_testoption(struct sl *s, struct lmi_option *arg) { int err = 0; /* FIXME: check options */ return (err); } /** * lmi_ioctl: - process LMI M_IOCTL message * @s: (locked) private structure * @q: active queue * @mp: the M_IOCTL message * @dp: data part * * This is step 1 of the LMI input-output control operation. Step 1 consists of a copyin operation * for SET operations and a copyout operation for GET operations. */ static int lmi_ioctl(struct sl *s, queue_t *q, mblk_t *mp) { struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; mblk_t *bp; int size = -1; int err = 0; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCTL(%s)", sl_iocname(ioc->ioc_cmd)); sl_save_total_state(s); switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(LMI_IOCGOPTIONS): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->option), false))) goto enobufs; bcopy(&s->option, bp->b_rptr, sizeof(s->option)); break; case _IOC_NR(LMI_IOCSOPTIONS): size = sizeof(s->option); break; default: err = EOPNOTSUPP; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) { if (size == -1) mi_copyout(q, mp); else mi_copyin(q, mp, NULL, size); } return (0); } /** * lmi_copyin: - process LMI M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is step number 2 for SET operations. This is the result of the implicit or explicit copyin * operation. We can now perform sets and commits. All SET operations also include a last copyout * step that copies out the information actually set. */ static int lmi_copyin(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; int err = 0; mblk_t *bp; if (!(bp = mi_copyout_alloc(q, mp, NULL, MBLKL(dp), false))) goto enobufs; bcopy(dp->b_rptr, bp->b_rptr, MBLKL(dp)); mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); sl_save_total_state(s); switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(LMI_IOCSOPTIONS): if ((err = lmi_testoption(s, (struct lmi_option *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->option, sizeof(s->option)); break; default: err = EPROTO; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) mi_copyout(q, mp); return (0); } /** * lmi_copyout: - process LMI M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is the final step which is a simple copy done operation. */ static int lmi_copyout(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); mi_copyout(q, mp); return (0); } /** * sdl_testconfig: - test SDL configuration for validity * @s: private structure * @arg: configuration to test */ static int sdl_testconfig(struct sl *s, struct sdl_config *arg) { int err = 0; if (arg->ifflags) err = EINVAL; if (arg->iftype != SDL_TYPE_NONE) err = EINVAL; if (arg->ifmode != SDL_MODE_NONE) err = EINVAL; if (arg->ifgmode != SDL_GMODE_NONE) err = EINVAL; if (arg->ifgtype != SDL_GMODE_NONE) err = EINVAL; if (arg->ifgcrc != SDL_GCRC_NONE) err = EINVAL; if (arg->ifclock != SDL_CLOCK_NONE) err = EINVAL; if (arg->ifcoding != SDL_CODING_NONE) err = EINVAL; if (arg->ifframing != SDL_FRAMING_NONE) err = EINVAL; if (arg->iftxlevel == 0) arg->iftxlevel = s->sdl.config.iftxlevel; else if (arg->iftxlevel <= 16) arg->iftxlevel--; else err = EINVAL; return (err); } #ifndef SDL_EVT_ALL #define SDL_EVT_ALL \ ( 0 \ | SDL_EVT_LOST_SYNC \ | SDL_EVT_SU_ERROR \ | SDL_EVT_TX_FAIL \ | SDL_EVT_RX_FAIL \ ) #endif /* SDL_EVT_ALL */ /** * sdl_setnotify: - set SDL notification bits * @s: private structure * @arg: notification arguments */ static int sdl_setnotify(struct sl *s, struct sdl_notify *arg) { if (arg->events & ~(SDL_EVT_ALL)) return (EINVAL); arg->events = arg->events | s->sdl.notify.events; return (0); } /** * sdl_clrnotify: - clear SDL notification bits * @s: private structure * @arg: notification arguments */ static int sdl_clrnotify(struct sl *s, struct sdl_notify *arg) { if (arg->events & ~(SDL_EVT_ALL)) return (EINVAL); arg->events = ~arg->events & s->sdl.notify.events; return (0); } /** * sdl_ioctl: - process SDL M_IOCTL message * @s: (locked) private structure * @q: active queue * @mp: the M_IOCTL message * @dp: data part * * This is step 1 of the SDL input-output control operation. Step 1 consists of a copyin operation * for SET operations and a copyout operation for GET operations. */ static int sdl_ioctl(struct sl *s, queue_t *q, mblk_t *mp) { struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; mblk_t *bp; int size = -1; int err = 0; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCTL(%s)", sl_iocname(ioc->ioc_cmd)); sl_save_total_state(s); switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SDL_IOCSCONFIG): size = sizeof(s->option); break; case _IOC_NR(SDL_IOCGCONFIG): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdl.config), false))) goto enobufs; bcopy(&s->sdl.config, bp->b_rptr, sizeof(s->sdl.config)); break; case _IOC_NR(SDL_IOCTCONFIG): size = sizeof(s->sdl.config); break; case _IOC_NR(SDL_IOCCCONFIG): size = sizeof(s->sdl.config); break; case _IOC_NR(SDL_IOCGSTATEM): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdl.statem), false))) goto enobufs; bcopy(&s->sdl.statem, bp->b_rptr, sizeof(s->sdl.statem)); break; case _IOC_NR(SDL_IOCCMRESET): /* FIXME reset the state machine. */ break; case _IOC_NR(SDL_IOCGSTATSP): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdl.statsp), false))) goto enobufs; bcopy(&s->sdl.statsp, bp->b_rptr, sizeof(s->sdl.statsp)); break; case _IOC_NR(SDL_IOCSSTATSP): size = sizeof(s->sdl.statsp); break; case _IOC_NR(SDL_IOCGSTATS): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdl.stats), false))) goto enobufs; bcopy(&s->sdl.stats, bp->b_rptr, sizeof(s->sdl.stats)); break; case _IOC_NR(SDL_IOCCSTATS): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdl.stats), false))) goto enobufs; bcopy(&s->sdl.stats, bp->b_rptr, sizeof(s->sdl.stats)); bzero(&s->sdl.stats, sizeof(s->sdl.stats)); break; case _IOC_NR(SDL_IOCGNOTIFY): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdl.notify), false))) goto enobufs; bcopy(&s->sdl.notify, bp->b_rptr, sizeof(s->sdl.notify)); break; case _IOC_NR(SDL_IOCSNOTIFY): size = sizeof(s->sdl.notify); break; case _IOC_NR(SDL_IOCCNOTIFY): size = sizeof(s->sdl.notify); break; default: err = EOPNOTSUPP; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) { if (size == -1) mi_copyout(q, mp); else mi_copyin(q, mp, NULL, size); } return (0); } /** * sdl_copyin: - process SDL M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is step number 2 for SET operations. This is the result of the implicit or explicit copyin * operation. We can now perform sets and commits. All SET operations also include a last copyout * step that copies out the information actually set. */ static int sdl_copyin(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; int err = 0; mblk_t *bp; if (!(bp = mi_copyout_alloc(q, mp, NULL, MBLKL(dp), false))) goto enobufs; bcopy(dp->b_rptr, bp->b_rptr, MBLKL(dp)); mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); sl_save_total_state(s); switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(SDL_IOCSCONFIG): if ((err = sdl_testconfig(s, (struct sdl_config *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdl.config, sizeof(s->sdl.config)); break; case _IOC_NR(SDL_IOCTCONFIG): err = sdl_testconfig(s, (struct sdl_config *) bp->b_rptr); break; case _IOC_NR(SDL_IOCCCONFIG): if ((err = sdl_testconfig(s, (struct sdl_config *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdl.config, sizeof(s->sdl.config)); break; case _IOC_NR(SDL_IOCSSTATSP): bcopy(bp->b_rptr, &s->sdl.statsp, sizeof(s->sdl.statsp)); break; case _IOC_NR(SDL_IOCSNOTIFY): if ((err = sdl_setnotify(s, (struct sdl_notify *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdl.notify, sizeof(s->sdl.notify)); break; case _IOC_NR(SDL_IOCCNOTIFY): if ((err = sdl_clrnotify(s, (struct sdl_notify *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdl.notify, sizeof(s->sdl.notify)); break; default: err = EPROTO; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) mi_copyout(q, mp); return (0); } /** * sdl_copyout: - process SDL M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is the final step which is a simple copy done operation. */ static int sdl_copyout(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); mi_copyout(q, mp); return (0); } #if 1 /** * sdt_testconfig: - test SDT configuration * @s: (locked) private structure * @arg: configuration argument */ static int sdt_testconfig(struct sl *s, struct sdt_config *arg) { int err = 0; /* FIXME: check configuration */ return (err); } #ifndef SDT_EVT_ALL #define SDT_EVT_ALL \ ( 0 \ | SDT_EVT_LOST_SYNC \ | SDT_EVT_SU_ERROR \ | SDT_EVT_TX_FAIL \ | SDT_EVT_RX_FAIL \ | SDT_EVT_CARRIER \ ) #endif /* SDT_EVT_ALL */ /** * sdt_setnotify: - set SDT notifications bits * @s: (locked) private structure * @arg: notification argument */ static int sdt_setnotify(struct sl *s, struct sdt_notify *arg) { if (arg->events & ~(SDT_EVT_ALL)) return (EINVAL); arg->events = arg->events | s->sdt.notify.events; return (0); } /** * sdt_clrnotify: - clear SDT notifications bits * @s: (locked) private structure * @arg: notification argument */ static int sdt_clrnotify(struct sl *s, struct sdt_notify *arg) { if (arg->events & ~(SDT_EVT_ALL)) return (EINVAL); arg->events = ~arg->events & s->sdt.notify.events; return (0); } /** * sdt_ioctl: - process SDT M_IOCTL message * @s: (locked) private structure * @q: active queue * @mp: the M_IOCTL message * * This is step 1 of the SDT input-output control operation. Step 1 consists * of a copyin operation for SET operations and a copyout operation for GET * operations. */ static int sdt_ioctl(struct sl *s, queue_t *q, mblk_t *mp) { struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; mblk_t *bp; int size = -1; int err = 0; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCTL(%s)", sl_iocname(ioc->ioc_cmd)); sl_save_total_state(s); switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SDT_IOCGCONFIG): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdt.config), false))) goto enobufs; bcopy(&s->sdt.config, bp->b_rptr, sizeof(s->sdt.config)); break; case _IOC_NR(SDT_IOCSCONFIG): size = sizeof(s->option); break; case _IOC_NR(SDT_IOCTCONFIG): size = sizeof(s->sdt.config); break; case _IOC_NR(SDT_IOCCCONFIG): size = sizeof(s->sdt.config); break; case _IOC_NR(SDT_IOCGSTATEM): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdt.statem), false))) goto enobufs; bcopy(&s->sdt.statem, bp->b_rptr, sizeof(s->sdt.statem)); break; case _IOC_NR(SDT_IOCCMRESET): /* FIXME reset the state machine. */ break; case _IOC_NR(SDT_IOCGSTATSP): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdt.statsp), false))) goto enobufs; bcopy(&s->sdt.statsp, bp->b_rptr, sizeof(s->sdt.statsp)); break; case _IOC_NR(SDT_IOCSSTATSP): size = sizeof(s->sdt.statsp); break; case _IOC_NR(SDT_IOCGSTATS): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdt.stats), false))) goto enobufs; bcopy(&s->sdt.stats, bp->b_rptr, sizeof(s->sdt.stats)); break; case _IOC_NR(SDT_IOCCSTATS): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdt.stats), false))) goto enobufs; bcopy(&s->sdt.stats, bp->b_rptr, sizeof(s->sdt.stats)); bzero(&s->sdt.stats, sizeof(s->sdt.stats)); break; case _IOC_NR(SDT_IOCGNOTIFY): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sdt.notify), false))) goto enobufs; bcopy(&s->sdt.notify, bp->b_rptr, sizeof(s->sdt.notify)); break; case _IOC_NR(SDT_IOCSNOTIFY): size = sizeof(s->sdt.notify); break; case _IOC_NR(SDT_IOCCNOTIFY): size = sizeof(s->sdt.notify); break; default: err = EOPNOTSUPP; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) { if (size == 0) mi_copy_done(q, mp, 0); else if (size == -1) mi_copyout(q, mp); else mi_copyin(q, mp, NULL, size); } return (0); } /** * sdt_copyin: - process SDT M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is step number 2 for SET operations. This is the result of the * implicit or explicit copyin operation. We can now perform sets and * commits. All SET operations also include a last copyout step that copies * out the information actually set. */ static int sdt_copyin(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; int err = 0; mblk_t *bp; if (!(bp = mi_copyout_alloc(q, mp, NULL, MBLKL(dp), false))) goto enobufs; bcopy(dp->b_rptr, bp->b_rptr, MBLKL(dp)); mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); sl_save_total_state(s); switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(SDT_IOCSCONFIG): if ((err = sdt_testconfig(s, (struct sdt_config *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdt.config, sizeof(s->sdt.config)); break; case _IOC_NR(SDT_IOCTCONFIG): err = sdt_testconfig(s, (struct sdt_config *) bp->b_rptr); break; case _IOC_NR(SDT_IOCCCONFIG): if ((err = sdt_testconfig(s, (struct sdt_config *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdt.config, sizeof(s->sdt.config)); break; case _IOC_NR(SDT_IOCSSTATSP): bcopy(bp->b_rptr, &s->sdt.statsp, sizeof(s->sdt.statsp)); break; case _IOC_NR(SDT_IOCSNOTIFY): if ((err = sdt_setnotify(s, (struct sdt_notify *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdt.notify, sizeof(s->sdt.notify)); break; case _IOC_NR(SDT_IOCCNOTIFY): if ((err = sdt_clrnotify(s, (struct sdt_notify *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sdt.notify, sizeof(s->sdt.notify)); break; default: err = EPROTO; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) mi_copyout(q, mp); return (0); } /** * sdt_copyout: - process SDT M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is the final step which is a simple copy done operation. */ static int sdt_copyout(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); mi_copyout(q, mp); return (0); } #endif #if 1 /** * sl_testconfig: - test SL configuration * @s: (locked) private structure * @arg: configuration argument */ static int sl_testconfig(struct sl *s, struct sl_config *arg) { int err = 0; /* FIXME: check configuration */ return (err); } #ifndef SL_EVT_ALL #define SL_EVT_ALL \ ( 0 \ | SL_EVT_FAIL_UNSPECIFIED \ | SL_EVT_FAIL_CONG_TIMEOUT \ | SL_EVT_FAIL_ACK_TIMEOUT \ | SL_EVT_FAIL_ABNORMAL_BSNR \ | SL_EVT_FAIL_ABNORMAL_FIBR \ | SL_EVT_FAIL_ABORMAL \ | SL_EVT_FAIL_SUERM_EIM \ | SL_EVT_FAIL_ALIGNMENT \ | SL_EVT_FAIL_RECEIVED_SIO \ | SL_EVT_FAIL_RECEIVED_SIN \ | SL_EVT_FAIL_RECEIVED_SIE \ | SL_EVT_FAIL_RECEIVED_SIOS \ | SL_EVT_FAIL_T1_TIMEOUT \ | SL_EVT_RPO_BEGIN \ | SL_EVT_RPO_END \ | SL_EVT_CONGEST_ONSET_IND \ | SL_EVT_CONGEST_DISCD_IND \ | SL_EVT_FAIL_ALL_REASONS \ ) #endif /* SL_EVT_ALL */ /** * sl_setnotify: - set SL notifications bits * @s: (locked) private structure * @arg: notification argument */ static int sl_setnotify(struct sl *s, struct sl_notify *arg) { if (arg->events & ~(SL_EVT_ALL)) return (EINVAL); arg->events = arg->events | s->sl.notify.events; return (0); } /** * sl_clrnotify: - clear SL notifications bits * @s: (locked) private structure * @arg: notification argument */ static int sl_clrnotify(struct sl *s, struct sl_notify *arg) { if (arg->events & ~(SL_EVT_ALL)) return (EINVAL); arg->events = ~arg->events & s->sl.notify.events; return (0); } /** * sl_ioctl: - process SL M_IOCTL message * @s: (locked) private structure * @q: active queue * @mp: the M_IOCTL message * * This is step 1 of the SL input-output control operation. Step 1 consists * of a copyin operation for SET operations and a copyout operation for GET * operations. */ static int sl_ioctl(struct sl *s, queue_t *q, mblk_t *mp) { struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; mblk_t *bp; int size = -1; int err = 0; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCTL(%s)", sl_iocname(ioc->ioc_cmd)); sl_save_total_state(s); switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SL_IOCGCONFIG): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sl.config), false))) goto enobufs; bcopy(&s->sl.config, bp->b_rptr, sizeof(s->sl.config)); break; case _IOC_NR(SL_IOCSCONFIG): size = sizeof(s->option); break; case _IOC_NR(SL_IOCTCONFIG): size = sizeof(s->sl.config); break; case _IOC_NR(SL_IOCCCONFIG): size = sizeof(s->sl.config); break; case _IOC_NR(SL_IOCGSTATEM): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sl.statem), false))) goto enobufs; bcopy(&s->sl.statem, bp->b_rptr, sizeof(s->sl.statem)); break; case _IOC_NR(SL_IOCCMRESET): /* FIXME reset the state machine. */ break; case _IOC_NR(SL_IOCGSTATSP): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sl.statsp), false))) goto enobufs; bcopy(&s->sl.statsp, bp->b_rptr, sizeof(s->sl.statsp)); break; case _IOC_NR(SL_IOCSSTATSP): size = sizeof(s->sl.statsp); break; case _IOC_NR(SL_IOCGSTATS): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sl.stats), false))) goto enobufs; bcopy(&s->sl.stats, bp->b_rptr, sizeof(s->sl.stats)); break; case _IOC_NR(SL_IOCCSTATS): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sl.stats), false))) goto enobufs; bcopy(&s->sl.stats, bp->b_rptr, sizeof(s->sl.stats)); bzero(&s->sl.stats, sizeof(s->sl.stats)); break; case _IOC_NR(SL_IOCGNOTIFY): if (!(bp = mi_copyout_alloc(q, mp, NULL, sizeof(s->sl.notify), false))) goto enobufs; bcopy(&s->sl.notify, bp->b_rptr, sizeof(s->sl.notify)); break; case _IOC_NR(SL_IOCSNOTIFY): size = sizeof(s->sl.notify); break; case _IOC_NR(SL_IOCCNOTIFY): size = sizeof(s->sl.notify); break; default: err = EOPNOTSUPP; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) { if (size == 0) mi_copy_done(q, mp, 0); else if (size == -1) mi_copyout(q, mp); else mi_copyin(q, mp, NULL, size); } return (0); } /** * sl_copyin: - process SL M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is step number 2 for SET operations. This is the result of the * implicit or explicit copyin operation. We can now perform sets and * commits. All SET operations also include a last copyout step that copies * out the information actually set. */ static int sl_copyin(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; int err = 0; mblk_t *bp; if (!(bp = mi_copyout_alloc(q, mp, NULL, MBLKL(dp), false))) goto enobufs; bcopy(dp->b_rptr, bp->b_rptr, MBLKL(dp)); mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); sl_save_total_state(s); switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(SL_IOCSCONFIG): if ((err = sl_testconfig(s, (struct sl_config *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sl.config, sizeof(s->sl.config)); break; case _IOC_NR(SL_IOCTCONFIG): err = sl_testconfig(s, (struct sl_config *) bp->b_rptr); break; case _IOC_NR(SL_IOCCCONFIG): if ((err = sl_testconfig(s, (struct sl_config *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sl.config, sizeof(s->sl.config)); break; case _IOC_NR(SL_IOCSSTATSP): bcopy(bp->b_rptr, &s->sl.statsp, sizeof(s->sl.statsp)); break; case _IOC_NR(SL_IOCSNOTIFY): if ((err = sl_setnotify(s, (struct sl_notify *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sl.notify, sizeof(s->sl.notify)); break; case _IOC_NR(SL_IOCCNOTIFY): if ((err = sl_clrnotify(s, (struct sl_notify *) bp->b_rptr)) == 0) bcopy(bp->b_rptr, &s->sl.notify, sizeof(s->sl.notify)); break; default: err = EPROTO; break; enobufs: err = ENOBUFS; break; } if (err < 0) { sl_restore_total_state(s); return (err); } if (err > 0) mi_copy_done(q, mp, err); if (err == 0) mi_copyout(q, mp); return (0); } /** * sl_copyout: - process SL M_IOCDATA message * @s: private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is the final step which is a simple copy done operation. */ static int sl_copyout(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; mi_strlog(s->oq, STRLOGIO, SL_TRACE, "-> M_IOCDATA(%s)", sl_iocname(cp->cp_cmd)); mi_copyout(q, mp); return (0); } #endif /** * sl_do_ioctl: - process M_IOCTL message * @ch: (locked) private structure * @q: active queue * @mp: the M_IOCTL message * * This is step 1 of the input-output control operation. Step 1 consists * of a copyin operation for SET operations and a copyout operation for GET * operations. */ static int sl_do_ioctl(struct sl *s, queue_t *q, mblk_t *mp) { struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; if (unlikely(!MBLKIN(mp, 0, sizeof(*ioc))) || unlikely(mp->b_cont == NULL)) { mi_copy_done(q, mp, EFAULT); return (0); } switch (_IOC_TYPE(ioc->ioc_cmd)) { case LMI_IOC_MAGIC: return lmi_ioctl(s, q, mp); case SDL_IOC_MAGIC: return sdl_ioctl(s, q, mp); #if 1 case SDT_IOC_MAGIC: return sdt_ioctl(s, q, mp); #endif #if 1 case SL_IOC_MAGIC: return sl_ioctl(s, q, mp); #endif default: if (bcanputnext(q, mp->b_band)) { putnext(q, mp); return (0); } return (-EBUSY); } } /** * sl_do_copyin: - process M_IOCDATA message * @s: (locked) private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is step number 2 for SET operations. This is the result of the * implicit or explicit copyin operation. We can now perform sets and * commits. All SET operations also include a last copyout step that copies * out the information actually set. */ static int sl_do_copyin(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; if (unlikely(!MBLKIN(mp, 0, sizeof(*cp))) || unlikely(mp->b_cont == NULL)) { mi_copy_done(q, mp, EFAULT); return (0); } switch (_IOC_TYPE(cp->cp_cmd)) { case LMI_IOC_MAGIC: return lmi_copyin(s, q, mp, dp); case SDL_IOC_MAGIC: return sdl_copyin(s, q, mp, dp); #if 1 case SDT_IOC_MAGIC: return sdt_copyin(s, q, mp, dp); #endif #if 1 case SL_IOC_MAGIC: return sl_copyin(s, q, mp, dp); #endif default: if (bcanputnext(q, mp->b_band)) { putnext(q, mp); return (0); } return (-EBUSY); } } /** * sl_do_copyout: - process M_IOCDATA message * @s: (locked) private structure * @q: active queue * @mp: the M_IOCDATA message * @dp: data part * * This is the final stop which is a simple copy done operation. */ static int sl_do_copyout(struct sl *s, queue_t *q, mblk_t *mp, mblk_t *dp) { struct copyresp *cp = (typeof(cp)) mp->b_rptr; if (unlikely(!MBLKIN(mp, 0, sizeof(*cp))) || unlikely(mp->b_cont == NULL)) { mi_copy_done(q, mp, EFAULT); return (0); } switch (_IOC_TYPE(cp->cp_cmd)) { case LMI_IOC_MAGIC: return lmi_copyout(s, q, mp, dp); case SDL_IOC_MAGIC: return sdl_copyout(s, q, mp, dp); #if 1 case SDT_IOC_MAGIC: return sdt_copyout(s, q, mp, dp); #endif #if 1 case SL_IOC_MAGIC: return sl_copyout(s, q, mp, dp); #endif default: if (bcanputnext(q, mp->b_band)) { putnext(q, mp); return (0); } return (-EBUSY); } } /* * ========================================================================= * * STREAMS MESSAGE HANDLING * * ========================================================================= */ /** * __sl_m_data: - process M_DATA message * @s: (locked) private structure * @q: active queue * @mp: the M_DATA message */ static fastcall int __sl_m_data(struct sl *s, queue_t *q, mblk_t *mp) { return sl_pdu_ind(s->other, q, mp, 0, mp->b_cont); } /** * sl_m_data: - process M_DATA message * @q: active queue * @mp: the M_DATA message */ static inline fastcall int sl_m_data(queue_t *q, mblk_t *mp) { caddr_t priv; int err = -EAGAIN; if (likely((priv = mi_trylock(q)) != NULL)) { err = __sl_m_data(SL_PRIV(q), q, mp); mi_unlock(priv); } return (err); } /** * sl_m_proto_slow: - process M_(PC)PROTO message * @s: private structure * @q: active queue * @mp: the M_(PC)PROTO message * @prim: the primitive */ static fastcall int sl_m_proto_slow(struct sl *s, queue_t *q, mblk_t *mp, lmi_ulong prim) { int rtn; switch (prim) { case SL_PDU_REQ: mi_strlog(s->oq, STRLOGDA, SL_TRACE, "-> %s", sl_primname(prim)); break; default: mi_strlog(s->oq, STRLOGRX, SL_TRACE, "-> %s", sl_primname(prim)); break; } sl_save_total_state(s); switch (prim) { case LMI_INFO_REQ: rtn = lmi_info_req(s, q, mp); break; case LMI_ATTACH_REQ: rtn = lmi_attach_req(s, q, mp); break; case LMI_DETACH_REQ: rtn = lmi_detach_req(s, q, mp); break; case LMI_ENABLE_REQ: rtn = lmi_enable_req(s, q, mp); break; case LMI_DISABLE_REQ: rtn = lmi_disable_req(s, q, mp); break; case LMI_OPTMGMT_REQ: rtn = lmi_optmgmt_req(s, q, mp); break; #if 0 case SDL_BITS_FOR_TRANSMISSION_REQ: rtn = sdl_bits_for_transmission_req(s, q, mp); break; case SDL_CONNECT_REQ: rtn = sdl_connect_req(s, q, mp); break; case SDL_DISCONNECT_REQ: rtn = sdl_disconnect_req(s, q, mp); break; #endif #if 0 case SDT_DAEDT_TRANSMISSION_REQ: rtn = sdt_daedt_transmission_req(s, q, mp); break; case SDT_DAEDT_START_REQ: rtn = sdt_daedt_start_req(s, q, mp); break; case SDT_DAEDR_START_REQ: rtn = sdt_daedr_start_req(s, q, mp); break; case SDT_AERM_START_REQ: rtn = sdt_aerm_start_req(s, q, mp); break; case SDT_AERM_STOP_REQ: rtn = sdt_aerm_stop_req(s, q, mp); break; case SDT_AERM_SET_TI_TO_TIN_REQ: rtn = sdt_aerm_set_ti_to_tin_req(s, q, mp); break; case SDT_AERM_SET_TI_TO_TIE_REQ: rtn = sdt_aerm_set_ti_to_tie_req(s, q, mp); break; case SDT_SUERM_START_REQ: rtn = sdt_suerm_start_req(s, q, mp); break; case SDT_SUERM_STOP_REQ: rtn = sdt_suerm_stop_req(s, q, mp); break; #endif #if 1 case SL_PDU_REQ: rtn = sl_pdu_req(s, q, mp); break; case SL_EMERGENCY_REQ: rtn = sl_emergency_req(s, q, mp); break; case SL_EMERGENCY_CEASES_REQ: rtn = sl_emergency_ceases_req(s, q, mp); break; case SL_START_REQ: rtn = sl_start_req(s, q, mp); break; case SL_STOP_REQ: rtn = sl_stop_req(s, q, mp); break; case SL_RETRIEVE_BSNT_REQ: rtn = sl_retrieve_bsnt_req(s, q, mp); break; case SL_RETRIEVAL_REQUEST_AND_FSNC_REQ: rtn = sl_retrieval_request_and_fsnc_req(s, q, mp); break; case SL_CLEAR_BUFFERS_REQ: rtn = sl_clear_buffers_req(s, q, mp); break; case SL_CLEAR_RTB_REQ: rtn = sl_clear_rtb_req(s, q, mp); break; case SL_CONTINUE_REQ: rtn = sl_continue_req(s, q, mp); break; case SL_LOCAL_PROCESSOR_OUTAGE_REQ: rtn = sl_local_processor_outage_req(s, q, mp); break; case SL_RESUME_REQ: rtn = sl_resume_req(s, q, mp); break; case SL_CONGESTION_DISCARD_REQ: rtn = sl_congestion_discard_req(s, q, mp); break; case SL_CONGESTION_ACCEPT_REQ: rtn = sl_congestion_accept_req(s, q, mp); break; case SL_NO_CONGESTION_REQ: rtn = sl_no_congestion_req(s, q, mp); break; case SL_POWER_ON_REQ: rtn = sl_power_on_req(s, q, mp); break; case SL_OPTMGMT_REQ: rtn = sl_optmgmt_req(s, q, mp); break; case SL_NOTIFY_REQ: rtn = sl_notify_req(s, q, mp); break; #endif default: rtn = lmi_other_req(s, q, mp); break; } if (rtn) sl_restore_total_state(s); return (rtn); } /** * __sl_m_proto: - process M_(PC)PROTO message * @s: locked private structure * @q: active queue * @mp: the M_(PC)PROTO message */ static inline fastcall int __sl_m_proto(struct sl *s, queue_t *q, mblk_t *mp) { t_uscalar_t prim; int rtn; if (likely(MBLKIN(mp, 0, sizeof(prim)))) { sl_ulong prim = *(typeof(prim) *) mp->b_rptr; if (likely(prim == SL_PDU_REQ)) { #ifndef _OPTIMIZE_SPEED mi_strlog(s->oq, STRLOGDA, SL_TRACE, "-> SL_PDU_REQ"); #endif /* _OPTIMIZE_SPEED */ rtn = sl_pdu_req(s, q, mp); } else { rtn = sl_m_proto_slow(s, q, mp, prim); } } else { freemsg(mp); rtn = 0; } return (rtn); } /** * sl_m_proto: = process M_(PC)PROTO message * @q: active queue * @mp: the M_(PC)PROTO message */ static inline fastcall int sl_m_proto(queue_t *q, mblk_t *mp) { caddr_t priv; int err = -EAGAIN; if (likely((priv = mi_trylock(q)) != NULL)) { err = __sl_m_proto(SL_PRIV(q), q, mp); mi_unlock(priv); } return (err); } /** * __sl_m_sig: process M_(PC)SIG message * @s: (locked) private structure * @q: active queue * @mp: the M_(PC)PROTO message * * This is the method for processing tick timers. Under the tick approach * each time that the tick timer fires we reset the timer. Then we prepare as * many blocks as will fit in the interval and send them to the other side. */ static inline fastcall int __sl_m_sig(struct sl *s, queue_t *q, mblk_t *mp) { int rtn = 0; if (!mi_timer_valid(mp)) return (0); sl_save_total_state(s); switch (*(int *) mp->b_rptr) { case 1: mi_strlog(s->oq, STRLOGTO, SL_TRACE, "-> T1 TIMEOUT <-"); rtn = sl_t1_timeout(s, q); break; default: mi_strlog(s->oq, STRLOGTO, SL_TRACE, "-> ?? TIMEOUT <-"); rtn = 0; break; } if (rtn != 0) { sl_restore_total_state(s); rtn = mi_timer_requeue(mp) ? rtn : 0; } return (rtn); } /** * sl_m_sig: process M_(PC)SIG message * @q: active queue * @mp: the M_(PC)PROTO message */ static inline fastcall int sl_m_sig(queue_t *q, mblk_t *mp) { caddr_t priv; int err = -EAGAIN; if (likely((priv = mi_trylock(q)) != NULL)) { err = __sl_m_sig(SL_PRIV(q), q, mp); mi_unlock(priv); } return (err); } /** * sl_m_flush: - process M_FLUSH message * @q: active queue * @mp: the M_FLUSH message * * Avoid having to push pipemod. If we are the bottommost module over a pipe * twist then perform the actions of pipemod. This means that the sl-pmod * module must be pushed over the same side of a pipe as pipemod, if pipemod * is pushed at all. */ static fastcall int sl_m_flush(queue_t *q, mblk_t *mp) { if (mp->b_rptr[0] & FLUSHW) { if (mp->b_rptr[0] & FLUSHBAND) flushband(q, mp->b_rptr[1], FLUSHDATA); else flushq(q, FLUSHDATA); } /* pipemod style flush bit reversal */ if (!SAMESTR(q)) { switch (mp->b_rptr[0] & FLUSHRW) { case FLUSHW: mp->b_rptr[0] &= ~FLUSHW; mp->b_rptr[0] |= FLUSHR; break; case FLUSHR: mp->b_rptr[0] &= ~FLUSHR; mp->b_rptr[0] |= FLUSHW; break; } } putnext(q, mp); return (0); } static fastcall int __sl_m_ioctl(struct sl *s, queue_t *q, mblk_t *mp) { int err; err = sl_do_ioctl(s, q, mp); if (err <= 0) return (err); mi_copy_done(q, mp, err); return (0); } /** * sl_m_ioctl: - process M_IOCTL message * @q: active queue * @mp: the M_IOCTL message */ static fastcall int sl_m_ioctl(queue_t *q, mblk_t *mp) { caddr_t priv; int err = -EAGAIN; if ((priv = mi_trylock(q)) != NULL) { err = __sl_m_ioctl(SL_PRIV(q), q, mp); mi_unlock(priv); } return (err); } static fastcall int __sl_m_iocdata(struct sl *s, queue_t *q, mblk_t *mp) { mblk_t *dp; int err; switch (mi_copy_state(q, mp, &dp)) { case -1: err = 0; break; case MI_COPY_CASE(MI_COPY_IN, 1): err = sl_do_copyin(s, q, mp, dp); break; case MI_COPY_CASE(MI_COPY_OUT, 1): err = sl_do_copyout(s, q, mp, dp); break; default: err = EPROTO; break; } if (err <= 0) return (err); mi_copy_done(q, mp, err); return (0); } /** * sl_m_iocdata: - process M_IOCDATA message * @q: active queue * @mp: the M_IOCDATA message */ static fastcall int sl_m_iocdata(queue_t *q, mblk_t *mp) { caddr_t priv; int err = -EAGAIN; if ((priv = mi_trylock(q)) != NULL) { err = __sl_m_iocdata(SL_PRIV(q), q, mp); mi_unlock(priv); } return (err); } /** * sl_m_rse: - process M_(PC)RSE message * @q: active queue * @mp: the M_(PC)RSE message */ static fastcall int sl_m_rse(queue_t *q, mblk_t *mp) { freemsg(mp); return (0); } /** * sl_m_other: - process other message * @q: active queue * @mp: other STREAMS message * * Simply pass unrecognized messages along. */ static fastcall int sl_m_other(queue_t *q, mblk_t *mp) { if (pcmsg(DB_TYPE(mp)) || bcanputnext(q, mp->b_band)) { putnext(q, mp); return (0); } return (-EBUSY); } /** * sl_msg_slow: - process STREAMS message, slow * @q: active queue * @mp: the STREAMS message * * This is the slow version of the STREAMS message handling. It is expected * that data is delivered in M_DATA message blocks instead of SL_PDU_IND or * SL_PDU_REQ message blocks. Nevertheless, if this slower function gets * called, it is more likely because we have an M_PROTO message block * containing an SL_PDU_REQ. */ static noinline fastcall int sl_msg_slow(queue_t *q, mblk_t *mp) { switch (__builtin_expect(DB_TYPE(mp), M_PROTO)) { case M_PROTO: case M_PCPROTO: return sl_m_proto(q, mp); #if 1 case M_SIG: case M_PCSIG: return sl_m_sig(q, mp); #endif case M_IOCTL: return sl_m_ioctl(q, mp); case M_IOCDATA: return sl_m_iocdata(q, mp); case M_FLUSH: return sl_m_flush(q, mp); case M_RSE: case M_PCRSE: return sl_m_rse(q, mp); default: return sl_m_other(q, mp); case M_DATA: return sl_m_data(q, mp); } } /** * sl_msg: - process STREAMS message * @q: active queue * @mp: the message * * This function returns zero when the message has been absorbed. When it returns non-zero, the * message is to be placed (back) on the queue. */ static inline fastcall int sl_msg(queue_t *q, mblk_t *mp) { if (likely(DB_TYPE(mp) == M_DATA)) return sl_m_data(q, mp); if (likely(DB_TYPE(mp) == M_PROTO)) return sl_m_proto(q, mp); return sl_msg_slow(q, mp); } /** * __sl_msg_slow: - process STREAMS message, slow * @s: locked private structure * @q: active queue * @mp: the STREAMS message */ static noinline fastcall int __sl_msg_slow(struct sl *s, queue_t *q, mblk_t *mp) { switch (__builtin_expect(DB_TYPE(mp), M_PROTO)) { case M_PROTO: case M_PCPROTO: return __sl_m_proto(s, q, mp); case M_SIG: case M_PCSIG: return __sl_m_sig(s, q, mp); case M_IOCTL: return __sl_m_ioctl(s, q, mp); case M_IOCDATA: return __sl_m_iocdata(s, q, mp); case M_FLUSH: return sl_m_flush(q, mp); case M_RSE: case M_PCRSE: return sl_m_rse(q, mp); default: return sl_m_other(q, mp); case M_DATA: return __sl_m_data(s, q, mp); } } /** * __sl_msg: - process STREAMS message locked * @s: locked private structure * @q: active queue * @mp: the message * * This function returns zero when the message has been absorbed. When it returns non-zero, the * message is to be placed (back) on the queue. */ static inline fastcall int __sl_msg(struct sl *s, queue_t *q, mblk_t *mp) { if (likely(DB_TYPE(mp) == M_DATA)) return __sl_m_data(s, q, mp); if (likely(DB_TYPE(mp) == M_PROTO)) return __sl_m_proto(s, q, mp); return __sl_msg_slow(s, q, mp); } /* * ========================================================================= * * STREAMS QUEUE PUT AND SERVICE PROCEDURES * * ========================================================================= */ /** * sl_putp: - put procedure * @q: active queue * @mp: message to put * * Quick canonical put procedure. */ static streamscall __hot_in int sl_putp(queue_t *q, mblk_t *mp) { if ((!pcmsg(DB_TYPE(mp)) && (q->q_first || (q->q_flag & QSVCBUSY))) || sl_msg(q, mp)) putq(q, mp); return (0); } /** * sl_srvp: - service procedure * @q: queue to service * * Quick canonical service procedure. This is a little quicker for * processing bulked messages because it takes the lock once for the entire * group of M_DATA messages, instead of once for each message. */ static streamscall __hot_read int sl_srvp(queue_t *q) { mblk_t *mp; if (likely((mp = getq(q)) != NULL)) { caddr_t priv; if (likely((priv = mi_trylock(q)) != NULL)) { do { if (unlikely(__sl_msg(SL_PRIV(q), q, mp) != 0)) break; } while (likely((mp = getq(q)) != NULL)); mi_unlock(priv); } if (unlikely(mp != NULL)) putbq(q, mp); } return (0); } /* * ========================================================================= * * STREAMS OPEN AND CLOSE ROUTINES * * ========================================================================= */ static caddr_t sl_opens = NULL; /** * sl_qopen: - STREAMS module queue open routine * @q: read queue of freshly allocated queue pair * @devp: device number of driver * @oflags: flags to open(2s) call * @sflag: STREAMS flag * @crp: credentials of closing process */ static streamscall int sl_qopen(queue_t *q, dev_t *devp, int oflags, int sflag, cred_t *crp) { struct sl_pair *p; mblk_t *loc_tp, *rem_tp; int err; if (q->q_ptr) return (0); if (!(loc_tp = mi_timer_alloc(sizeof(int)))) return (ENOBUFS); *(int *) loc_tp->b_rptr = 1; if (!(rem_tp = mi_timer_alloc(sizeof(int)))) { mi_timer_free(loc_tp); return (ENOBUFS); } *(int *) rem_tp->b_rptr = 1; if ((err = mi_open_comm(&sl_opens, sizeof(*p), q, devp, oflags, sflag, crp))) { mi_timer_free(loc_tp); mi_timer_free(rem_tp); return (err); } p = PRIV(q); bzero(p, sizeof(*p)); /* initialize the structure */ p->r_priv.pair = p; p->r_priv.other = &p->w_priv; p->r_priv.oq = WR(q); p->r_priv.max_sdu = 272; p->r_priv.min_sdu = 3; p->r_priv.header_len = 0; p->r_priv.ppa_style = LMI_STYLE1; p->r_priv.state.l_state = LMI_DISABLED; p->r_priv.oldstate.l_state = LMI_DISABLED; p->r_priv.state.i_state = SLS_POWER_OFF; p->r_priv.oldstate.i_state = SLS_POWER_OFF; p->r_priv.state.i_flags = 0; p->r_priv.oldstate.i_flags = 0; p->r_priv.t1 = loc_tp; bufq_init(&p->r_priv.tb); bufq_init(&p->r_priv.rb); p->r_priv.option.pvar = SS7_PVAR_ITUT_00; p->r_priv.option.popt = 0; p->r_priv.sdt.notify.events = 0; p->r_priv.sdt.config.t8 = 100; p->r_priv.sdt.config.Tin = 4; p->r_priv.sdt.config.Tie = 1; p->r_priv.sdt.config.T = 64; p->r_priv.sdt.config.D = 256; p->r_priv.sdt.config.Te = 793544; /* E1 */ p->r_priv.sdt.config.De = 11328000; /* E1 */ p->r_priv.sdt.config.Ue = 198384000; /* E1 */ p->r_priv.sdt.config.N = 16; p->r_priv.sdt.config.m = 272; p->r_priv.sdt.config.b = 8; p->r_priv.sdt.config.f = SDT_FLAGS_ONE; p->r_priv.sdt.statem.aerm_state = SDT_STATE_IDLE; p->r_priv.sdt.statem.aborted_proving = false; p->r_priv.sdt.statem.Ca = 0; p->r_priv.sdt.statem.Ti = 0; p->r_priv.sdt.statem.suerm_state = SDT_STATE_IDLE; p->r_priv.sdt.statem.Cs = 0; p->r_priv.sdt.statem.Ns = 0; p->r_priv.sdt.statem.eim_state = SDT_STATE_IDLE; p->r_priv.sdt.statem.Ce = 0; p->r_priv.sdt.statem.su_received = false; p->r_priv.sdt.statem.interval_error = false; p->r_priv.sdt.statem.daedt_state = SDT_STATE_IDLE; p->r_priv.sdt.statem.daedr_state = SDT_STATE_IDLE; p->r_priv.sdt.statem.octet_counting_mode = false; p->r_priv.sdt.stats.tx_bytes = 0; p->r_priv.sdt.stats.tx_sus = 0; p->r_priv.sdt.stats.tx_sus_repeated = 0; p->r_priv.sdt.stats.tx_underruns = 0; p->r_priv.sdt.stats.tx_aborts = 0; p->r_priv.sdt.stats.tx_buffer_overflows = 0; p->r_priv.sdt.stats.tx_sus_in_error = 0; p->r_priv.sdt.stats.rx_bytes = 0; p->r_priv.sdt.stats.rx_sus = 0; p->r_priv.sdt.stats.rx_sus_compressed = 0; p->r_priv.sdt.stats.rx_overruns = 0; p->r_priv.sdt.stats.rx_aborts = 0; p->r_priv.sdt.stats.rx_buffer_overflows = 0; p->r_priv.sdt.stats.rx_sus_in_error = 0; p->r_priv.sdt.stats.rx_sync_transitions = 0; p->r_priv.sdt.stats.rx_crc_errors = 0; p->r_priv.sdt.stats.rx_frame_errors = 0; p->r_priv.sdt.stats.rx_frame_overflows = 0; p->r_priv.sdt.stats.rx_frame_too_long = 0; p->r_priv.sdt.stats.rx_frame_too_short = 0; p->r_priv.sdt.stats.rx_residue_errors = 0; p->r_priv.sdt.stats.rx_length_error = 0; p->r_priv.sdt.stats.carrier_cts_lost = 0; p->r_priv.sdt.stats.carrier_dcd_lost = 0; p->r_priv.sdt.stats.carrier_lost = 0; p->r_priv.sdl.notify.events = 0; p->r_priv.sdl.config.ifname = NULL; p->r_priv.sdl.config.iftype = SDL_TYPE_PACKET; p->r_priv.sdl.config.ifrate = SDL_RATE_NONE; p->r_priv.sdl.config.ifgtype = SDL_GTYPE_NONE; p->r_priv.sdl.config.ifgrate = SDL_GRATE_NONE; p->r_priv.sdl.config.ifmode = SDL_MODE_PEER; p->r_priv.sdl.config.ifgmode = SDL_GMODE_NONE; p->r_priv.sdl.config.ifgcrc = SDL_GCRC_NONE; p->r_priv.sdl.config.ifclock = SDL_CLOCK_NONE; p->r_priv.sdl.config.ifcoding = SDL_CODING_NONE; p->r_priv.sdl.config.ifframing = SDL_FRAMING_NONE; p->r_priv.sdl.config.ifblksize = 8; p->r_priv.sdl.config.ifleads = 0; p->r_priv.sdl.config.ifbpv = 0; p->r_priv.sdl.config.ifalarms = 0; p->r_priv.sdl.config.ifrxlevel = 0; p->r_priv.sdl.config.iftxlevel = 1; p->r_priv.sdl.config.ifsync = 0; // p->r_priv.sdl.config.ifsyncsrc = { 0, 0, 0, 0}; p->r_priv.sdl.statem.tx_state = SDL_STATE_IDLE; p->r_priv.sdl.statem.rx_state = SDL_STATE_IDLE; p->r_priv.sdl.stats.rx_octets = 0; p->r_priv.sdl.stats.tx_octets = 0; p->r_priv.sdl.stats.rx_overruns = 0; p->r_priv.sdl.stats.tx_underruns = 0; p->r_priv.sdl.stats.rx_buffer_overflows = 0; p->r_priv.sdl.stats.tx_buffer_overflows = 0; p->r_priv.sdl.stats.lead_cts_lost = 0; p->r_priv.sdl.stats.lead_dcd_lost = 0; p->r_priv.sdl.stats.carrier_lost = 0; p->w_priv.pair = p; p->w_priv.other = &p->r_priv; p->w_priv.oq = q; p->w_priv.max_sdu = 272; p->w_priv.min_sdu = 3; p->w_priv.header_len = 0; p->w_priv.ppa_style = LMI_STYLE1; p->w_priv.state.l_state = LMI_DISABLED; p->w_priv.oldstate.l_state = LMI_DISABLED; p->w_priv.state.i_state = SLS_POWER_OFF; p->w_priv.oldstate.i_state = SLS_POWER_OFF; p->w_priv.state.i_flags = 0; p->w_priv.oldstate.i_flags = 0; p->w_priv.t1 = rem_tp; bufq_init(&p->w_priv.tb); bufq_init(&p->w_priv.rb); p->w_priv.option.pvar = SS7_PVAR_ITUT_00; p->w_priv.option.popt = 0; p->w_priv.sdt.notify.events = 0; p->w_priv.sdt.config.t8 = 100; p->w_priv.sdt.config.Tin = 4; p->w_priv.sdt.config.Tie = 1; p->w_priv.sdt.config.T = 64; p->w_priv.sdt.config.D = 256; p->w_priv.sdt.config.Te = 793544; /* E1 */ p->w_priv.sdt.config.De = 11328000; /* E1 */ p->w_priv.sdt.config.Ue = 198384000; /* E1 */ p->w_priv.sdt.config.N = 16; p->w_priv.sdt.config.m = 272; p->w_priv.sdt.config.b = 8; p->w_priv.sdt.config.f = SDT_FLAGS_ONE; p->w_priv.sdt.statem.aerm_state = SDT_STATE_IDLE; p->w_priv.sdt.statem.aborted_proving = false; p->w_priv.sdt.statem.Ca = 0; p->w_priv.sdt.statem.Ti = 0; p->w_priv.sdt.statem.suerm_state = SDT_STATE_IDLE; p->w_priv.sdt.statem.Cs = 0; p->w_priv.sdt.statem.Ns = 0; p->w_priv.sdt.statem.eim_state = SDT_STATE_IDLE; p->w_priv.sdt.statem.Ce = 0; p->w_priv.sdt.statem.su_received = false; p->w_priv.sdt.statem.interval_error = false; p->w_priv.sdt.statem.daedt_state = SDT_STATE_IDLE; p->w_priv.sdt.statem.daedr_state = SDT_STATE_IDLE; p->w_priv.sdt.statem.octet_counting_mode = false; p->w_priv.sdt.stats.tx_bytes = 0; p->w_priv.sdt.stats.tx_sus = 0; p->w_priv.sdt.stats.tx_sus_repeated = 0; p->w_priv.sdt.stats.tx_underruns = 0; p->w_priv.sdt.stats.tx_aborts = 0; p->w_priv.sdt.stats.tx_buffer_overflows = 0; p->w_priv.sdt.stats.tx_sus_in_error = 0; p->w_priv.sdt.stats.rx_bytes = 0; p->w_priv.sdt.stats.rx_sus = 0; p->w_priv.sdt.stats.rx_sus_compressed = 0; p->w_priv.sdt.stats.rx_overruns = 0; p->w_priv.sdt.stats.rx_aborts = 0; p->w_priv.sdt.stats.rx_buffer_overflows = 0; p->w_priv.sdt.stats.rx_sus_in_error = 0; p->w_priv.sdt.stats.rx_sync_transitions = 0; p->w_priv.sdt.stats.rx_crc_errors = 0; p->w_priv.sdt.stats.rx_frame_errors = 0; p->w_priv.sdt.stats.rx_frame_overflows = 0; p->w_priv.sdt.stats.rx_frame_too_long = 0; p->w_priv.sdt.stats.rx_frame_too_short = 0; p->w_priv.sdt.stats.rx_residue_errors = 0; p->w_priv.sdt.stats.rx_length_error = 0; p->w_priv.sdt.stats.carrier_cts_lost = 0; p->w_priv.sdt.stats.carrier_dcd_lost = 0; p->w_priv.sdt.stats.carrier_lost = 0; p->w_priv.sdl.notify.events = 0; p->w_priv.sdl.config.ifname = NULL; p->w_priv.sdl.config.iftype = SDL_TYPE_PACKET; p->w_priv.sdl.config.ifrate = SDL_RATE_NONE; p->w_priv.sdl.config.ifgtype = SDL_GTYPE_NONE; p->w_priv.sdl.config.ifgrate = SDL_GRATE_NONE; p->w_priv.sdl.config.ifmode = SDL_MODE_PEER; p->w_priv.sdl.config.ifgmode = SDL_GMODE_NONE; p->w_priv.sdl.config.ifgcrc = SDL_GCRC_NONE; p->w_priv.sdl.config.ifclock = SDL_CLOCK_NONE; p->w_priv.sdl.config.ifcoding = SDL_CODING_NONE; p->w_priv.sdl.config.ifframing = SDL_FRAMING_NONE; p->w_priv.sdl.config.ifblksize = 8; p->w_priv.sdl.config.ifleads = 0; p->w_priv.sdl.config.ifbpv = 0; p->w_priv.sdl.config.ifalarms = 0; p->w_priv.sdl.config.ifrxlevel = 0; p->w_priv.sdl.config.iftxlevel = 1; p->w_priv.sdl.config.ifsync = 0; // p->w_priv.sdl.config.ifsyncsrc = { 0, 0, 0, 0}; p->w_priv.sdl.statem.tx_state = SDL_STATE_IDLE; p->w_priv.sdl.statem.rx_state = SDL_STATE_IDLE; p->w_priv.sdl.stats.rx_octets = 0; p->w_priv.sdl.stats.tx_octets = 0; p->w_priv.sdl.stats.rx_overruns = 0; p->w_priv.sdl.stats.tx_underruns = 0; p->w_priv.sdl.stats.rx_buffer_overflows = 0; p->w_priv.sdl.stats.tx_buffer_overflows = 0; p->w_priv.sdl.stats.lead_cts_lost = 0; p->w_priv.sdl.stats.lead_dcd_lost = 0; p->w_priv.sdl.stats.carrier_lost = 0; qprocson(q); return (0); } /** * sl_qclose: - STREAMS module queue close routine * @q: read queue of closing queue pair * @oflags: flags to open(2s) call * @crp: credentials of closing process */ static streamscall int sl_qclose(queue_t *q, int oflags, cred_t *crp) { struct sl_pair *p = PRIV(q); qprocsoff(q); mi_timer_free(XCHG(&p->r_priv.t1, NULL)); mi_timer_free(XCHG(&p->w_priv.t1, NULL)); bufq_purge(&p->r_priv.tb); bufq_purge(&p->r_priv.rb); bufq_purge(&p->w_priv.tb); bufq_purge(&p->w_priv.rb); mi_close_comm(&sl_opens, q); return (0); } /* * ========================================================================= * * PRIVATE STRUCTURE ALLOCATION, DEALLOCATION AND CACHE * * ========================================================================= */ /* * ========================================================================= * * REGISTRATION AND INITIALIZATION * * ========================================================================= */ STATIC struct qinit sl_rinit = { .qi_putp = sl_putp, /* Read put (message from below) */ .qi_srvp = sl_srvp, /* Read queue service */ .qi_qopen = sl_qopen, /* Each open */ .qi_qclose = sl_qclose, /* Last close */ .qi_minfo = &sl_minfo, /* Information */ .qi_mstat = &sl_rstat, /* Statistics */ }; STATIC struct qinit sl_winit = { .qi_putp = sl_putp, /* Write put (message from above) */ .qi_srvp = sl_srvp, /* Write queue service */ .qi_minfo = &sl_minfo, /* Information */ .qi_mstat = &sl_wstat, /* Statistics */ }; STATIC struct streamtab slpmodinfo = { .st_rdinit = &sl_rinit, /* Upper read queue */ .st_wrinit = &sl_winit, /* Upper write queue */ }; #ifdef LINUX /* * ========================================================================= * * LINUX INITIALIZATION * * ========================================================================= */ unsigned short modid = MOD_ID; #ifndef module_param MODULE_PARM(modid, "h"); #else /* module_param */ module_param(modid, ushort, 0444); #endif /* module_param */ MODULE_PARM_DESC(modid, "Module ID for SLPMOD module. (0 for allocation.)"); STATIC struct fmodsw sl_fmod = { .f_name = MOD_NAME, .f_str = &slpmodinfo, .f_flag = D_MP, .f_kmod = THIS_MODULE, }; /** * slpmodinit: - initialize SL-PMOD */ MODULE_STATIC int __init slpmodinit(void) { int err; cmn_err(CE_NOTE, MOD_BANNER); if ((err = register_strmod(&sl_fmod)) < 0) { cmn_err(CE_WARN, "%s: could not register module %d, err = %d\n", MOD_NAME, (int) modid, err); return (err); } if (modid == 0) modid = err; return (0); } /** * slpmodterminate: - terminate SL-PMOD */ MODULE_STATIC void __exit slpmodterminate(void) { int err; if ((err = unregister_strmod(&sl_fmod)) < 0) { cmn_err(CE_WARN, "%s: could not unregister module, err = %d", MOD_NAME, err); return; } return; } module_init(slpmodinit); module_exit(slpmodterminate); #endif /* LINUX */
0x7678/openss7
src/modules/slpmod.c
C
agpl-3.0
107,602
//var socket = io.connect('http://localhost:8081'); //////////////////////////////////////////////////////////////Player design////////////////////////////////////////////////////////////// //$("#player_detect").css({ 'position': 'absolute','z-index': '10', 'background-color': 'green','height': '1.5%', 'width': '1%','left': '10','top':'10' }); //$("#player_div").css({ 'position': 'absolute','z-index': '0','overflow': 'hidden','opacity': '0.3', 'background-color': '','height': CviewY, 'width': CviewX }); //$(".detect").css({ 'position': 'absolute','opacity': '0.3', 'height': '25%', 'width': '25%' }); ///////////////////////////////////////////////////////////////////////Debug///////////////////////////////////////////////////////////////////// var interval = setInterval(function() { updateMovement(); var socket = io.connect('http://localhost:8081'); $("#container").css({ 'position': 'absolute','z-index':'-10', 'background-color': '','height': gameBGResCX, 'width': gameBGResCY,'left': '0%','top':'0%' }); $("#cenario").css({ 'opacity':'0.3','z-index':'3','position': 'absolute','background-image': 'url("'+floorbackimg+'")','background-size': '100% 100%','height': gameBGResCX, 'width': gameBGResCY,'box-sizing': 'border-box','border:': '2px solid red' }); ////////////////////////////////////////////////////////////////Minimap/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var player = $('#player_detect'); var camera = $('#player_div'); newPos = new Object(); newPos.left = -camera.offset().left; newPos.top = -camera.offset().top; newPos.left = -camera.offset().left; newPos.top = -camera.offset().top; $("#container").offset(newPos); function terminal() { // var socket = io.connect('http://localhost:8081'); var cene = $('#cene'); var playerdiv = $('#player_detect'); // var camera = $('#player_div'); var cene = $('#cene'); var x = cene.offset().left; var y = cene.offset().top; ///////////////////////position feedback///////////////////// //var cord = {x, y}; //socket.emit('CORD', cord, function (data) {}); // both X and X feedback //socket.emit('X', x, function (data) {}); // X feedback //socket.emit('Y', y, function (data) {}); // Y feedback }; terminal(); }, refreshScreen); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
necasjanz/Nelux-3d
interface/2dEnv.js
JavaScript
agpl-3.0
2,730
# pylint: disable=arguments-differ """ Models for the shopping cart and assorted purchase types """ from collections import namedtuple from datetime import datetime from datetime import timedelta from decimal import Decimal import json import analytics from io import BytesIO from django.db.models import Q, F import pytz import logging import smtplib import StringIO import csv from boto.exception import BotoServerError # this is a super-class of SESError and catches connection errors from django.dispatch import receiver from django.db import models from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.mail import send_mail from django.contrib.auth.models import User from django.utils.translation import ugettext as _, ugettext_lazy from django.db import transaction from django.db.models import Sum, Count from django.db.models.signals import post_save, post_delete from django.core.urlresolvers import reverse from model_utils.managers import InheritanceManager from model_utils.models import TimeStampedModel from django.core.mail.message import EmailMessage from xmodule.modulestore.django import modulestore from eventtracking import tracker from courseware.courses import get_course_by_id from config_models.models import ConfigurationModel from course_modes.models import CourseMode from edxmako.shortcuts import render_to_string from student.models import CourseEnrollment, UNENROLL_DONE, EnrollStatusChange from util.query import use_read_replica_if_available from openedx.core.djangoapps.xmodule_django.models import CourseKeyField from .exceptions import ( InvalidCartItem, PurchasedCallbackException, ItemAlreadyInCartException, AlreadyEnrolledInCourseException, CourseDoesNotExistException, MultipleCouponsNotAllowedException, InvalidStatusToRetire, UnexpectedOrderItemStatus, ItemNotFoundInCartException ) from shoppingcart.pdf import PDFInvoice from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers log = logging.getLogger("shoppingcart") ORDER_STATUSES = ( # The user is selecting what he/she wants to purchase. ('cart', 'cart'), # The user has been sent to the external payment processor. # At this point, the order should NOT be modified. # If the user returns to the payment flow, he/she will start a new order. ('paying', 'paying'), # The user has successfully purchased the items in the order. ('purchased', 'purchased'), # The user's order has been refunded. ('refunded', 'refunded'), # The user's order went through, but the order was erroneously left # in 'cart'. ('defunct-cart', 'defunct-cart'), # The user's order went through, but the order was erroneously left # in 'paying'. ('defunct-paying', 'defunct-paying'), ) # maps order statuses to their defunct states ORDER_STATUS_MAP = { 'cart': 'defunct-cart', 'paying': 'defunct-paying', } # we need a tuple to represent the primary key of various OrderItem subclasses OrderItemSubclassPK = namedtuple('OrderItemSubclassPK', ['cls', 'pk']) class OrderTypes(object): """ This class specify purchase OrderTypes. """ PERSONAL = 'personal' BUSINESS = 'business' ORDER_TYPES = ( (PERSONAL, 'personal'), (BUSINESS, 'business'), ) class Order(models.Model): """ This is the model for an order. Before purchase, an Order and its related OrderItems are used as the shopping cart. FOR ANY USER, THERE SHOULD ONLY EVER BE ZERO OR ONE ORDER WITH STATUS='cart'. """ class Meta(object): app_label = "shoppingcart" user = models.ForeignKey(User, db_index=True) currency = models.CharField(default="usd", max_length=8) # lower case ISO currency codes status = models.CharField(max_length=32, default='cart', choices=ORDER_STATUSES) purchase_time = models.DateTimeField(null=True, blank=True) refunded_time = models.DateTimeField(null=True, blank=True) # Now we store data needed to generate a reasonable receipt # These fields only make sense after the purchase bill_to_first = models.CharField(max_length=64, blank=True) bill_to_last = models.CharField(max_length=64, blank=True) bill_to_street1 = models.CharField(max_length=128, blank=True) bill_to_street2 = models.CharField(max_length=128, blank=True) bill_to_city = models.CharField(max_length=64, blank=True) bill_to_state = models.CharField(max_length=8, blank=True) bill_to_postalcode = models.CharField(max_length=16, blank=True) bill_to_country = models.CharField(max_length=64, blank=True) bill_to_ccnum = models.CharField(max_length=8, blank=True) # last 4 digits bill_to_cardtype = models.CharField(max_length=32, blank=True) # a JSON dump of the CC processor response, for completeness processor_reply_dump = models.TextField(blank=True) # bulk purchase registration code workflow billing details company_name = models.CharField(max_length=255, null=True, blank=True) company_contact_name = models.CharField(max_length=255, null=True, blank=True) company_contact_email = models.CharField(max_length=255, null=True, blank=True) recipient_name = models.CharField(max_length=255, null=True, blank=True) recipient_email = models.CharField(max_length=255, null=True, blank=True) customer_reference_number = models.CharField(max_length=63, null=True, blank=True) order_type = models.CharField(max_length=32, default='personal', choices=OrderTypes.ORDER_TYPES) @classmethod def get_cart_for_user(cls, user): """ Always use this to preserve the property that at most 1 order per user has status = 'cart' """ # find the newest element in the db try: cart_order = cls.objects.filter(user=user, status='cart').order_by('-id')[:1].get() except ObjectDoesNotExist: # if nothing exists in the database, create a new cart cart_order, _created = cls.objects.get_or_create(user=user, status='cart') return cart_order @classmethod def does_user_have_cart(cls, user): """ Returns a boolean whether a shopping cart (Order) exists for the specified user """ return cls.objects.filter(user=user, status='cart').exists() @classmethod def user_cart_has_items(cls, user, item_types=None): """ Returns true if the user (anonymous user ok) has a cart with items in it. (Which means it should be displayed. If a item_type is passed in, then we check to see if the cart has at least one of those types of OrderItems """ if not user.is_authenticated(): return False cart = cls.get_cart_for_user(user) if not item_types: # check to see if the cart has at least some item in it return cart.has_items() else: # if the caller is explicitly asking to check for particular types for item_type in item_types: if cart.has_items(item_type): return True return False @classmethod def remove_cart_item_from_order(cls, item, user): """ Removes the item from the cart if the item.order.status == 'cart'. Also removes any code redemption associated with the order_item """ if item.order.status == 'cart': log.info("order item %s removed for user %s", str(item.id), user) item.delete() # remove any redemption entry associated with the item CouponRedemption.remove_code_redemption_from_item(item, user) @property def total_cost(self): """ Return the total cost of the cart. If the order has been purchased, returns total of all purchased and not refunded items. """ return sum(i.line_cost for i in self.orderitem_set.filter(status=self.status)) def has_items(self, item_type=None): """ Does the cart have any items in it? If an item_type is passed in then we check to see if there are any items of that class type """ if not item_type: return self.orderitem_set.exists() else: items = self.orderitem_set.all().select_subclasses() for item in items: if isinstance(item, item_type): return True return False def reset_cart_items_prices(self): """ Reset the items price state in the user cart """ for item in self.orderitem_set.all(): if item.is_discounted: item.unit_cost = item.list_price item.save() def clear(self): """ Clear out all the items in the cart """ self.orderitem_set.all().delete() @transaction.atomic def start_purchase(self): """ Start the purchase process. This will set the order status to "paying", at which point it should no longer be modified. Future calls to `Order.get_cart_for_user()` will filter out orders with status "paying", effectively creating a new (empty) cart. """ if self.status == 'cart': self.status = 'paying' self.save() for item in OrderItem.objects.filter(order=self).select_subclasses(): item.start_purchase() def update_order_type(self): """ updating order type. This method wil inspect the quantity associated with the OrderItem. In the application, it is implied that when qty > 1, then the user is to purchase 'RegistrationCodes' which are randomly generated strings that users can distribute to others in order for them to enroll in paywalled courses. The UI/UX may change in the future to make the switching between PaidCourseRegistration and CourseRegCodeItems a more explicit UI gesture from the purchaser """ cart_items = self.orderitem_set.all() is_order_type_business = False for cart_item in cart_items: if cart_item.qty > 1: is_order_type_business = True items_to_delete = [] old_to_new_id_map = [] if is_order_type_business: for cart_item in cart_items: if hasattr(cart_item, 'paidcourseregistration'): course_reg_code_item = CourseRegCodeItem.add_to_order( self, cart_item.paidcourseregistration.course_id, cart_item.qty, ) # update the discounted prices if coupon redemption applied course_reg_code_item.list_price = cart_item.list_price course_reg_code_item.unit_cost = cart_item.unit_cost course_reg_code_item.save() items_to_delete.append(cart_item) old_to_new_id_map.append({"oldId": cart_item.id, "newId": course_reg_code_item.id}) else: for cart_item in cart_items: if hasattr(cart_item, 'courseregcodeitem'): paid_course_registration = PaidCourseRegistration.add_to_order( self, cart_item.courseregcodeitem.course_id, ) # update the discounted prices if coupon redemption applied paid_course_registration.list_price = cart_item.list_price paid_course_registration.unit_cost = cart_item.unit_cost paid_course_registration.save() items_to_delete.append(cart_item) old_to_new_id_map.append({"oldId": cart_item.id, "newId": paid_course_registration.id}) for item in items_to_delete: item.delete() self.order_type = OrderTypes.BUSINESS if is_order_type_business else OrderTypes.PERSONAL self.save() return old_to_new_id_map def generate_pdf_receipt(self, order_items): """ Generates the pdf receipt for the given order_items and returns the pdf_buffer. """ items_data = [] for item in order_items: item_total = item.qty * item.unit_cost items_data.append({ 'item_description': item.pdf_receipt_display_name, 'quantity': item.qty, 'list_price': item.get_list_price(), 'discount': item.get_list_price() - item.unit_cost, 'item_total': item_total }) pdf_buffer = BytesIO() PDFInvoice( items_data=items_data, item_id=str(self.id), date=self.purchase_time, is_invoice=False, total_cost=self.total_cost, payment_received=self.total_cost, balance=0 ).generate_pdf(pdf_buffer) return pdf_buffer def generate_registration_codes_csv(self, orderitems, site_name): """ this function generates the csv file """ course_names = [] csv_file = StringIO.StringIO() csv_writer = csv.writer(csv_file) csv_writer.writerow(['Course Name', 'Registration Code', 'URL']) for item in orderitems: course_id = item.course_id course = get_course_by_id(item.course_id, depth=0) registration_codes = CourseRegistrationCode.objects.filter(course_id=course_id, order=self) course_names.append(course.display_name) for registration_code in registration_codes: redemption_url = reverse('register_code_redemption', args=[registration_code.code]) url = '{base_url}{redemption_url}'.format(base_url=site_name, redemption_url=redemption_url) csv_writer.writerow([unicode(course.display_name).encode("utf-8"), registration_code.code, url]) return csv_file, course_names def send_confirmation_emails(self, orderitems, is_order_type_business, csv_file, pdf_file, site_name, course_names): """ send confirmation e-mail """ recipient_list = [(self.user.username, self.user.email, 'user')] # pylint: disable=no-member if self.company_contact_email: recipient_list.append((self.company_contact_name, self.company_contact_email, 'company_contact')) joined_course_names = "" if self.recipient_email: recipient_list.append((self.recipient_name, self.recipient_email, 'email_recipient')) joined_course_names = " " + ", ".join(course_names) if not is_order_type_business: subject = _("Order Payment Confirmation") else: subject = _('Confirmation and Registration Codes for the following courses: {course_name_list}').format( course_name_list=joined_course_names ) dashboard_url = '{base_url}{dashboard}'.format( base_url=site_name, dashboard=reverse('dashboard') ) try: from_address = configuration_helpers.get_value( 'email_from_address', settings.PAYMENT_CONFIRM_EMAIL ) # Send a unique email for each recipient. Don't put all email addresses in a single email. for recipient in recipient_list: # Some of the names in the db end in white space. recipient_name = self.user.profile.name.strip() message = render_to_string( 'emails/business_order_confirmation_email.txt' if is_order_type_business else 'emails/order_confirmation_email.txt', { 'order': self, 'recipient_name': recipient_name, 'recipient_type': recipient[2], 'site_name': site_name, 'order_items': orderitems, 'course_names': ", ".join(course_names), 'dashboard_url': dashboard_url, 'currency_symbol': settings.PAID_COURSE_REGISTRATION_CURRENCY[1], 'order_placed_by': '{username} ({email})'.format( username=self.user.username, email=self.user.email ), 'has_billing_info': settings.FEATURES['STORE_BILLING_INFO'], 'platform_name': configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME), 'payment_support_email': configuration_helpers.get_value( 'payment_support_email', settings.PAYMENT_SUPPORT_EMAIL, ), 'payment_email_signature': configuration_helpers.get_value('payment_email_signature'), 'payment_support_phone': configuration_helpers.get_value('payment_support_phone', settings.PAYMENT_SUPPORT_PHONE), 'payment_platform_name': configuration_helpers.get_value('payment_platform_name', settings.PAYMENT_PLATFORM_NAME), } ) email = EmailMessage( subject=subject, body=message, from_email=from_address, to=[recipient[1]] ) # Only the business order is HTML formatted. A single seat order confirmation is plain text. if is_order_type_business: email.content_subtype = "html" if csv_file: email.attach(u'RegistrationCodesRedemptionUrls.csv', csv_file.getvalue(), 'text/csv') if pdf_file is not None: email.attach(u'ReceiptOrder{}.pdf'.format(str(self.id)), pdf_file.getvalue(), 'application/pdf') else: file_buffer = StringIO.StringIO(_('pdf download unavailable right now, please contact support.')) email.attach(u'pdf_not_available.txt', file_buffer.getvalue(), 'text/plain') email.send() except (smtplib.SMTPException, BotoServerError): # sadly need to handle diff. mail backends individually log.error('Failed sending confirmation e-mail for order %d', self.id) def purchase(self, first='', last='', street1='', street2='', city='', state='', postalcode='', country='', ccnum='', cardtype='', processor_reply_dump=''): """ Call to mark this order as purchased. Iterates through its OrderItems and calls their purchased_callback `first` - first name of person billed (e.g. John) `last` - last name of person billed (e.g. Smith) `street1` - first line of a street address of the billing address (e.g. 11 Cambridge Center) `street2` - second line of a street address of the billing address (e.g. Suite 101) `city` - city of the billing address (e.g. Cambridge) `state` - code of the state, province, or territory of the billing address (e.g. MA) `postalcode` - postal code of the billing address (e.g. 02142) `country` - country code of the billing address (e.g. US) `ccnum` - last 4 digits of the credit card number of the credit card billed (e.g. 1111) `cardtype` - 3-digit code representing the card type used (e.g. 001) `processor_reply_dump` - all the parameters returned by the processor """ if self.status == 'purchased': log.error( u"`purchase` method called on order {}, but order is already purchased.".format(self.id) # pylint: disable=no-member ) return self.status = 'purchased' self.purchase_time = datetime.now(pytz.utc) self.bill_to_first = first self.bill_to_last = last self.bill_to_city = city self.bill_to_state = state self.bill_to_country = country self.bill_to_postalcode = postalcode if settings.FEATURES['STORE_BILLING_INFO']: self.bill_to_street1 = street1 self.bill_to_street2 = street2 self.bill_to_ccnum = ccnum self.bill_to_cardtype = cardtype self.processor_reply_dump = processor_reply_dump # save these changes on the order, then we can tell when we are in an # inconsistent state self.save() # this should return all of the objects with the correct types of the # subclasses orderitems = OrderItem.objects.filter(order=self).select_subclasses() site_name = configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME) if self.order_type == OrderTypes.BUSINESS: self.update_order_type() for item in orderitems: item.purchase_item() csv_file = None course_names = [] if self.order_type == OrderTypes.BUSINESS: # # Generate the CSV file that contains all of the RegistrationCodes that have already been # generated when the purchase has transacted # csv_file, course_names = self.generate_registration_codes_csv(orderitems, site_name) try: pdf_file = self.generate_pdf_receipt(orderitems) except Exception: # pylint: disable=broad-except log.exception('Exception at creating pdf file.') pdf_file = None try: self.send_confirmation_emails( orderitems, self.order_type == OrderTypes.BUSINESS, csv_file, pdf_file, site_name, course_names ) except Exception: # pylint: disable=broad-except # Catch all exceptions here, since the Django view implicitly # wraps this in a transaction. If the order completes successfully, # we don't want to roll back just because we couldn't send # the confirmation email. log.exception('Error occurred while sending payment confirmation email') self._emit_order_event('Completed Order', orderitems) def refund(self): """ Refund the given order. As of right now, this just marks the order as refunded. """ self.status = 'refunded' self.save() orderitems = OrderItem.objects.filter(order=self).select_subclasses() self._emit_order_event('Refunded Order', orderitems) def _emit_order_event(self, event_name, orderitems): """ Emit an analytics event with the given name for this Order. Will iterate over all associated OrderItems and add them as products in the event as well. """ try: if settings.LMS_SEGMENT_KEY: tracking_context = tracker.get_tracker().resolve_context() analytics.track(self.user.id, event_name, { 'orderId': self.id, 'total': str(self.total_cost), 'currency': self.currency, 'products': [item.analytics_data() for item in orderitems] }, context={ 'ip': tracking_context.get('ip'), 'Google Analytics': { 'clientId': tracking_context.get('client_id') } }) except Exception: # pylint: disable=broad-except # Capturing all exceptions thrown while tracking analytics events. We do not want # an operation to fail because of an analytics event, so we will capture these # errors in the logs. log.exception( u'Unable to emit {event} event for user {user} and order {order}'.format( event=event_name, user=self.user.id, order=self.id) ) def add_billing_details(self, company_name='', company_contact_name='', company_contact_email='', recipient_name='', recipient_email='', customer_reference_number=''): """ This function is called after the user selects a purchase type of "Business" and is asked to enter the optional billing details. The billing details are updated for that order. company_name - Name of purchasing organization company_contact_name - Name of the key contact at the company the sale was made to company_contact_email - Email of the key contact at the company the sale was made to recipient_name - Name of the company should the invoice be sent to recipient_email - Email of the company should the invoice be sent to customer_reference_number - purchase order number of the organization associated with this Order """ self.company_name = company_name self.company_contact_name = company_contact_name self.company_contact_email = company_contact_email self.recipient_name = recipient_name self.recipient_email = recipient_email self.customer_reference_number = customer_reference_number self.save() def generate_receipt_instructions(self): """ Call to generate specific instructions for each item in the order. This gets displayed on the receipt page, typically. Instructions are something like "visit your dashboard to see your new courses". This will return two things in a pair. The first will be a dict with keys=OrderItemSubclassPK corresponding to an OrderItem and values=a set of html instructions they generate. The second will be a set of de-duped html instructions """ instruction_set = set([]) # heh. not ia32 or alpha or sparc instruction_dict = {} order_items = OrderItem.objects.filter(order=self).select_subclasses() for item in order_items: item_pk_with_subclass, set_of_html = item.generate_receipt_instructions() instruction_dict[item_pk_with_subclass] = set_of_html instruction_set.update(set_of_html) return instruction_dict, instruction_set def retire(self): """ Method to "retire" orders that have gone through to the payment service but have (erroneously) not had their statuses updated. This method only works on orders that satisfy the following conditions: 1) the order status is either "cart" or "paying" (otherwise we raise an InvalidStatusToRetire error) 2) the order's order item's statuses match the order's status (otherwise we throw an UnexpectedOrderItemStatus error) """ # if an order is already retired, no-op: if self.status in ORDER_STATUS_MAP.values(): return if self.status not in ORDER_STATUS_MAP.keys(): raise InvalidStatusToRetire( "order status {order_status} is not 'paying' or 'cart'".format( order_status=self.status ) ) for item in self.orderitem_set.all(): if item.status != self.status: raise UnexpectedOrderItemStatus( "order_item status is different from order status" ) self.status = ORDER_STATUS_MAP[self.status] self.save() for item in self.orderitem_set.all(): item.retire() def find_item_by_course_id(self, course_id): """ course_id: Course id of the item to find Returns OrderItem from the Order given a course_id Raises exception ItemNotFoundException when the item having the given course_id is not present in the cart """ cart_items = OrderItem.objects.filter(order=self).select_subclasses() found_items = [] for item in cart_items: if getattr(item, 'course_id', None): if item.course_id == course_id: found_items.append(item) if not found_items: raise ItemNotFoundInCartException return found_items class OrderItem(TimeStampedModel): """ This is the basic interface for order items. Order items are line items that fill up the shopping carts and orders. Each implementation of OrderItem should provide its own purchased_callback as a method. """ class Meta(object): app_label = "shoppingcart" objects = InheritanceManager() order = models.ForeignKey(Order, db_index=True) # this is denormalized, but convenient for SQL queries for reports, etc. user should always be = order.user user = models.ForeignKey(User, db_index=True) # this is denormalized, but convenient for SQL queries for reports, etc. status should always be = order.status status = models.CharField(max_length=32, default='cart', choices=ORDER_STATUSES, db_index=True) qty = models.IntegerField(default=1) unit_cost = models.DecimalField(default=0.0, decimal_places=2, max_digits=30) list_price = models.DecimalField(decimal_places=2, max_digits=30, null=True) line_desc = models.CharField(default="Misc. Item", max_length=1024) currency = models.CharField(default="usd", max_length=8) # lower case ISO currency codes fulfilled_time = models.DateTimeField(null=True, db_index=True) refund_requested_time = models.DateTimeField(null=True, db_index=True) service_fee = models.DecimalField(default=0.0, decimal_places=2, max_digits=30) # general purpose field, not user-visible. Used for reporting report_comments = models.TextField(default="") @property def line_cost(self): """ Return the total cost of this OrderItem """ return self.qty * self.unit_cost @classmethod def add_to_order(cls, order, *args, **kwargs): """ A suggested convenience function for subclasses. NOTE: This does not add anything to the cart. That is left up to the subclasses to implement for themselves """ # this is a validation step to verify that the currency of the item we # are adding is the same as the currency of the order we are adding it # to currency = kwargs.get('currency', 'usd') if order.currency != currency and order.orderitem_set.exists(): raise InvalidCartItem(_("Trying to add a different currency into the cart")) @transaction.atomic def purchase_item(self): """ This is basically a wrapper around purchased_callback that handles modifying the OrderItem itself """ self.purchased_callback() self.status = 'purchased' self.fulfilled_time = datetime.now(pytz.utc) self.save() def start_purchase(self): """ Start the purchase process. This will set the order item status to "paying", at which point it should no longer be modified. """ self.status = 'paying' self.save() def purchased_callback(self): """ This is called on each inventory item in the shopping cart when the purchase goes through. """ raise NotImplementedError def generate_receipt_instructions(self): """ This is called on each item in a purchased order to generate receipt instructions. This should return a list of `ReceiptInstruction`s in HTML string Default implementation is to return an empty set """ return self.pk_with_subclass, set([]) @property def pk_with_subclass(self): """ Returns a named tuple that annotates the pk of this instance with its class, to fully represent a pk of a subclass (inclusive) of OrderItem """ return OrderItemSubclassPK(type(self), self.pk) @property def is_discounted(self): """ Returns True if the item a discount coupon has been applied to the OrderItem and False otherwise. Earlier, the OrderItems were stored with an empty list_price if a discount had not been applied. Now we consider the item to be non discounted if list_price is None or list_price == unit_cost. In these lines, an item is discounted if it's non-None and list_price and unit_cost mismatch. This should work with both new and old records. """ return self.list_price and self.list_price != self.unit_cost def get_list_price(self): """ Returns the unit_cost if no discount has been applied, or the list_price if it is defined. """ return self.list_price if self.list_price else self.unit_cost @property def single_item_receipt_template(self): """ The template that should be used when there's only one item in the order """ return 'shoppingcart/receipt.html' @property def single_item_receipt_context(self): """ Extra variables needed to render the template specified in `single_item_receipt_template` """ return {} def additional_instruction_text(self, **kwargs): # pylint: disable=unused-argument """ Individual instructions for this order item. Currently, only used for emails. """ return '' @property def pdf_receipt_display_name(self): """ How to display this item on a PDF printed receipt file. This can be overridden by the subclasses of OrderItem """ course_key = getattr(self, 'course_id', None) if course_key: course = get_course_by_id(course_key, depth=0) return course.display_name else: raise Exception( "Not Implemented. OrderItems that are not Course specific should have" " a overridden pdf_receipt_display_name property" ) def analytics_data(self): """Simple function used to construct analytics data for the OrderItem. The default implementation returns defaults for most attributes. When no name or category is specified by the implementation, the string 'N/A' is placed for the name and category. This should be handled appropriately by all implementations. Returns A dictionary containing analytics data for this OrderItem. """ return { 'id': self.id, 'sku': type(self).__name__, 'name': 'N/A', 'price': str(self.unit_cost), 'quantity': self.qty, 'category': 'N/A', } def retire(self): """ Called by the `retire` method defined in the `Order` class. Retires an order item if its (and its order's) status was erroneously not updated to "purchased" after the order was processed. """ self.status = ORDER_STATUS_MAP[self.status] self.save() class Invoice(TimeStampedModel): """ This table capture all the information needed to support "invoicing" which is when a user wants to purchase Registration Codes, but will not do so via a Credit Card transaction. """ class Meta(object): app_label = "shoppingcart" company_name = models.CharField(max_length=255, db_index=True) company_contact_name = models.CharField(max_length=255) company_contact_email = models.CharField(max_length=255) recipient_name = models.CharField(max_length=255) recipient_email = models.CharField(max_length=255) address_line_1 = models.CharField(max_length=255) address_line_2 = models.CharField(max_length=255, null=True, blank=True) address_line_3 = models.CharField(max_length=255, null=True, blank=True) city = models.CharField(max_length=255, null=True) state = models.CharField(max_length=255, null=True) zip = models.CharField(max_length=15, null=True) country = models.CharField(max_length=64, null=True) # This field has been deprecated. # The total amount can now be calculated as the sum # of each invoice item associated with the invoice. # For backwards compatibility, this field is maintained # and written to during invoice creation. total_amount = models.FloatField() # This field has been deprecated in order to support # invoices for items that are not course-related. # Although this field is still maintained for backwards # compatibility, you should use CourseRegistrationCodeInvoiceItem # to look up the course ID for purchased redeem codes. course_id = CourseKeyField(max_length=255, db_index=True) internal_reference = models.CharField( max_length=255, null=True, blank=True, help_text=ugettext_lazy("Internal reference code for this invoice.") ) customer_reference_number = models.CharField( max_length=63, null=True, blank=True, help_text=ugettext_lazy("Customer's reference code for this invoice.") ) is_valid = models.BooleanField(default=True) @classmethod def get_invoice_total_amount_for_course(cls, course_key): """ returns the invoice total amount generated by course. """ result = cls.objects.filter(course_id=course_key, is_valid=True).aggregate(total=Sum('total_amount')) total = result.get('total', 0) return total if total else 0 def generate_pdf_invoice(self, course, course_price, quantity, sale_price): """ Generates the pdf invoice for the given course and returns the pdf_buffer. """ discount_per_item = float(course_price) - sale_price / quantity list_price = course_price - discount_per_item items_data = [{ 'item_description': course.display_name, 'quantity': quantity, 'list_price': list_price, 'discount': discount_per_item, 'item_total': quantity * list_price }] pdf_buffer = BytesIO() PDFInvoice( items_data=items_data, item_id=str(self.id), date=datetime.now(pytz.utc), is_invoice=True, total_cost=float(self.total_amount), payment_received=0, balance=float(self.total_amount) ).generate_pdf(pdf_buffer) return pdf_buffer def snapshot(self): """Create a snapshot of the invoice. A snapshot is a JSON-serializable representation of the invoice's state, including its line items and associated transactions (payments/refunds). This is useful for saving the history of changes to the invoice. Returns: dict """ return { 'internal_reference': self.internal_reference, 'customer_reference': self.customer_reference_number, 'is_valid': self.is_valid, 'contact_info': { 'company_name': self.company_name, 'company_contact_name': self.company_contact_name, 'company_contact_email': self.company_contact_email, 'recipient_name': self.recipient_name, 'recipient_email': self.recipient_email, 'address_line_1': self.address_line_1, 'address_line_2': self.address_line_2, 'address_line_3': self.address_line_3, 'city': self.city, 'state': self.state, 'zip': self.zip, 'country': self.country, }, 'items': [ item.snapshot() for item in InvoiceItem.objects.filter(invoice=self).select_subclasses() ], 'transactions': [ trans.snapshot() for trans in InvoiceTransaction.objects.filter(invoice=self) ], } def __unicode__(self): label = ( unicode(self.internal_reference) if self.internal_reference else u"No label" ) created = ( self.created.strftime("%Y-%m-%d") if self.created else u"No date" ) return u"{label} ({date_created})".format( label=label, date_created=created ) INVOICE_TRANSACTION_STATUSES = ( # A payment/refund is in process, but money has not yet been transferred ('started', 'started'), # A payment/refund has completed successfully # This should be set ONLY once money has been successfully exchanged. ('completed', 'completed'), # A payment/refund was promised, but was cancelled before # money had been transferred. An example would be # cancelling a refund check before the recipient has # a chance to deposit it. ('cancelled', 'cancelled') ) class InvoiceTransaction(TimeStampedModel): """Record payment and refund information for invoices. There are two expected use cases: 1) We send an invoice to someone, and they send us a check. We then manually create an invoice transaction to represent the payment. 2) We send an invoice to someone, and they pay us. Later, we need to issue a refund for the payment. We manually create a transaction with a negative amount to represent the refund. """ class Meta(object): app_label = "shoppingcart" invoice = models.ForeignKey(Invoice) amount = models.DecimalField( default=0.0, decimal_places=2, max_digits=30, help_text=ugettext_lazy( "The amount of the transaction. Use positive amounts for payments" " and negative amounts for refunds." ) ) currency = models.CharField( default="usd", max_length=8, help_text=ugettext_lazy("Lower-case ISO currency codes") ) comments = models.TextField( null=True, blank=True, help_text=ugettext_lazy("Optional: provide additional information for this transaction") ) status = models.CharField( max_length=32, default='started', choices=INVOICE_TRANSACTION_STATUSES, help_text=ugettext_lazy( "The status of the payment or refund. " "'started' means that payment is expected, but money has not yet been transferred. " "'completed' means that the payment or refund was received. " "'cancelled' means that payment or refund was expected, but was cancelled before money was transferred. " ) ) created_by = models.ForeignKey(User) last_modified_by = models.ForeignKey(User, related_name='last_modified_by_user') @classmethod def get_invoice_transaction(cls, invoice_id): """ if found Returns the Invoice Transaction object for the given invoice_id else returns None """ try: return cls.objects.get(Q(invoice_id=invoice_id), Q(status='completed') | Q(status='refunded')) except InvoiceTransaction.DoesNotExist: return None @classmethod def get_total_amount_of_paid_course_invoices(cls, course_key): """ returns the total amount of the paid invoices. """ result = cls.objects.filter(amount__gt=0, invoice__course_id=course_key, status='completed').aggregate( total=Sum( 'amount', output_field=models.DecimalField(decimal_places=2, max_digits=30) ) ) total = result.get('total', 0) return total if total else 0 def snapshot(self): """Create a snapshot of the invoice transaction. The returned dictionary is JSON-serializable. Returns: dict """ return { 'amount': unicode(self.amount), 'currency': self.currency, 'comments': self.comments, 'status': self.status, 'created_by': self.created_by.username, 'last_modified_by': self.last_modified_by.username } class InvoiceItem(TimeStampedModel): """ This is the basic interface for invoice items. Each invoice item represents a "line" in the invoice. For example, in an invoice for course registration codes, there might be an invoice item representing 10 registration codes for the DemoX course. """ class Meta(object): app_label = "shoppingcart" objects = InheritanceManager() invoice = models.ForeignKey(Invoice, db_index=True) qty = models.IntegerField( default=1, help_text=ugettext_lazy("The number of items sold.") ) unit_price = models.DecimalField( default=0.0, decimal_places=2, max_digits=30, help_text=ugettext_lazy("The price per item sold, including discounts.") ) currency = models.CharField( default="usd", max_length=8, help_text=ugettext_lazy("Lower-case ISO currency codes") ) def snapshot(self): """Create a snapshot of the invoice item. The returned dictionary is JSON-serializable. Returns: dict """ return { 'qty': self.qty, 'unit_price': unicode(self.unit_price), 'currency': self.currency } class CourseRegistrationCodeInvoiceItem(InvoiceItem): """ This is an invoice item that represents a payment for a course registration. """ class Meta(object): app_label = "shoppingcart" course_id = CourseKeyField(max_length=128, db_index=True) def snapshot(self): """Create a snapshot of the invoice item. This is the same as a snapshot for other invoice items, with the addition of a `course_id` field. Returns: dict """ snapshot = super(CourseRegistrationCodeInvoiceItem, self).snapshot() snapshot['course_id'] = unicode(self.course_id) return snapshot class InvoiceHistory(models.Model): """History of changes to invoices. This table stores snapshots of invoice state, including the associated line items and transactions (payments/refunds). Entries in the table are created, but never deleted or modified. We use Django signals to save history entries on change events. These signals are fired within a database transaction, so the history record is created only if the invoice change is successfully persisted. """ timestamp = models.DateTimeField(auto_now_add=True, db_index=True) invoice = models.ForeignKey(Invoice) # JSON-serialized representation of the current state # of the invoice, including its line items and # transactions (payments/refunds). snapshot = models.TextField(blank=True) @classmethod def save_invoice_snapshot(cls, invoice): """Save a snapshot of the invoice's current state. Arguments: invoice (Invoice): The invoice to save. """ cls.objects.create( invoice=invoice, snapshot=json.dumps(invoice.snapshot()) ) @staticmethod def snapshot_receiver(sender, instance, **kwargs): # pylint: disable=unused-argument """Signal receiver that saves a snapshot of an invoice. Arguments: sender: Not used, but required by Django signals. instance (Invoice, InvoiceItem, or InvoiceTransaction) """ if isinstance(instance, Invoice): InvoiceHistory.save_invoice_snapshot(instance) elif hasattr(instance, 'invoice'): InvoiceHistory.save_invoice_snapshot(instance.invoice) class Meta(object): get_latest_by = "timestamp" app_label = "shoppingcart" # Hook up Django signals to record changes in the history table. # We record any change to an invoice, invoice item, or transaction. # We also record any deletion of a transaction, since users can delete # transactions via Django admin. # Note that we need to include *each* InvoiceItem subclass # here, since Django signals do not fire automatically for subclasses # of the "sender" class. post_save.connect(InvoiceHistory.snapshot_receiver, sender=Invoice) post_save.connect(InvoiceHistory.snapshot_receiver, sender=InvoiceItem) post_save.connect(InvoiceHistory.snapshot_receiver, sender=CourseRegistrationCodeInvoiceItem) post_save.connect(InvoiceHistory.snapshot_receiver, sender=InvoiceTransaction) post_delete.connect(InvoiceHistory.snapshot_receiver, sender=InvoiceTransaction) class CourseRegistrationCode(models.Model): """ This table contains registration codes With registration code, a user can register for a course for free """ class Meta(object): app_label = "shoppingcart" code = models.CharField(max_length=32, db_index=True, unique=True) course_id = CourseKeyField(max_length=255, db_index=True) created_by = models.ForeignKey(User, related_name='created_by_user') created_at = models.DateTimeField(auto_now_add=True) order = models.ForeignKey(Order, db_index=True, null=True, related_name="purchase_order") mode_slug = models.CharField(max_length=100, null=True) is_valid = models.BooleanField(default=True) # For backwards compatibility, we maintain the FK to "invoice" # In the future, we will remove this in favor of the FK # to "invoice_item" (which can be used to look up the invoice). invoice = models.ForeignKey(Invoice, null=True) invoice_item = models.ForeignKey(CourseRegistrationCodeInvoiceItem, null=True) @classmethod def order_generated_registration_codes(cls, course_id): """ Returns the registration codes that were generated via bulk purchase scenario. """ return cls.objects.filter(order__isnull=False, course_id=course_id) @classmethod def invoice_generated_registration_codes(cls, course_id): """ Returns the registration codes that were generated via invoice. """ return cls.objects.filter(invoice__isnull=False, course_id=course_id) class RegistrationCodeRedemption(models.Model): """ This model contains the registration-code redemption info """ class Meta(object): app_label = "shoppingcart" order = models.ForeignKey(Order, db_index=True, null=True) registration_code = models.ForeignKey(CourseRegistrationCode, db_index=True) redeemed_by = models.ForeignKey(User, db_index=True) redeemed_at = models.DateTimeField(auto_now_add=True, null=True) course_enrollment = models.ForeignKey(CourseEnrollment, null=True) @classmethod def registration_code_used_for_enrollment(cls, course_enrollment): """ Returns RegistrationCodeRedemption object if registration code has been used during the course enrollment else Returns None. """ # theoretically there could be more than one (e.g. someone self-unenrolls # then re-enrolls with a different regcode) reg_codes = cls.objects.filter(course_enrollment=course_enrollment).order_by('-redeemed_at') if reg_codes: # return the first one. In all normal use cases of registration codes # the user will only have one return reg_codes[0] return None @classmethod def is_registration_code_redeemed(cls, course_reg_code): """ Checks the existence of the registration code in the RegistrationCodeRedemption """ return cls.objects.filter(registration_code__code=course_reg_code).exists() @classmethod def get_registration_code_redemption(cls, code, course_id): """ Returns the registration code redemption object if found else returns None. """ try: code_redemption = cls.objects.get(registration_code__code=code, registration_code__course_id=course_id) except cls.DoesNotExist: code_redemption = None return code_redemption @classmethod def create_invoice_generated_registration_redemption(cls, course_reg_code, user): # pylint: disable=invalid-name """ This function creates a RegistrationCodeRedemption entry in case the registration codes were invoice generated and thus the order_id is missing. """ code_redemption = RegistrationCodeRedemption(registration_code=course_reg_code, redeemed_by=user) code_redemption.save() return code_redemption class SoftDeleteCouponManager(models.Manager): """ Use this manager to get objects that have a is_active=True """ def get_active_coupons_queryset(self): """ filter the is_active = True Coupons only """ return super(SoftDeleteCouponManager, self).get_queryset().filter(is_active=True) def get_queryset(self): """ get all the coupon objects """ return super(SoftDeleteCouponManager, self).get_queryset() class Coupon(models.Model): """ This table contains coupon codes A user can get a discount offer on course if provide coupon code """ class Meta(object): app_label = "shoppingcart" code = models.CharField(max_length=32, db_index=True) description = models.CharField(max_length=255, null=True, blank=True) course_id = CourseKeyField(max_length=255) percentage_discount = models.IntegerField(default=0) created_by = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) expiration_date = models.DateTimeField(null=True, blank=True) def __unicode__(self): return "[Coupon] code: {} course: {}".format(self.code, self.course_id) objects = SoftDeleteCouponManager() @property def display_expiry_date(self): """ return the coupon expiration date in the readable format """ return (self.expiration_date - timedelta(days=1)).strftime("%B %d, %Y") if self.expiration_date else None class CouponRedemption(models.Model): """ This table contain coupon redemption info """ class Meta(object): app_label = "shoppingcart" order = models.ForeignKey(Order, db_index=True) user = models.ForeignKey(User, db_index=True) coupon = models.ForeignKey(Coupon, db_index=True) @classmethod def remove_code_redemption_from_item(cls, item, user): """ If an item removed from shopping cart then we will remove the corresponding redemption info of coupon code """ order_item_course_id = item.course_id try: # Try to remove redemption information of coupon code, If exist. coupon_redemption = cls.objects.get( user=user, coupon__course_id=order_item_course_id if order_item_course_id else CourseKeyField.Empty, order=item.order_id ) coupon_redemption.delete() log.info( u'Coupon "%s" redemption entry removed for user "%s" for order item "%s"', coupon_redemption.coupon.code, user, str(item.id), ) except CouponRedemption.DoesNotExist: log.debug(u'Code redemption does not exist for order item id=%s.', str(item.id)) @classmethod def remove_coupon_redemption_from_cart(cls, user, cart): """ This method delete coupon redemption """ coupon_redemption = cls.objects.filter(user=user, order=cart) if coupon_redemption: coupon_redemption.delete() log.info(u'Coupon redemption entry removed for user %s for order %s', user, cart.id) @classmethod def get_discount_price(cls, percentage_discount, value): """ return discounted price against coupon """ discount = Decimal("{0:.2f}".format(Decimal(percentage_discount / 100.00) * value)) return value - discount @classmethod def add_coupon_redemption(cls, coupon, order, cart_items): """ add coupon info into coupon_redemption model """ is_redemption_applied = False coupon_redemptions = cls.objects.filter(order=order, user=order.user) for coupon_redemption in coupon_redemptions: if coupon_redemption.coupon.code != coupon.code or coupon_redemption.coupon.id == coupon.id: log.exception( u"Coupon redemption already exist for user '%s' against order id '%s'", order.user.username, order.id, ) raise MultipleCouponsNotAllowedException for item in cart_items: if item.course_id: if item.course_id == coupon.course_id: coupon_redemption = cls(order=order, user=order.user, coupon=coupon) coupon_redemption.save() discount_price = cls.get_discount_price(coupon.percentage_discount, item.unit_cost) item.list_price = item.unit_cost item.unit_cost = discount_price item.save() log.info( u"Discount generated for user %s against order id '%s'", order.user.username, order.id, ) is_redemption_applied = True return is_redemption_applied return is_redemption_applied @classmethod def get_top_discount_codes_used(cls, course_id): """ Returns the top discount codes used. QuerySet = [ { 'coupon__percentage_discount': 22, 'coupon__code': '12', 'coupon__used_count': '2', }, { ... } ] """ return cls.objects.filter(order__status='purchased', coupon__course_id=course_id).values( 'coupon__code', 'coupon__percentage_discount' ).annotate(coupon__used_count=Count('coupon__code')).order_by('-coupon__used_count') @classmethod def get_total_coupon_code_purchases(cls, course_id): """ returns total seats purchases using coupon codes """ return cls.objects.filter(order__status='purchased', coupon__course_id=course_id).aggregate(Count('coupon')) class PaidCourseRegistration(OrderItem): """ This is an inventory item for paying for a course registration """ class Meta(object): app_label = "shoppingcart" course_id = CourseKeyField(max_length=128, db_index=True) mode = models.SlugField(default=CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG) course_enrollment = models.ForeignKey(CourseEnrollment, null=True) @classmethod def get_self_purchased_seat_count(cls, course_key, status='purchased'): """ returns the count of paid_course items filter by course_id and status. """ return cls.objects.filter(course_id=course_key, status=status).count() @classmethod def get_course_item_for_user_enrollment(cls, user, course_id, course_enrollment): """ Returns PaidCourseRegistration object if user has payed for the course enrollment else Returns None """ try: return cls.objects.filter(course_id=course_id, user=user, course_enrollment=course_enrollment, status='purchased').latest('id') except PaidCourseRegistration.DoesNotExist: return None @classmethod def contained_in_order(cls, order, course_id): """ Is the course defined by course_id contained in the order? """ return course_id in [ item.course_id for item in order.orderitem_set.all().select_subclasses("paidcourseregistration") if isinstance(item, cls) ] @classmethod def get_total_amount_of_purchased_item(cls, course_key, status='purchased'): """ This will return the total amount of money that a purchased course generated """ total_cost = 0 result = cls.objects.filter(course_id=course_key, status=status).aggregate( total=Sum( F('qty') * F('unit_cost'), output_field=models.DecimalField(decimal_places=2, max_digits=30) ) ) if result['total'] is not None: total_cost = result['total'] return total_cost @classmethod @transaction.atomic def add_to_order(cls, order, course_id, mode_slug=CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG, cost=None, currency=None): # pylint: disable=arguments-differ """ A standardized way to create these objects, with sensible defaults filled in. Will update the cost if called on an order that already carries the course. Returns the order item """ # First a bunch of sanity checks: # actually fetch the course to make sure it exists, use this to # throw errors if it doesn't. course = modulestore().get_course(course_id) if not course: log.error("User {} tried to add non-existent course {} to cart id {}" .format(order.user.email, course_id, order.id)) raise CourseDoesNotExistException if cls.contained_in_order(order, course_id): log.warning( u"User %s tried to add PaidCourseRegistration for course %s, already in cart id %s", order.user.email, course_id, order.id, ) raise ItemAlreadyInCartException if CourseEnrollment.is_enrolled(user=order.user, course_key=course_id): log.warning("User {} trying to add course {} to cart id {}, already registered" .format(order.user.email, course_id, order.id)) raise AlreadyEnrolledInCourseException ### Validations done, now proceed ### handle default arguments for mode_slug, cost, currency course_mode = CourseMode.mode_for_course(course_id, mode_slug) if not course_mode: # user could have specified a mode that's not set, in that case return the DEFAULT_MODE course_mode = CourseMode.DEFAULT_SHOPPINGCART_MODE if not cost: cost = course_mode.min_price if not currency: currency = course_mode.currency super(PaidCourseRegistration, cls).add_to_order(order, course_id, cost, currency=currency) item, __ = cls.objects.get_or_create(order=order, user=order.user, course_id=course_id) item.status = order.status item.mode = course_mode.slug item.qty = 1 item.unit_cost = cost item.list_price = cost item.line_desc = _(u'Registration for Course: {course_name}').format( course_name=course.display_name_with_default_escaped) item.currency = currency order.currency = currency item.report_comments = item.csv_report_comments order.save() item.save() log.info("User {} added course registration {} to cart: order {}" .format(order.user.email, course_id, order.id)) CourseEnrollment.send_signal_full(EnrollStatusChange.paid_start, user=order.user, mode=item.mode, course_id=course_id, cost=cost, currency=currency) return item def purchased_callback(self): """ When purchased, this should enroll the user in the course. We are assuming that course settings for enrollment date are configured such that only if the (user.email, course_id) pair is found in CourseEnrollmentAllowed will the user be allowed to enroll. Otherwise requiring payment would in fact be quite silly since there's a clear back door. """ if not modulestore().has_course(self.course_id): msg = u"The customer purchased Course {0}, but that course doesn't exist!".format(self.course_id) log.error(msg) raise PurchasedCallbackException(msg) # enroll in course and link to the enrollment_id self.course_enrollment = CourseEnrollment.enroll(user=self.user, course_key=self.course_id, mode=self.mode) self.save() log.info("Enrolled {0} in paid course {1}, paid ${2}" .format(self.user.email, self.course_id, self.line_cost)) self.course_enrollment.send_signal(EnrollStatusChange.paid_complete, cost=self.line_cost, currency=self.currency) def generate_receipt_instructions(self): """ Generates instructions when the user has purchased a PaidCourseRegistration. Basically tells the user to visit the dashboard to see their new classes """ notification = _( u"Please visit your {link_start}dashboard{link_end} " u"to see your new course." ).format( link_start=u'<a href="{url}">'.format(url=reverse('dashboard')), link_end=u'</a>', ) return self.pk_with_subclass, set([notification]) @property def csv_report_comments(self): """ Tries to fetch an annotation associated with the course_id from the database. If not found, returns u"". Otherwise returns the annotation """ try: return PaidCourseRegistrationAnnotation.objects.get(course_id=self.course_id).annotation except PaidCourseRegistrationAnnotation.DoesNotExist: return u"" def analytics_data(self): """Simple function used to construct analytics data for the OrderItem. If the Order Item is associated with a course, additional fields will be populated with course information. If there is a mode associated, the mode data is included in the SKU. Returns A dictionary containing analytics data for this OrderItem. """ data = super(PaidCourseRegistration, self).analytics_data() sku = data['sku'] if self.course_id != CourseKeyField.Empty: data['name'] = unicode(self.course_id) data['category'] = unicode(self.course_id.org) if self.mode: data['sku'] = sku + u'.' + unicode(self.mode) return data class CourseRegCodeItem(OrderItem): """ This is an inventory item for paying for generating course registration codes """ class Meta(object): app_label = "shoppingcart" course_id = CourseKeyField(max_length=128, db_index=True) mode = models.SlugField(default=CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG) @classmethod def get_bulk_purchased_seat_count(cls, course_key, status='purchased'): """ returns the sum of bulk purchases seats. """ total = 0 result = cls.objects.filter(course_id=course_key, status=status).aggregate(total=Sum('qty')) if result['total'] is not None: total = result['total'] return total @classmethod def contained_in_order(cls, order, course_id): """ Is the course defined by course_id contained in the order? """ return course_id in [ item.course_id for item in order.orderitem_set.all().select_subclasses("courseregcodeitem") if isinstance(item, cls) ] @classmethod def get_total_amount_of_purchased_item(cls, course_key, status='purchased'): """ This will return the total amount of money that a purchased course generated """ total_cost = 0 result = cls.objects.filter(course_id=course_key, status=status).aggregate( total=Sum( F('qty') * F('unit_cost'), output_field=models.DecimalField(decimal_places=2, max_digits=30) ) ) if result['total'] is not None: total_cost = result['total'] return total_cost @classmethod @transaction.atomic def add_to_order(cls, order, course_id, qty, mode_slug=CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG, cost=None, currency=None): # pylint: disable=arguments-differ """ A standardized way to create these objects, with sensible defaults filled in. Will update the cost if called on an order that already carries the course. Returns the order item """ # First a bunch of sanity checks: # actually fetch the course to make sure it exists, use this to # throw errors if it doesn't. course = modulestore().get_course(course_id) if not course: log.error("User {} tried to add non-existent course {} to cart id {}" .format(order.user.email, course_id, order.id)) raise CourseDoesNotExistException if cls.contained_in_order(order, course_id): log.warning("User {} tried to add PaidCourseRegistration for course {}, already in cart id {}" .format(order.user.email, course_id, order.id)) raise ItemAlreadyInCartException if CourseEnrollment.is_enrolled(user=order.user, course_key=course_id): log.warning("User {} trying to add course {} to cart id {}, already registered" .format(order.user.email, course_id, order.id)) raise AlreadyEnrolledInCourseException ### Validations done, now proceed ### handle default arguments for mode_slug, cost, currency course_mode = CourseMode.mode_for_course(course_id, mode_slug) if not course_mode: # user could have specified a mode that's not set, in that case return the DEFAULT_SHOPPINGCART_MODE course_mode = CourseMode.DEFAULT_SHOPPINGCART_MODE if not cost: cost = course_mode.min_price if not currency: currency = course_mode.currency super(CourseRegCodeItem, cls).add_to_order(order, course_id, cost, currency=currency) item, created = cls.objects.get_or_create(order=order, user=order.user, course_id=course_id) # pylint: disable=unused-variable item.status = order.status item.mode = course_mode.slug item.unit_cost = cost item.list_price = cost item.qty = qty item.line_desc = _(u'Enrollment codes for Course: {course_name}').format( course_name=course.display_name_with_default_escaped) item.currency = currency order.currency = currency item.report_comments = item.csv_report_comments order.save() item.save() log.info("User {} added course registration {} to cart: order {}" .format(order.user.email, course_id, order.id)) return item def purchased_callback(self): """ The purchase is completed, this OrderItem type will generate Registration Codes that will be redeemed by users """ if not modulestore().has_course(self.course_id): msg = u"The customer purchased Course {0}, but that course doesn't exist!".format(self.course_id) log.error(msg) raise PurchasedCallbackException(msg) total_registration_codes = int(self.qty) # we need to import here because of a circular dependency # we should ultimately refactor code to have save_registration_code in this models.py # file, but there's also a shared dependency on a random string generator which # is in another PR (for another feature) from lms.djangoapps.instructor.views.api import save_registration_code for i in range(total_registration_codes): # pylint: disable=unused-variable save_registration_code(self.user, self.course_id, self.mode, order=self.order) log.info("Enrolled {0} in paid course {1}, paid ${2}" .format(self.user.email, self.course_id, self.line_cost)) @property def csv_report_comments(self): """ Tries to fetch an annotation associated with the course_id from the database. If not found, returns u"". Otherwise returns the annotation """ try: return CourseRegCodeItemAnnotation.objects.get(course_id=self.course_id).annotation except CourseRegCodeItemAnnotation.DoesNotExist: return u"" def analytics_data(self): """Simple function used to construct analytics data for the OrderItem. If the OrderItem is associated with a course, additional fields will be populated with course information. If a mode is available, it will be included in the SKU. Returns A dictionary containing analytics data for this OrderItem. """ data = super(CourseRegCodeItem, self).analytics_data() sku = data['sku'] if self.course_id != CourseKeyField.Empty: data['name'] = unicode(self.course_id) data['category'] = unicode(self.course_id.org) if self.mode: data['sku'] = sku + u'.' + unicode(self.mode) return data class CourseRegCodeItemAnnotation(models.Model): """ A model that maps course_id to an additional annotation. This is specifically needed because when Stanford generates report for the paid courses, each report item must contain the payment account associated with a course. And unfortunately we didn't have the concept of a "SKU" or stock item where we could keep this association, so this is to retrofit it. """ class Meta(object): app_label = "shoppingcart" course_id = CourseKeyField(unique=True, max_length=128, db_index=True) annotation = models.TextField(null=True) def __unicode__(self): # pylint: disable=no-member return u"{} : {}".format(self.course_id.to_deprecated_string(), self.annotation) class PaidCourseRegistrationAnnotation(models.Model): """ A model that maps course_id to an additional annotation. This is specifically needed because when Stanford generates report for the paid courses, each report item must contain the payment account associated with a course. And unfortunately we didn't have the concept of a "SKU" or stock item where we could keep this association, so this is to retrofit it. """ class Meta(object): app_label = "shoppingcart" course_id = CourseKeyField(unique=True, max_length=128, db_index=True) annotation = models.TextField(null=True) def __unicode__(self): # pylint: disable=no-member return u"{} : {}".format(self.course_id.to_deprecated_string(), self.annotation) class CertificateItem(OrderItem): """ This is an inventory item for purchasing certificates """ class Meta(object): app_label = "shoppingcart" course_id = CourseKeyField(max_length=128, db_index=True) course_enrollment = models.ForeignKey(CourseEnrollment) mode = models.SlugField() @receiver(UNENROLL_DONE) def refund_cert_callback(sender, course_enrollment=None, skip_refund=False, **kwargs): # pylint: disable=no-self-argument,unused-argument """ When a CourseEnrollment object calls its unenroll method, this function checks to see if that unenrollment occurred in a verified certificate that was within the refund deadline. If so, it actually performs the refund. Returns the refunded certificate on a successful refund; else, it returns nothing. """ # Only refund verified cert unenrollments that are within bounds of the expiration date if (not course_enrollment.refundable()) or skip_refund: return target_certs = CertificateItem.objects.filter(course_id=course_enrollment.course_id, user_id=course_enrollment.user, status='purchased', mode='verified') try: target_cert = target_certs[0] except IndexError: log.warning( u"Matching CertificateItem not found while trying to refund. User %s, Course %s", course_enrollment.user, course_enrollment.course_id, ) return target_cert.status = 'refunded' target_cert.refund_requested_time = datetime.now(pytz.utc) target_cert.save() target_cert.order.refund() order_number = target_cert.order_id # send billing an email so they can handle refunding subject = _("[Refund] User-Requested Refund") message = "User {user} ({user_email}) has requested a refund on Order #{order_number}.".format(user=course_enrollment.user, user_email=course_enrollment.user.email, order_number=order_number) to_email = [settings.PAYMENT_SUPPORT_EMAIL] from_email = configuration_helpers.get_value('payment_support_email', settings.PAYMENT_SUPPORT_EMAIL) try: send_mail(subject, message, from_email, to_email, fail_silently=False) except Exception as exception: # pylint: disable=broad-except err_str = ('Failed sending email to billing to request a refund for verified certificate' ' (User {user}, Course {course}, CourseEnrollmentID {ce_id}, Order #{order})\n{exception}') log.error(err_str.format( user=course_enrollment.user, course=course_enrollment.course_id, ce_id=course_enrollment.id, order=order_number, exception=exception, )) return target_cert @classmethod @transaction.atomic def add_to_order(cls, order, course_id, cost, mode, currency='usd'): """ Add a CertificateItem to an order Returns the CertificateItem object after saving `order` - an order that this item should be added to, generally the cart order `course_id` - the course that we would like to purchase as a CertificateItem `cost` - the amount the user will be paying for this CertificateItem `mode` - the course mode that this certificate is going to be issued for This item also creates a new enrollment if none exists for this user and this course. Example Usage: cart = Order.get_cart_for_user(user) CertificateItem.add_to_order(cart, 'edX/Test101/2013_Fall', 30, 'verified') """ super(CertificateItem, cls).add_to_order(order, course_id, cost, currency=currency) course_enrollment = CourseEnrollment.get_or_create_enrollment(order.user, course_id) # do some validation on the enrollment mode valid_modes = CourseMode.modes_for_course_dict(course_id) if mode in valid_modes: mode_info = valid_modes[mode] else: msg = u"Mode {mode} does not exist for {course_id}".format(mode=mode, course_id=course_id) log.error(msg) raise InvalidCartItem( _(u"Mode {mode} does not exist for {course_id}").format(mode=mode, course_id=course_id) ) item, _created = cls.objects.get_or_create( order=order, user=order.user, course_id=course_id, course_enrollment=course_enrollment, mode=mode, ) item.status = order.status item.qty = 1 item.unit_cost = cost item.list_price = cost course_name = modulestore().get_course(course_id).display_name # Translators: In this particular case, mode_name refers to a # particular mode (i.e. Honor Code Certificate, Verified Certificate, etc) # by which a user could enroll in the given course. item.line_desc = _("{mode_name} for course {course}").format( mode_name=mode_info.name, course=course_name ) item.currency = currency order.currency = currency order.save() item.save() # signal course added to cart course_enrollment.send_signal(EnrollStatusChange.paid_start, cost=cost, currency=currency) return item def purchased_callback(self): """ When purchase goes through, activate and update the course enrollment for the correct mode """ self.course_enrollment.change_mode(self.mode) self.course_enrollment.activate() self.course_enrollment.send_signal(EnrollStatusChange.upgrade_complete, cost=self.unit_cost, currency=self.currency) def additional_instruction_text(self): verification_reminder = "" refund_reminder_msg = _("You can unenroll in the course and receive a full refund for 14 days after the course " "start date. ") is_enrollment_mode_verified = self.course_enrollment.is_verified_enrollment() is_professional_mode_verified = self.course_enrollment.is_professional_enrollment() if is_enrollment_mode_verified: domain = configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME) path = reverse('verify_student_verify_now', kwargs={'course_id': unicode(self.course_id)}) verification_url = "http://{domain}{path}".format(domain=domain, path=path) verification_reminder = _( "If you haven't verified your identity yet, please start the verification process ({verification_url})." ).format(verification_url=verification_url) if is_professional_mode_verified: refund_reminder_msg = _("You can unenroll in the course and receive a full refund for 2 days after the " "course start date. ") refund_reminder = _( "{refund_reminder_msg}" "To receive your refund, contact {billing_email}. " "Please include your order number in your email. " "Please do NOT include your credit card information." ).format( refund_reminder_msg=refund_reminder_msg, billing_email=settings.PAYMENT_SUPPORT_EMAIL ) # Need this to be unicode in case the reminder strings # have been translated and contain non-ASCII unicode return u"{verification_reminder} {refund_reminder}".format( verification_reminder=verification_reminder, refund_reminder=refund_reminder ) @classmethod def verified_certificates_count(cls, course_id, status): """Return a queryset of CertificateItem for every verified enrollment in course_id with the given status.""" return use_read_replica_if_available( CertificateItem.objects.filter(course_id=course_id, mode='verified', status=status).count()) # TODO combine these three methods into one @classmethod def verified_certificates_monetary_field_sum(cls, course_id, status, field_to_aggregate): """ Returns a Decimal indicating the total sum of field_to_aggregate for all verified certificates with a particular status. Sample usages: - status 'refunded' and field_to_aggregate 'unit_cost' will give the total amount of money refunded for course_id - status 'purchased' and field_to_aggregate 'service_fees' gives the sum of all service fees for purchased certificates etc """ query = use_read_replica_if_available( CertificateItem.objects.filter(course_id=course_id, mode='verified', status=status)).aggregate(Sum(field_to_aggregate))[field_to_aggregate + '__sum'] if query is None: return Decimal(0.00) else: return query @classmethod def verified_certificates_contributing_more_than_minimum(cls, course_id): return use_read_replica_if_available( CertificateItem.objects.filter( course_id=course_id, mode='verified', status='purchased', unit_cost__gt=(CourseMode.min_course_price_for_verified_for_currency(course_id, 'usd')))).count() def analytics_data(self): """Simple function used to construct analytics data for the OrderItem. If the CertificateItem is associated with a course, additional fields will be populated with course information. If there is a mode associated with the certificate, it is included in the SKU. Returns A dictionary containing analytics data for this OrderItem. """ data = super(CertificateItem, self).analytics_data() sku = data['sku'] if self.course_id != CourseKeyField.Empty: data['name'] = unicode(self.course_id) data['category'] = unicode(self.course_id.org) if self.mode: data['sku'] = sku + u'.' + unicode(self.mode) return data class DonationConfiguration(ConfigurationModel): """Configure whether donations are enabled on the site.""" class Meta(ConfigurationModel.Meta): app_label = "shoppingcart" class Donation(OrderItem): """A donation made by a user. Donations can be made for a specific course or to the organization as a whole. Users can choose the donation amount. """ class Meta(object): app_label = "shoppingcart" # Types of donations DONATION_TYPES = ( ("general", "A general donation"), ("course", "A donation to a particular course") ) # The type of donation donation_type = models.CharField(max_length=32, default="general", choices=DONATION_TYPES) # If a donation is made for a specific course, then store the course ID here. # If the donation is made to the organization as a whole, # set this field to CourseKeyField.Empty course_id = CourseKeyField(max_length=255, db_index=True) @classmethod @transaction.atomic def add_to_order(cls, order, donation_amount, course_id=None, currency='usd'): """Add a donation to an order. Args: order (Order): The order to add this donation to. donation_amount (Decimal): The amount the user is donating. Keyword Args: course_id (CourseKey): If provided, associate this donation with a particular course. currency (str): The currency used for the the donation. Raises: InvalidCartItem: The provided course ID is not valid. Returns: Donation """ # This will validate the currency but won't actually add the item to the order. super(Donation, cls).add_to_order(order, currency=currency) # Create a line item description, including the name of the course # if this is a per-course donation. # This will raise an exception if the course can't be found. description = cls._line_item_description(course_id=course_id) params = { "order": order, "user": order.user, "status": order.status, "qty": 1, "unit_cost": donation_amount, "currency": currency, "line_desc": description } if course_id is not None: params["course_id"] = course_id params["donation_type"] = "course" else: params["donation_type"] = "general" return cls.objects.create(**params) def purchased_callback(self): """Donations do not need to be fulfilled, so this method does nothing.""" pass def generate_receipt_instructions(self): """Provide information about tax-deductible donations in the receipt. Returns: tuple of (Donation, unicode) """ return self.pk_with_subclass, set([self._tax_deduction_msg()]) def additional_instruction_text(self, **kwargs): """Provide information about tax-deductible donations in the confirmation email. Returns: unicode """ return self._tax_deduction_msg() def _tax_deduction_msg(self): """Return the translated version of the tax deduction message. Returns: unicode """ return _( u"We greatly appreciate this generous contribution and your support of the {platform_name} mission. " u"This receipt was prepared to support charitable contributions for tax purposes. " u"We confirm that neither goods nor services were provided in exchange for this gift." ).format(platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)) @classmethod def _line_item_description(cls, course_id=None): """Create a line-item description for the donation. Includes the course display name if provided. Keyword Arguments: course_id (CourseKey) Raises: CourseDoesNotExistException: The course ID is not valid. Returns: unicode """ # If a course ID is provided, include the display name of the course # in the line item description. if course_id is not None: course = modulestore().get_course(course_id) if course is None: msg = u"Could not find a course with the ID '{course_id}'".format(course_id=course_id) log.error(msg) raise CourseDoesNotExistException( _(u"Could not find a course with the ID '{course_id}'").format(course_id=course_id) ) return _(u"Donation for {course}").format(course=course.display_name) # The donation is for the organization as a whole, not a specific course else: return _(u"Donation for {platform_name}").format( platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), ) @property def single_item_receipt_context(self): return { 'receipt_has_donation_item': True, } def analytics_data(self): """Simple function used to construct analytics data for the OrderItem. If the donation is associated with a course, additional fields will be populated with course information. When no name or category is specified by the implementation, the platform name is used as a default value for required event fields, to declare that the Order is specific to the platform, rather than a specific product name or category. Returns A dictionary containing analytics data for this OrderItem. """ data = super(Donation, self).analytics_data() if self.course_id != CourseKeyField.Empty: data['name'] = unicode(self.course_id) data['category'] = unicode(self.course_id.org) else: data['name'] = configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME) data['category'] = configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME) return data @property def pdf_receipt_display_name(self): """ How to display this item on a PDF printed receipt file. """ return self._line_item_description(course_id=self.course_id)
caesar2164/edx-platform
lms/djangoapps/shoppingcart/models.py
Python
agpl-3.0
91,861
class CreateAnalyticSequenceAndAnalyticSegmentTables < ActiveRecord::Migration[5.0] def change create_table :analytic_sequences do |t| t.timestamps end create_table :analytic_segments do |t| t.references :analytic_sequence, index: true, foreign_key: true, null: false t.string :name, null: false t.integer :position, null: false t.timestamps end end end
ekylibre/ekylibre
db/migrate/20210219172016_create_analytic_sequence_and_analytic_segment_tables.rb
Ruby
agpl-3.0
405
<a class="menu-item about" href="#about">{{i18n "more-menu.about"}}</a> <a class="menu-item recommended-mobile-wallets" href="#recommended-mobile-wallets">{{i18n "more-menu.recommended-mobile-wallets"}}</a>
Learn-by-doing/crypto-terminal
html/templates/more-menu.html
HTML
agpl-3.0
207
/* * Copyright (C) 2005 Luca Veltri - University of Parma - Italy * * This file is part of MjSip (http://www.mjsip.org) * * MjSip is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * MjSip is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Affero GNU General Public License for more details. * * You should have received a copy of the Affero GNU General Public License * along with MjSip; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author(s): * Luca Veltri (luca.veltri@unipr.it) */ package org.zoolu.sip.provider; import org.zoolu.net.*; import org.zoolu.sip.header.*; import org.zoolu.sip.message.Message; import org.zoolu.sip.address.*; import org.zoolu.sip.transaction.Transaction; import org.zoolu.tools.Configure; import org.zoolu.tools.Configurable; import org.zoolu.tools.Parser; import org.zoolu.tools.Random; import org.zoolu.tools.Log; import org.zoolu.tools.LogLevel; import org.zoolu.tools.RotatingLog; //import org.zoolu.tools.MD5; import org.zoolu.tools.SimpleDigest; import org.zoolu.tools.DateFormat; import java.util.Hashtable; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.io.PrintStream; //PersonalJava //import java.util.HashSet; //import java.util.Iterator; import org.zoolu.tools.HashSet; import org.zoolu.tools.Iterator; import java.util.Enumeration; import java.util.Vector; import java.util.Date; /** SipProvider implements the SIP transport layer, that is the layer responsable for * sending and receiving SIP messages. Messages are received by the callback function * defined in the interface SipProviderListener. * <p> * SipProvider implements also multiplexing/demultiplexing service through the use of * SIP interface identifiers and <i>onReceivedMessage()<i/> callback function * of specific SipProviderListener. * <p> * A SipProviderListener can be added to a SipProvider through the * addSipProviderListener(id,listener) method, where: * <b> - <i>id<i/> is the SIP interface identifier the listener has to be bound to, * <b> - <i>listener<i/> is the SipProviderListener that received messages are passed to. * <p/> * The SIP interface identifier specifies the type of messages the listener is going to * receive for. Together with the specific SipProvider, it represents the complete SIP * Service Access Point (SAP) address/identifier used for demultiplexing SIP messages * at receiving side. * <p/> * The identifier can be of one of the three following types: transaction_id, dialog_id, * or method_id. These types of identifiers characterize respectively: * <br> - messages within a specific transaction, * <br> - messages within a specific dialog, * <br> - messages related to a specific SIP method. * It is also possible to use the the identifier ANY to specify * <br> - all messages that are out of any transactions, dialogs, or already specified * method types. * <p> * When receiving a message, the SipProvider first tries to look for a matching * transaction, then looks for a matching dialog, then for a matching method type, * and finally for a default listener (i.e. that with identifier ANY). * For the matched SipProviderListener, the method <i>onReceivedMessage()</i> is fired. * <p> * Note: no 482 (Loop Detected) responses are generated for requests that does not * properly match any ongoing transactions, dialogs, nor method types. */ public class SipProvider implements Configurable, TransportListener, TcpServerListener { // **************************** Constants **************************** /** UDP protocol type */ public static final String PROTO_UDP="udp"; /** TCP protocol type */ public static final String PROTO_TCP="tcp"; /** TLS protocol type */ public static final String PROTO_TLS="tls"; /** SCTP protocol type */ public static final String PROTO_SCTP="sctp"; /** String value "auto-configuration" used for auto configuration of the host address. */ public static final String AUTO_CONFIGURATION="AUTO-CONFIGURATION"; /** String value "auto-configuration" used for auto configuration of the host address. */ public static final String ALL_INTERFACES="ALL-INTERFACES"; /** String value "NO-OUTBOUND" used for setting no outbound proxy. */ //public static final String NO_OUTBOUND="NO-OUTBOUND"; /** Identifier used as listener id for capturing ANY incoming messages * that does not match any active method_id, transaction_id, nor dialog_id. * <br> In this context, "active" means that there is a active listener * for that specific method, transaction, or dialog. */ public static final Identifier ANY=new Identifier("ANY"); /** Identifier used as listener id for capturing any incoming messages in PROMISQUE mode, * that means that messages are passed to the present listener regardless of * any other active SipProviderListeners for specific messages. * <p/> * More than one SipProviderListener can be added and be active concurrently * for capturing messages in PROMISQUE mode. */ public static final Identifier PROMISQUE=new Identifier("PROMISQUE"); /** Minimum length for a valid SIP message. */ private static final int MIN_MESSAGE_LENGTH=12; // ***************** Readable/configurable attributes ***************** /** Via address/name. * Use 'auto-configuration' for auto detection, or let it undefined. */ String via_addr=null; /** Local SIP port */ int host_port=0; /** Network interface (IP address) used by SIP. * Use 'ALL-INTERFACES' for binding SIP to all interfaces (or let it undefined). */ String host_ifaddr=null; /** Transport protocols (the first protocol is used as default) */ String[] transport_protocols=null; /** Max number of (contemporary) open connections */ int nmax_connections=0; /** Outbound proxy (host_addr[:host_port]). * Use 'NONE' for not using an outbound proxy (or let it undefined). */ SocketAddress outbound_proxy=null; /** Whether logging all packets (including non-SIP keepalive tokens). */ boolean log_all_packets=false; // for backward compatibility: /** Outbound proxy addr (for backward compatibility). */ private String outbound_addr=null; /** Outbound proxy port (for backward compatibility). */ private int outbound_port=-1; // ********************* Non-readable attributes ********************* /** Event Loger */ protected Log event_log=null; /** Message Loger */ protected Log message_log=null; /** Network interface (IP address) used by SIP. */ IpAddress host_ipaddr=null; /** Default transport */ String default_transport=null; /** Whether using UDP as transport protocol */ boolean transport_udp=false; /** Whether using TCP as transport protocol */ boolean transport_tcp=false; /** Whether using TLS as transport protocol */ boolean transport_tls=false; /** Whether using SCTP as transport protocol */ boolean transport_sctp=false; /** Whether adding 'rport' parameter on outgoing requests. */ boolean rport=true; /** Whether forcing 'rport' parameter on incoming requests ('force-rport' mode). */ boolean force_rport=false; /** List of provider listeners */ Hashtable listeners=null; /** List of exception listeners */ HashSet exception_listeners=null; /** UDP transport */ UdpTransport udp=null; /** Tcp server */ TcpServer tcp_server=null; /** Connections */ Hashtable connections=null; // *************************** Costructors *************************** /** Creates a void SipProvider. */ /*protected SipProvider() { }*/ /** Creates a new SipProvider. */ public SipProvider(String via_addr, int port) { init(via_addr,port,null,null); initlog(); startTrasport(); } /** Creates a new SipProvider. * Costructs the SipProvider, initializing the SipProviderListeners, the transport protocols, and other attributes. */ public SipProvider(String via_addr, int port, String[] protocols, String ifaddr) { init(via_addr,port,protocols,ifaddr); initlog(); startTrasport(); } /** Creates a new SipProvider. * The SipProvider attributres are read from file. */ public SipProvider(String file) { if (!SipStack.isInit()) SipStack.init(file); new Configure(this,file); init(via_addr,host_port,transport_protocols,host_ifaddr); initlog(); startTrasport(); } /** Inits the SipProvider, initializing the SipProviderListeners, the transport protocols, the outbound proxy, and other attributes. */ private void init(String viaddr, int port, String[] protocols, String ifaddr) { if (!SipStack.isInit()) SipStack.init(); via_addr=viaddr; if (via_addr==null || via_addr.equalsIgnoreCase(AUTO_CONFIGURATION)) via_addr=IpAddress.getLocalHostAddress().toString(); host_port=port; if (host_port<=0) host_port=SipStack.default_port; host_ipaddr=null; if (ifaddr!=null && !ifaddr.equalsIgnoreCase(ALL_INTERFACES)) { try { host_ipaddr=IpAddress.getByName(ifaddr); } catch (IOException e) { e.printStackTrace(); host_ipaddr=null; } } transport_protocols=protocols; if (transport_protocols==null) transport_protocols=SipStack.default_transport_protocols; default_transport=transport_protocols[0]; for (int i=0; i<transport_protocols.length; i++) { transport_protocols[i]=transport_protocols[i].toLowerCase(); if (transport_protocols[i].equals(PROTO_UDP)) transport_udp=true; else if (transport_protocols[i].equals(PROTO_TCP)) transport_tcp=true; /* else if (transport_protocols[i].equals(PROTO_TLS)) transport_tls=true; else if (transport_protocols[i].equals(PROTO_SCTP)) transport_sctp=true; */ } if (nmax_connections<=0) nmax_connections=SipStack.default_nmax_connections; // just for backward compatibility.. if (outbound_port<0) outbound_port=SipStack.default_port; if (outbound_addr!=null) { if (outbound_addr.equalsIgnoreCase(Configure.NONE) || outbound_addr.equalsIgnoreCase("NO-OUTBOUND")) outbound_proxy=null; else outbound_proxy=new SocketAddress(outbound_addr,outbound_port); } rport=SipStack.use_rport; force_rport=SipStack.force_rport; exception_listeners=new HashSet(); listeners=new Hashtable(); connections=new Hashtable(); } /** Inits logs. */ private void initlog() { if (SipStack.debug_level>0) { String filename=SipStack.log_path+"//"+via_addr+"."+host_port; event_log=new RotatingLog(filename+"_events.log",null,SipStack.debug_level,SipStack.max_logsize*1024,SipStack.log_rotations,SipStack.rotation_scale,SipStack.rotation_time); message_log=new RotatingLog(filename+"_messages.log",null,SipStack.debug_level,SipStack.max_logsize*1024,SipStack.log_rotations,SipStack.rotation_scale,SipStack.rotation_time); } printLog("Date: "+DateFormat.formatHHMMSS(new Date()),LogLevel.HIGH); printLog("SipStack: "+SipStack.release,LogLevel.HIGH); printLog("new SipProvider(): "+toString(),LogLevel.HIGH); } /** Starts the transport services. */ private void startTrasport() { // start udp if (transport_udp) { try { if (host_ipaddr==null) udp=new UdpTransport(host_port,this); else udp=new UdpTransport(host_port,host_ipaddr,this); printLog("udp is up",LogLevel.MEDIUM); } catch (Exception e) { printException(e,LogLevel.HIGH); } } // start tcp if (transport_tcp) { try { if (host_ipaddr==null) tcp_server=new TcpServer(host_port,this); else tcp_server=new TcpServer(host_port,host_ipaddr,this); printLog("tcp is up",LogLevel.MEDIUM); } catch (Exception e) { printException(e,LogLevel.HIGH); } } //printLog("transport is up",LogLevel.MEDIUM); } /** Stops the transport services. */ private void stopTrasport() { // stop udp if (udp!=null) { printLog("udp is going down",LogLevel.LOWER); udp.halt(); udp=null; } // stop tcp if (tcp_server!=null) { printLog("tcp is going down",LogLevel.LOWER); tcp_server.halt(); tcp_server=null; } if (connections!=null) { printLog("connections are going down",LogLevel.LOWER); for (Enumeration e=connections.elements(); e.hasMoreElements(); ) { ConnectedTransport c=(ConnectedTransport)e.nextElement(); c.halt(); } connections=null; } } /** Stops the SipProviders. */ public void halt() { printLog("halt: SipProvider is going down",LogLevel.MEDIUM); stopTrasport(); listeners=new Hashtable(); exception_listeners=new HashSet(); } /** Parses a single line (loaded from the config file) */ public void parseLine(String line) { String attribute; Parser par; int index=line.indexOf("="); if (index>0) { attribute=line.substring(0,index).trim(); par=new Parser(line,index+1); } else { attribute=line; par=new Parser(""); } char[] delim={' ',','}; if (attribute.equals("via_addr")) { via_addr=par.getString(); return; } if (attribute.equals("host_port")) { host_port=par.getInt(); return; } if (attribute.equals("host_ifaddr")) { host_ifaddr=par.getString(); return; } if (attribute.equals("transport_protocols")) { transport_protocols=par.getWordArray(delim); return; } if (attribute.equals("nmax_connections")) { nmax_connections=par.getInt(); return; } if (attribute.equals("outbound_proxy")) { String soaddr=par.getString(); if (soaddr==null || soaddr.length()==0 || soaddr.equalsIgnoreCase(Configure.NONE) || soaddr.equalsIgnoreCase("NO-OUTBOUND")) outbound_proxy=null; else outbound_proxy=new SocketAddress(soaddr); return; } if (attribute.equals("log_all_packets")) { log_all_packets=(par.getString().toLowerCase().startsWith("y")); return; } // old parameters if (attribute.equals("host_addr")) System.err.println("WARNING: parameter 'host_addr' is no more supported; use 'via_addr' instead."); if (attribute.equals("all_interfaces")) System.err.println("WARNING: parameter 'all_interfaces' is no more supported; use 'host_iaddr' for setting a specific interface or let it undefined."); if (attribute.equals("use_outbound")) System.err.println("WARNING: parameter 'use_outbound' is no more supported; use 'outbound_proxy' for setting an outbound proxy or let it undefined."); if (attribute.equals("outbound_addr")) { System.err.println("WARNING: parameter 'outbound_addr' has been deprecated; use 'outbound_proxy=<host_addr>[:<host_port>]' instead."); outbound_addr=par.getString(); return; } if (attribute.equals("outbound_port")) { System.err.println("WARNING: parameter 'outbound_port' has been deprecated; use 'outbound_proxy=<host_addr>[:<host_port>]' instead."); outbound_port=par.getInt(); return; } } /** Converts the entire object into lines (to be saved into the config file) */ protected String toLines() { // currently not implemented.. return toString(); } /** Gets a String with the list of transport protocols. */ private String transportProtocolsToString() { String list=transport_protocols[0]; for (int i=1; i<transport_protocols.length; i++) list+="/"+transport_protocols[i]; return list; } // ************************** Public methods ************************* /** Gets via address. */ public String getViaAddress() { return via_addr; } /** Sets via address. */ /*public void setViaAddress(String addr) { via_addr=addr; }*/ /** Gets host port. */ public int getPort() { return host_port; } /** Whether binding the sip provider to all interfaces or only on the specified host address. */ public boolean isAllInterfaces() { return host_ipaddr==null; } /** Gets host interface IpAddress. */ public IpAddress getInterfaceAddress() { return host_ipaddr; } /** Gets array of transport protocols. */ public String[] getTransportProtocols() { return transport_protocols; } /** Gets the default transport protocol. */ public String getDefaultTransport() { return default_transport; } /** Gets the default transport protocol. */ public void setDefaultTransport(String proto) { default_transport=proto; } /** Sets rport support. */ public void setRport(boolean flag) { rport=flag; } /** Whether using rport. */ public boolean isRportSet() { return rport; } /** Sets 'force-rport' mode. */ public void setForceRport(boolean flag) { force_rport=flag; } /** Whether using 'force-rport' mode. */ public boolean isForceRportSet() { return force_rport; } /** Whether has outbound proxy. */ public boolean hasOutboundProxy() { return outbound_proxy!=null; } /** Gets the outbound proxy. */ public SocketAddress getOutboundProxy() { return outbound_proxy; } /** Sets the outbound proxy. Use 'null' for not using any outbound proxy. */ public void setOutboundProxy(SocketAddress soaddr) { outbound_proxy=soaddr; } /** Removes the outbound proxy. */ /*public void removeOutboundProxy() { setOutboundProxy(null); }*/ /** Gets the max number of (contemporary) open connections. */ public int getNMaxConnections() { return nmax_connections; } /** Sets the max number of (contemporary) open connections. */ public void setNMaxConnections(int n) { nmax_connections=n; } /** Gets event log. */ public Log getLog() { return event_log; } /** Returns the list (Hashtable) of active listener_IDs. */ public Hashtable getListeners() { return listeners; } /** Adds a new listener to the SipProvider for caputering any message in PROMISQUE mode. * It is the same as using method addSipProviderListener(SipProvider.PROMISQUE,listener). * <p/> * When capturing messages in promisque mode all messages are passed to the SipProviderListener * before passing them to the specific listener (if present). * <br/> Note that more that one SipProviderListener can be active in promisque mode * at the same time;in that case the same message is passed to all PROMISQUE * SipProviderListeners. * @param listener is the SipProviderListener. * @return It returns <i>true</i> if the SipProviderListener is added, * <i>false</i> if the listener_ID is already in use. */ public boolean addSipProviderPromisqueListener(SipProviderListener listener) { return addSipProviderListener(PROMISQUE,listener); } /** Adds a new listener to the SipProvider for caputering ANY message. * It is the same as using method addSipProviderListener(SipProvider.ANY,listener). * @param listener is the SipProviderListener. * @return It returns <i>true</i> if the SipProviderListener is added, * <i>false</i> if the listener_ID is already in use. */ public boolean addSipProviderListener(SipProviderListener listener) { return addSipProviderListener(ANY,listener); } /** Adds a new listener to the SipProvider. * @param id is the unique identifier for the messages which the listener * as to be associated to. It is used as key. * It can identify a method, a transaction, or a dialog. * Use SipProvider.ANY to capture all messages. * Use SipProvider.PROMISQUE if you want to capture all message in promisque mode * (letting other listeners to capture the same received messages). * @param listener is the SipProviderListener for this message id. * @return It returns <i>true</i> if the SipProviderListener is added, * <i>false</i> if the listener_ID is already in use. */ public boolean addSipProviderListener(Identifier id, SipProviderListener listener) { printLog("adding SipProviderListener: "+id,LogLevel.MEDIUM); boolean ret; Identifier key=id; if (listeners.containsKey(key)) { printWarning("trying to add a SipProviderListener with a id that is already in use.",LogLevel.HIGH); ret=false; } else { listeners.put(key,listener); ret=true; } if (listeners!=null) { String list=""; for (Enumeration e=listeners.keys(); e.hasMoreElements();) list+=e.nextElement()+", "; printLog(listeners.size()+" listeners: "+list,LogLevel.LOW); } return ret; } /** Removes a SipProviderListener. * @param id is the unique identifier used to select the listened messages. * @return It returns <i>true</i> if the SipProviderListener is removed, * <i>false</i> if the identifier is missed. */ public boolean removeSipProviderListener(Identifier id) { printLog("removing SipProviderListener: "+id,LogLevel.MEDIUM); boolean ret; Identifier key=id; if (!listeners.containsKey(key)) { printWarning("trying to remove a missed SipProviderListener.",LogLevel.HIGH); ret=false; } else { listeners.remove(key); ret=true; } if (listeners!=null) { String list=""; for (Enumeration e=listeners.keys(); e.hasMoreElements();) list+=e.nextElement()+", "; printLog(listeners.size()+" listeners: "+list,LogLevel.LOW); } return ret; } /** Sets the SipProviderExceptionListener. * The SipProviderExceptionListener is the listener for all exceptions * thrown by the SipProviders. * @param e_listener is the SipProviderExceptionListener. * @return It returns <i>true</i> if the SipProviderListener has been correctly set, * <i>false</i> if the SipProviderListener was already set. */ public boolean addSipProviderExceptionListener(SipProviderExceptionListener e_listener) { printLog("adding SipProviderExceptionListener",LogLevel.MEDIUM); if (exception_listeners.contains(e_listener)) { printWarning("trying to add an already present SipProviderExceptionListener.",LogLevel.HIGH); return false; } else { exception_listeners.add(e_listener); return true; } } /** Removes a SipProviderExceptionListener. * @param e_listener is the SipProviderExceptionListener. * @return It returns <i>true</i> if the SipProviderExceptionListener has been correctly removed, * <i>false</i> if the SipProviderExceptionListener is missed. */ public boolean removeSipProviderExceptionListener(SipProviderExceptionListener e_listener) { printLog("removing SipProviderExceptionListener",LogLevel.MEDIUM); if (!exception_listeners.contains(e_listener)) { printWarning("trying to remove a missed SipProviderExceptionListener.",LogLevel.HIGH); return false; } else { exception_listeners.remove(e_listener); return true; } } /** Sends a Message, specifing the transport portocol, nexthop address and port. * <p> This is a low level method and * forces the message to be routed to a specific nexthop address, port and transport, * regardless whatever the Via, Route, or request-uri, address to. * <p> * In case of connection-oriented transport, the connection is selected as follows: * <br> - if an existing connection is found matching the destination * end point (socket), such connection is used, otherwise * <br> - a new connection is established * * @return It returns a Connection in case of connection-oriented delivery * (e.g. TCP) or null in case of connection-less delivery (e.g. UDP) */ public ConnectionIdentifier sendMessage(Message msg, String proto, String dest_addr, int dest_port, int ttl) { if (log_all_packets || msg.getLength()>MIN_MESSAGE_LENGTH) printLog("Resolving host address '"+dest_addr+"'",LogLevel.MEDIUM); try { IpAddress dest_ipaddr=IpAddress.getByName(dest_addr); return sendMessage(msg,proto,dest_ipaddr,dest_port,ttl); } catch (Exception e) { printException(e,LogLevel.HIGH); return null; } } /** Sends a Message, specifing the transport portocol, nexthop address and port. */ private ConnectionIdentifier sendMessage(Message msg, String proto, IpAddress dest_ipaddr, int dest_port, int ttl) { ConnectionIdentifier conn_id=new ConnectionIdentifier(proto,dest_ipaddr,dest_port); if (log_all_packets || msg.getLength()>MIN_MESSAGE_LENGTH) printLog("Sending message to "+conn_id,LogLevel.MEDIUM); if (transport_udp && proto.equals(PROTO_UDP)) { // UDP //printLog("using UDP",LogLevel.LOW); conn_id=null; try { // if (ttl>0 && multicast_address) do something? udp.sendMessage(msg,dest_ipaddr,dest_port); } catch (IOException e) { printException(e,LogLevel.HIGH); return null; } } else if (transport_tcp && proto.equals(PROTO_TCP)) { // TCP //printLog("using TCP",LogLevel.LOW); if (!connections.containsKey(conn_id)) { printLog("no active connection found matching "+conn_id,LogLevel.MEDIUM); printLog("open "+proto+" connection to "+dest_ipaddr+":"+dest_port,LogLevel.MEDIUM); TcpTransport conn=null; try { conn=new TcpTransport(dest_ipaddr,dest_port,this); } catch (Exception e) { printLog("connection setup FAILED",LogLevel.HIGH); return null; } printLog("connection "+conn+" opened",LogLevel.HIGH); addConnection(conn); } else { printLog("active connection found matching "+conn_id,LogLevel.MEDIUM); } ConnectedTransport conn=(ConnectedTransport)connections.get(conn_id); if (conn!=null) { printLog("sending data through conn "+conn,LogLevel.MEDIUM); try { conn.sendMessage(msg); conn_id=new ConnectionIdentifier(conn); } catch (IOException e) { printException(e,LogLevel.HIGH); return null; } } else { // this point has not to be reached printLog("ERROR: conn "+conn_id+" not found: abort.",LogLevel.MEDIUM); return null; } } else { // otherwise printWarning("Unsupported protocol ("+proto+"): Message discarded",LogLevel.HIGH); return null; } // logs String dest_addr=dest_ipaddr.toString(); printMessageLog(proto,dest_addr,dest_port,msg.getLength(),msg,"sent"); return conn_id; } /** Sends the message <i>msg</i>. * <p> * The destination for the request is computed as follows: * <br> - if <i>outbound_addr</i> is set, <i>outbound_addr</i> and * <i>outbound_port</i> are used, otherwise * <br> - if message has Route header with lr option parameter (i.e. RFC3261 compliant), * the first Route address is used, otherwise * <br> - the request's Request-URI is considered. * <p> * The destination for the response is computed based on the sent-by parameter in * the Via header field (RFC3261 compliant) * <p> * As transport it is used the protocol specified in the 'via' header field * <p> * In case of connection-oriented transport: * <br> - if an already established connection is found matching the destination * end point (socket), such connection is used, otherwise * <br> - a new connection is established * * @return Returns a ConnectionIdentifier in case of connection-oriented delivery * (e.g. TCP) or null in case of connection-less delivery (e.g. UDP) */ public ConnectionIdentifier sendMessage(Message msg) { printLog("Sending message:\r\n"+msg.toString(),LogLevel.LOWER); // select the transport protocol ViaHeader via=msg.getViaHeader(); String proto=via.getProtocol().toLowerCase(); printLog("using transport "+proto,LogLevel.MEDIUM); // select the destination address and port String dest_addr=null; int dest_port=0; int ttl=0; if (msg.isRequest()) { // REQUESTS if (outbound_proxy!=null) { dest_addr=outbound_proxy.getAddress().toString(); dest_port=outbound_proxy.getPort(); } else { if (msg.hasRouteHeader() && msg.getRouteHeader().getNameAddress().getAddress().hasLr()) { SipURL url=msg.getRouteHeader().getNameAddress().getAddress(); dest_addr=url.getHost(); dest_port=url.getPort(); } else { SipURL url=msg.getRequestLine().getAddress(); dest_addr=url.getHost(); dest_port=url.getPort(); if (url.hasMaddr()) { dest_addr=url.getMaddr(); if (url.hasTtl()) ttl=url.getTtl(); // update the via header by adding maddr and ttl params via.setMaddr(dest_addr); if (ttl>0) via.setTtl(ttl); msg.removeViaHeader(); msg.addViaHeader(via); } } } } else { // RESPONSES SipURL url=via.getSipURL(); if (via.hasReceived()) dest_addr=via.getReceived(); else dest_addr=url.getHost(); if (via.hasRport()) dest_port=via.getRport(); if (dest_port<=0) dest_port=url.getPort(); } if (dest_port<=0) dest_port=SipStack.default_port; return sendMessage(msg,proto,dest_addr,dest_port,ttl); } /** Sends the message <i>msg</i> using the specified connection. */ public ConnectionIdentifier sendMessage(Message msg, ConnectionIdentifier conn_id) { if (log_all_packets || msg.getLength()>MIN_MESSAGE_LENGTH) printLog("Sending message through conn "+conn_id,LogLevel.HIGH); printLog("message:\r\n"+msg.toString(),LogLevel.LOWER); if (conn_id!=null && connections.containsKey(conn_id)) { // connection exists printLog("active connection found matching "+conn_id,LogLevel.MEDIUM); ConnectedTransport conn=(ConnectedTransport)connections.get(conn_id); try { conn.sendMessage(msg); // logs //String proto=conn.getProtocol(); String proto=conn.getProtocol(); String dest_addr=conn.getRemoteAddress().toString(); int dest_port=conn.getRemotePort(); printMessageLog(proto,dest_addr,dest_port,msg.getLength(),msg,"sent"); return conn_id; } catch (Exception e) { printException(e,LogLevel.HIGH); } } //else printLog("no active connection found matching "+conn_id,LogLevel.MEDIUM); return sendMessage(msg); } /** Processes the message received. * It is called each time a new message is received by the transport layer, and * it performs the actual message processing. */ protected void processReceivedMessage(Message msg) { try { // logs printMessageLog(msg.getTransportProtocol(),msg.getRemoteAddress(),msg.getRemotePort(),msg.getLength(),msg,"received"); // discard too short messages if (msg.getLength()<=2) { if (log_all_packets) printLog("message too short: discarded\r\n",LogLevel.LOW); return; } // discard non-SIP messages String first_line=msg.getFirstLine(); if (first_line==null || first_line.toUpperCase().indexOf("SIP/2.0")<0) { if (log_all_packets) printLog("NOT a SIP message: discarded\r\n",LogLevel.LOW); return; } printLog("received new SIP message",LogLevel.HIGH); printLog("message:\r\n"+msg.toString(),LogLevel.LOWER); // if a request, handle "received" and "rport" parameters if (msg.isRequest()) { ViaHeader vh=msg.getViaHeader(); boolean via_changed=false; String src_addr=msg.getRemoteAddress(); int src_port=msg.getRemotePort(); String via_addr=vh.getHost(); int via_port=vh.getPort(); if (via_port<=0) via_port=SipStack.default_port; if (!via_addr.equals(src_addr)) { vh.setReceived(src_addr); via_changed=true; } if (vh.hasRport()) { vh.setRport(src_port); via_changed=true; } else { if (force_rport && via_port!=src_port) { vh.setRport(src_port); via_changed=true; } } if (via_changed) { msg.removeViaHeader(); msg.addViaHeader(vh); } } // is there any listeners? if (listeners==null || listeners.size()==0) { printLog("no listener found: meesage discarded.",LogLevel.HIGH); return; } // try to look for a UA in promisque mode if (listeners.containsKey(PROMISQUE)) { printLog("message passed to uas: "+PROMISQUE,LogLevel.MEDIUM); ((SipProviderListener)listeners.get(PROMISQUE)).onReceivedMessage(this,msg); } // after the callback check if the message is still valid if (!msg.isRequest() && !msg.isResponse()) { printLog("No valid SIP message: message discarded.",LogLevel.HIGH); return; } // this was the promisque listener; now keep on looking for a tighter listener.. // try to look for a transaction Identifier key=msg.getTransactionId(); printLog("DEBUG: transaction-id: "+key,LogLevel.MEDIUM); if (listeners.containsKey(key)) { printLog("message passed to transaction: "+key,LogLevel.MEDIUM); ((SipProviderListener)listeners.get(key)).onReceivedMessage(this,msg); return; } // try to look for a dialog key=msg.getDialogId(); printLog("DEBUG: dialog-id: "+key,LogLevel.MEDIUM); if (listeners.containsKey(key)) { printLog("message passed to dialog: "+key,LogLevel.MEDIUM); ((SipProviderListener)listeners.get(key)).onReceivedMessage(this,msg); return; } // try to look for a UAS key=msg.getMethodId(); if (listeners.containsKey(key)) { printLog("message passed to uas: "+key,LogLevel.MEDIUM); ((SipProviderListener)listeners.get(key)).onReceivedMessage(this,msg); return; } // try to look for a default UA if (listeners.containsKey(ANY)) { printLog("message passed to uas: "+ANY,LogLevel.MEDIUM); ((SipProviderListener)listeners.get(ANY)).onReceivedMessage(this,msg); return; } // if we are here, no listener_ID matched.. printLog("No SipListener found matching that message: message DISCARDED",LogLevel.HIGH); //printLog("Pending SipProviderListeners= "+getListeners().size(),3); printLog("Pending SipProviderListeners= "+listeners.size(),LogLevel.MEDIUM); } catch (Exception e) { printWarning("Error handling a new incoming message",LogLevel.HIGH); printException(e,LogLevel.MEDIUM); if (exception_listeners==null || exception_listeners.size()==0) { System.err.println("Error handling a new incoming message"); e.printStackTrace(); } else { for (Iterator i=exception_listeners.iterator(); i.hasNext(); ) try { ((SipProviderExceptionListener)i.next()).onMessageException(msg,e); } catch (Exception e2) { printWarning("Error handling handling the Exception",LogLevel.HIGH); printException(e2,LogLevel.MEDIUM); } } } } /** Adds a new Connection */ private void addConnection(ConnectedTransport conn) { ConnectionIdentifier conn_id=new ConnectionIdentifier(conn); if (connections.containsKey(conn_id)) { // remove the previous connection printLog("trying to add the already established connection "+conn_id,LogLevel.HIGH); printLog("connection "+conn_id+" will be replaced",LogLevel.HIGH); ConnectedTransport old_conn=(ConnectedTransport)connections.get(conn_id); old_conn.halt(); connections.remove(conn_id); } else if (connections.size()>=nmax_connections) { // remove the older unused connection printLog("reached the maximum number of connection: removing the older unused connection",LogLevel.HIGH); long older_time=System.currentTimeMillis(); ConnectionIdentifier older_id=null; for (Enumeration e=connections.elements(); e.hasMoreElements(); ) { ConnectedTransport co=(ConnectedTransport)e.nextElement(); if (co.getLastTimeMillis()<older_time) older_id=new ConnectionIdentifier(co); } if (older_id!=null) removeConnection(older_id); } connections.put(conn_id,conn); conn_id=new ConnectionIdentifier(conn); conn=(ConnectedTransport)connections.get(conn_id); // DEBUG log: printLog("active connenctions:",LogLevel.LOW); for (Enumeration e=connections.keys(); e.hasMoreElements(); ) { ConnectionIdentifier id=(ConnectionIdentifier)e.nextElement(); printLog("conn-id="+id+": "+((ConnectedTransport)connections.get(id)).toString(),LogLevel.LOW); } } /** Removes a Connection */ private void removeConnection(ConnectionIdentifier conn_id) { if (connections.containsKey(conn_id)) { ConnectedTransport conn=(ConnectedTransport)connections.get(conn_id); conn.halt(); connections.remove(conn_id); // DEBUG log: printLog("active connenctions:",LogLevel.LOW); for (Enumeration e=connections.elements(); e.hasMoreElements(); ) { ConnectedTransport co=(ConnectedTransport)e.nextElement(); printLog("conn "+co.toString(),LogLevel.LOW); } } } //************************* Callback methods ************************* /** When a new SIP message is received. */ public void onReceivedMessage(Transport transport, Message msg) { processReceivedMessage(msg); } /** When Transport terminates. */ public void onTransportTerminated(Transport transport, Exception error) { printLog("transport "+transport+" terminated",LogLevel.MEDIUM); if (transport.getProtocol().equals(PROTO_TCP)) { ConnectionIdentifier conn_id=new ConnectionIdentifier((ConnectedTransport)transport); removeConnection(conn_id); } if (error!=null) printException(error,LogLevel.HIGH); } /** When a new incoming Connection is established */ public void onIncomingConnection(TcpServer tcp_server, TcpSocket socket) { printLog("incoming connection from "+socket.getAddress()+":"+socket.getPort(),LogLevel.MEDIUM); ConnectedTransport conn=new TcpTransport(socket,this); printLog("tcp connection "+conn+" opened",LogLevel.MEDIUM); addConnection(conn); } /** When TcpServer terminates. */ public void onServerTerminated(TcpServer tcp_server, Exception error) { printLog("tcp server "+tcp_server+" terminated",LogLevel.MEDIUM); } //************************** Other methods *************************** /** Picks a fresh branch value. * The branch ID MUST be unique across space and time for * all requests sent by the UA. * The branch ID always begin with the characters "z9hG4bK". These * 7 characters are used by RFC 3261 as a magic cookie. */ public static String pickBranch() { //String str=Long.toString(Math.abs(Random.nextLong()),16); //if (str.length()<5) str+="00000"; //return "z9hG4bK"+str.substring(0,5); return "z9hG4bK"+Random.nextNumString(5); } /** Picks an unique branch value based on a SIP message. * This value could also be used as transaction ID */ public String pickBranch(Message msg) { StringBuffer sb=new StringBuffer(); sb.append(msg.getRequestLine().getAddress().toString()); sb.append(getViaAddress()+getPort()); ViaHeader top_via=msg.getViaHeader(); if (top_via.hasBranch()) sb.append(top_via.getBranch()); else { sb.append(top_via.getHost()+top_via.getPort()); sb.append(msg.getCSeqHeader().getSequenceNumber()); sb.append(msg.getCallIdHeader().getCallId()); sb.append(msg.getFromHeader().getTag()); sb.append(msg.getToHeader().getTag()); } //return "z9hG4bK"+(new MD5(unique_str)).asHex().substring(0,9); return "z9hG4bK"+(new SimpleDigest(5,sb.toString())).asHex(); } /** Picks a new tag. * A tag MUST be globally unique and cryptographically random * with at least 32 bits of randomness. A property of this selection * requirement is that a UA will place a different tag into the From * header of an INVITE than it would place into the To header of the * response to the same INVITE. This is needed in order for a UA to * invite itself to a session. */ public static String pickTag() { //String str=Long.toString(Math.abs(Random.nextLong()),16); //if (str.length()<8) str+="00000000"; //return str.substring(0,8); return "z9hG4bK"+Random.nextNumString(8); } /** Picks a new tag. The tag is generated uniquely based on message <i>req</i>. * This tag can be generated for responses in a stateless * manner - in a manner that will generate the same tag for the * same request consistently. */ public static String pickTag(Message req) { //return String.valueOf(tag_generator++); //return (new MD5(request.toString())).asHex().substring(0,8); return (new SimpleDigest(8,req.toString())).asHex(); } /** Picks a new call-id. * The call-id is a globally unique * identifier over space and time. It is implemented in the * form "localid@host". Call-id must be considered case-sensitive and is * compared byte-by-byte. */ public String pickCallId() { //String str=Long.toString(Math.abs(Random.nextLong()),16); //if (str.length()<12) str+="000000000000"; //return str.substring(0,12)+"@"+getViaAddress(); return Random.nextNumString(12)+"@"+getViaAddress(); } /** picks an initial CSeq */ public static int pickInitialCSeq() { return 1; } /** (<b>Deprecated</b>) Constructs a NameAddress based on an input string. * The input string can be a: * <br> - <i>user</i> name, * <br> - <i>user@address</i> url, * <br> - <i>"Name" &lt;sip:user@address&gt;</i> address, * <p> * In the former case, * a SIP URL is costructed using the outbound proxy as host address if present, * otherwise the local via address is used. */ public NameAddress completeNameAddress(String str) { if (str.indexOf("<sip:")>=0) return new NameAddress(str); else { SipURL url=completeSipURL(str); return new NameAddress(url); } } /** Constructs a SipURL based on an input string. */ private SipURL completeSipURL(String str) { // in case it is passed only the 'user' field, add '@'<outbound_proxy>[':'<outbound_port>] if (!str.startsWith("sip:") && str.indexOf("@")<0 && str.indexOf(".")<0 && str.indexOf(":")<0) { // may be it is just the user name.. String url="sip:"+str+"@"; if (outbound_proxy!=null) { url+=outbound_proxy.getAddress().toString(); int port=outbound_proxy.getPort(); if (port>0 && port!=SipStack.default_port) url+=":"+port; } else { url+=via_addr; if (host_port>0 && host_port!=SipStack.default_port) url+=":"+host_port; } return new SipURL(url); } else return new SipURL(str); } /** Constructs a SipURL for the given <i>username</i> on the local SIP UA. * If <i>username</i> is null, only host address and port are used. */ /*public SipURL getSipURL(String user_name) { return new SipURL(user_name,via_addr,(host_port!=SipStack.default_port)?host_port:-1); }*/ //******************************* Logs ******************************* /** Gets a String value for this object */ public String toString() { if (host_ipaddr==null) return host_port+"/"+transportProtocolsToString(); else return host_ipaddr.toString()+":"+host_port+"/"+transportProtocolsToString(); } /** Adds a new string to the default Log */ private final void printLog(String str, int level) { if (event_log!=null) { String provider_id=(host_ipaddr==null)? Integer.toString(host_port) : host_ipaddr.toString()+":"+host_port; event_log.println("SipProvider-"+provider_id+": "+str,level+SipStack.LOG_LEVEL_TRANSPORT); } } /** Adds a WARNING to the default Log */ private final void printWarning(String str, int level) { printLog("WARNING: "+str,level); } /** Adds the Exception message to the default Log */ private final void printException(Exception e, int level) { if (event_log!=null) event_log.printException(e,level+SipStack.LOG_LEVEL_TRANSPORT); } /** Adds the SIP message to the messageslog */ private final void printMessageLog(String proto, String addr, int port, int len, Message msg, String str) { if (log_all_packets || len>=MIN_MESSAGE_LENGTH) { if (message_log!=null) { message_log.printPacketTimestamp(proto,addr,port,len,str+"\r\n"+msg.toString()+"-----End-of-message-----\r\n",1); } if (event_log!=null) { String first_line=msg.getFirstLine(); if (first_line!=null) first_line=first_line.trim(); else first_line="NOT a SIP message"; event_log.print("\r\n"); event_log.printPacketTimestamp(proto,addr,port,len,first_line+", "+str,1); event_log.print("\r\n"); } } } }
ging/isabel
components/gateway/GWSIP/mjsip_1.6/src/org/zoolu/sip/provider/SipProvider.java
Java
agpl-3.0
47,764
<?php namespace Page\Responsive; use Behat\Mink\Driver\SahiDriver; use Behat\Mink\Element\NodeElement; use Element\MultipleElement; class Detail extends \Page\Emotion\Detail { /** * Returns an array of all css selectors of the element/page * @return array */ public function getCssSelectors() { return array( 'productRating' => 'div.product--rating-container .product--rating > meta', 'productRatingCount' => 'div.product--rating-container .product--rating > span', 'configuratorForm' => 'form.configurator--form', 'notificationForm' => 'form.notification--form', 'notificationSubmit' => '.notification--button', 'voteForm' => 'form.review--form' ); } protected $configuratorTypes = array( 'table' => 'configurator--form', 'standard' => 'configurator--form upprice--form', 'select' => 'configurator--form selection--form' ); /** * Helper function how to read the evaluation from the evaluation element * @param NodeElement $element * @return string */ protected function getEvaluation($element) { $evaluation = $element->getAttribute('content'); $evaluation = floatval($evaluation); $evaluation*= 2; return (string) $evaluation; } /** * Puts the current article <quantity> times to basket * @param int $quantity */ public function toBasket($quantity = 1) { $this->fillField('sQuantity', $quantity); $this->pressButton('In den Warenkorb'); if ($this->getSession()->getDriver() instanceof SahiDriver) { $this->clickLink('Warenkorb anzeigen'); } } protected function checkRating(MultipleElement $articleEvaluations, $average) { $locators = array('productRating', 'productRatingCount'); $elements = \Helper::findElements($this, $locators); $check = array(); foreach($elements as $locator => $element) { switch($locator) { case 'productRating': $rating = $element->getAttribute('content'); $rating = floatval($rating); $check[$locator] = array($rating, $average); break; case 'productRatingCount': $check[$locator] = array($element->getText(), count($articleEvaluations)); break; } } $check = \Helper::floatArray($check); $result = \Helper::checkArray($check); if ($result !== true) { $message = sprintf('There was a different value of the evaluation! (%s: "%s" instead of %s)', $result, $check[$result][0], $check[$result][1]); \Helper::throwException($message); } } /** * Fills the notification form and submits it * @param string $email */ public function submitNotification($email) { $data = array( array( 'field' => 'sNotificationEmail', 'value' => $email ) ); \Helper::fillForm($this, 'notificationForm', $data); $locators = array('notificationSubmit'); $elements = \Helper::findElements($this, $locators); $elements['notificationSubmit']->press(); } }
Zwilla/shopware
tests/Mink/features/bootstrap/Page/Responsive/Detail.php
PHP
agpl-3.0
3,393
# -- # Kernel/Language/en.pm - provides en_US languag translation # Copyright (C) 2001-2014 OTRS AG, http://otrs.com/ # -- # This software comes with ABSOLUTELY NO WARRANTY. For details, see # the enclosed file COPYING for license information (AGPL). If you # did not receive this file, see http://www.gnu.org/licenses/agpl.txt. # -- package Kernel::Language::en; use strict; use warnings; sub Data { my $Self = shift; # http://en.wikipedia.org/wiki/Date_and_time_notation_by_country#United_States # month-day-year (e.g., "12/31/99") # $$START$$ # Last translation file sync: Thu Apr 9 10:12:50 2009 # possible charsets $Self->{Charset} = ['us-ascii', 'UTF-8', 'iso-8859-1', 'iso-8859-15', ]; # date formats (%A=WeekDay;%B=LongMonth;%T=Time;%D=Day;%M=Month;%Y=Year;) $Self->{DateFormat} = '%M/%D/%Y %T'; $Self->{DateFormatLong} = '%T - %M/%D/%Y'; $Self->{DateFormatShort} = '%M/%D/%Y'; $Self->{DateInputFormat} = '%M/%D/%Y'; $Self->{DateInputFormatLong} = '%M/%D/%Y - %T'; $Self->{Separator} = ','; # maybe nothing ... or help texts $Self->{Translation} = { 'May_long' => 'May', 'History::Move' => 'Ticket moved into Queue "%s" (%s) from Queue "%s" (%s).', 'History::TypeUpdate' => 'Updated Type to %s (ID=%s).', 'History::ServiceUpdate' => 'Updated Service to %s (ID=%s).', 'History::SLAUpdate' => 'Updated SLA to %s (ID=%s).', 'History::NewTicket' => 'New Ticket [%s] created (Q=%s;P=%s;S=%s).', 'History::FollowUp' => 'FollowUp for [%s]. %s', 'History::SendAutoReject' => 'AutoReject sent to "%s".', 'History::SendAutoReply' => 'AutoReply sent to "%s".', 'History::SendAutoFollowUp' => 'AutoFollowUp sent to "%s".', 'History::Forward' => 'Forwarded to "%s".', 'History::Bounce' => 'Bounced to "%s".', 'History::SendAnswer' => 'Email sent to "%s".', 'History::SendAgentNotification' => '"%s"-notification sent to "%s".', 'History::SendCustomerNotification' => 'Notification sent to "%s".', 'History::EmailAgent' => 'Email sent to customer.', 'History::EmailCustomer' => 'Added email. %s', 'History::PhoneCallAgent' => 'Agent called customer.', 'History::PhoneCallCustomer' => 'Customer called us.', 'History::AddNote' => 'Added note (%s)', 'History::Lock' => 'Locked ticket.', 'History::Unlock' => 'Unlocked ticket.', 'History::TimeAccounting' => '%s time unit(s) accounted. Now total %s time unit(s).', 'History::Remove' => '%s', 'History::CustomerUpdate' => 'Updated: %s', 'History::PriorityUpdate' => 'Changed priority from "%s" (%s) to "%s" (%s).', 'History::OwnerUpdate' => 'New owner is "%s" (ID=%s).', 'History::ResponsibleUpdate' => 'New responsible is "%s" (ID=%s).', 'History::LoopProtection' => 'Loop-Protection! No auto-response sent to "%s".', 'History::Misc' => '%s', 'History::SetPendingTime' => 'Updated: %s', 'History::StateUpdate' => 'Old: "%s" New: "%s"', 'History::TicketDynamicFieldUpdate' => 'Updated: %s=%s;%s=%s;', 'History::WebRequestCustomer' => 'Customer request via web.', 'History::TicketLinkAdd' => 'Added link to ticket "%s".', 'History::TicketLinkDelete' => 'Deleted link to ticket "%s".', 'History::Subscribe' => 'Added subscription for user "%s".', 'History::Unsubscribe' => 'Removed subscription for user "%s".', 'History::SystemRequest' => 'System Request (%s).', 'History::EscalationResponseTimeNotifyBefore' => 'Escalation response time forewarned', 'History::EscalationUpdateTimeNotifyBefore' => 'Escalation update time forewarned', 'History::EscalationSolutionTimeNotifyBefore' => 'Escalation solution time forewarned', 'History::EscalationResponseTimeStart' => 'Escalation response time in effect', 'History::EscalationUpdateTimeStart' => 'Escalation update time in effect', 'History::EscalationSolutionTimeStart' => 'Escalation solution time in effect', 'History::EscalationResponseTimeStop' => 'Escalation response time finished', 'History::EscalationUpdateTimeStop' => 'Escalation update time finished', 'History::EscalationSolutionTimeStop' => 'Escalation solution time finished', 'History::ArchiveFlagUpdate' => 'Archive state changed: "%s"', #CustomerUser fields 'Title{CustomerUser}' => 'Title', 'Firstname{CustomerUser}' => 'First name', 'Lastname{CustomerUser}' => 'Last name', 'Username{CustomerUser}' => 'Username', 'Email{CustomerUser}' => 'E-mail address', 'CustomerID{CustomerUser}' => 'Customer ID', 'Phone{CustomerUser}' => 'Phone', 'Fax{CustomerUser}' => 'Fax', 'Mobile{CustomerUser}' => 'Cellphone', 'Street{CustomerUser}' => 'Street', 'Zip{CustomerUser}' => 'ZIP code', 'City{CustomerUser}' => 'City', 'Country{CustomerUser}' => 'Country', 'Comment{CustomerUser}' => 'Comment', #User field 'Title{user}' => 'Title', }; # $$STOP$$ return; } 1;
rahulvador/CoreHD
Kernel/Language/en.pm
Perl
agpl-3.0
5,251
/******************************************************************************* Toutes les fonctions liées à la page pour le gestion des cadres des options, demande d'un nouveau texte… *******************************************************************************/ //cette fonction permet d'avoir un nouveau texte var texte_en_cours = ""; //c'est le texte original comme il est obtenu var le_texte = ""; //c'est le texte avec les corrections typo validées dans les options var text_nb; var text_source; function new_text(a) { //on réinitialise les variables lost_time = 0; nb_err = 0; nb_fois_err = 0; t_car = new Array; list_f = new Array; j = 0; g=0; posghost=0; stop_ghost = true; ghost_is_start = false; curseur_err_bol = false; val_result("reset"); if(a=="new") { // requète javascript pour récupérer numéro###credit###texte var req = "new_text.php?t="+text_nb+"&l="+document.getElementById("lang").value; if (document.getElementById("methode").value == "number") { var prompt_result = prompt("Indiquer ici le numéro du texte que vous souhaitez charger.",text_nb); if (prompt_result == null) return; req += "&force="+prompt_result; } var req_text = request(req,"text_nmbr"); var reg = new RegExp("###","g"); var t_get = req_text.split(reg); texte_en_cours = t_get[2]; text_source = t_get[1]; text_nb = t_get[0]; clean_ghost(); } document.getElementById("txt").value = ""; //on efface le texte précédement tapé val=document.getElementById("txt").value; options(); //on passe par les options pour le mise en forme typographique et l'affichage du texte document.getElementById("err").style.visibility = "hidden"; //on cache le champ d'erreur (pas vraiment utile car on ne peut pas finir sur une erreur) document.getElementById("txt").style.backgroundColor = "#f0fff0"; //on met le fond de la zone de frappe en vert document.getElementById("d_replay").style.visibility = "hidden"; //on cache le bouton de replay document.getElementById("txt").readOnly = false; //et en écriture document.getElementById("resultats").innerHTML = ""; //on efface les résultats de la session précédente document.getElementById("resultats").style.backgroundColor = "inherit"; //on met le fond en blanc document.getElementById("resultats").style.border = "none"; //et sans bordure pour rendre le tout invisible if (text_source.length > 45) var txt_link = text_source.substr(0,42)+"…"; else var txt_link = text_source; document.getElementById("text_nmbr").innerHTML = "Texte nº"+text_nb+' — source : <a title="'+text_source+'" href="'+text_source+'">'+txt_link+"</a>"; } //cette fonction permet de faire la mise en forme typographique et d'afficher le texte modifié function options() { le_texte = texte_en_cours; //on passe par une autre variable pour conserver le texte original //apostrophes if (document.getElementById("apo_typ").checked == false) { le_texte = le_texte.replace(/’/g,"'"); } //majuscules accentuées if (document.getElementById("maj_acc").checked == false) { le_texte = le_texte.replace(/[ÉÈÊË]/g,"E"); le_texte = le_texte.replace(/À/g,"A"); //on peut bien entendu en ajouter d'autres } //ligatures æ, Æ, œ et Œ if (document.getElementById("ligat").checked == false) { le_texte = le_texte.replace(/œ/g,"oe"); le_texte = le_texte.replace(/Œ/g,"Oe"); le_texte = le_texte.replace(/æ/g,"ae"); le_texte = le_texte.replace(/Æ/g,"Ae"); } //guillemets français « » if (document.getElementById("quote_fr").checked == false) { le_texte = le_texte.replace(/« /g,'"'); le_texte = le_texte.replace(/ »/g,'"'); } //espaces insécables if (document.getElementById("no_brk_spc").checked == false) { le_texte = le_texte.replace(/ /g," "); } //points de suspension if (document.getElementById("pds").checked == false) le_texte = le_texte.replace(/…/g,'...'); // tiret quadratin if (document.getElementById("tiret").checked == false) le_texte = le_texte.replace(/[–—]/g,"-"); var tt = new Array; tt = le_texte.split(""); //on split le texte pour récupérer tous les caractères indépendament // on ajoute les espaces incécables en même temps qu'on englobe chaque caractères dans un span pour le curseur for (var i=0 ; i<le_texte.length ; i++) { if (document.getElementById("no_brk_spc_display").checked == true && tt[i] == " ") tt[i] = '<span style="background-color:#cccccc"><span id="car'+(i+1)+'">'+tt[i]+'</span></span>'; else tt[i] = '<span id="car'+(i+1)+'">'+tt[i]+'</span>'; } // et on met tout le texte dans la zone de lecture en recolant le tout document.getElementById("rd_txt").innerHTML = '<span id="car-3"></span><span id="car-2"></span><span id="car-1"></span><span id="car0"></span>'+tt.join(""); if (document.getElementById("curseur_actif").checked) //si l'utilisateur en veut document.getElementById("car1").style.backgroundColor = cur_col; //on affiche le curseur jaune document.getElementById("txt").focus(); //on donne le focus à la zone de frappe } //cette fonction permet de faire une mise en forme des temps pour les résultats, utile dans la fonction calcul() function form_time(time) { var min = time.getMinutes(); var sec = time.getSeconds(); var mil = time.getMilliseconds(); mil = Math.round(mil/100); return min +" min. "+ sec +","+ mil +" s"; } //cette fonction permet de faire les calculs de la session var mpm_session=0; //c'est la vitesse en mpm (pour l'enregistrer avec le fantôme) var debug=false; function calcul() { var dt = new Array; //tableau des Δt(i) for (var i=0;i<nb_car-1;i++) { if (!isNaN(t_car[i+1]) && !isNaN(t_car[i])) dt[i] = t_car[i+1]-t_car[i]; // on récupère les interval de temps entre chaque frappe else { if (isNaN(t_car[i])) { dt[i] = t_car[i+1]-((t_car[i-1]+t_car[i+1])/2); // on récupère les interval de temps entre chaque frappe } else if (isNaN(t_car[i+1])) { dt[i] = ((t_car[i]+t_car[i+2])/2)-t_car[i]; // on récupère les interval de temps entre chaque frappe } } } // on calcul le temps entre le 1er et le dernier caractère tapé // la particularité c'est que quand on revient au premier pendant la frappe, le temps du caractère 0 (le premier en fait) est réinitialisé, on peut donc recommencé dans recharger de texte par exemple si on le souhaite var total_time = t_car[nb_car-1] - t_car[0]; //on calcul les différentes statistiques de la session var cps = Math.round(100000 * nb_car / total_time)/100; //coups par seconde var mpm = Math.round(cps * 600 / lettre_par_mot)/10; //mots par minute mpm_session = mpm; //on sauvegarde temporairement pour la donner au fantôme si on enregistre la session var precision = Math.round(1000*(nb_car-nb_err)/nb_car)/10; //précision //moyenne de la somme des fréquence de frappe //---------------------------------------------- var msf = 0; for (var i=0 ; i<nb_car-1 ; i++) { msf = msf + 1 / (dt[i]/1000); } msf = msf/(nb_car-1); var fl = Math.round(cps/msf*10000)/100; // et la fluidité « fl » qui en découle //------------------------------------------------ // la vitesse (en mots par minute) qui aurait pu être atteinte sans les erreurs et le pourcentage de temps perdu var mpm_top = Math.round((1000 * nb_car / (total_time-lost_time))* 600 / lettre_par_mot)/10; var lost_time_percent = Math.round(1000*lost_time/total_time)/10; if (debug) { alert("lost_time"+lost_time); alert("lost_time_percent"+lost_time_percent); } // le temps perdu et le temps total au format texte lost_time = form_time(new Date(lost_time)); total_time = form_time(new Date(total_time)); // on lance l'affichage des statistiques de la session aff_session(cps,mpm,precision,fl,mpm_top,lost_time_percent,lost_time,total_time); } //cette fonction affiche des résultats de la session function aff_session(cps,mpm,precision,fl,mpm_top,lost_time_percent,lost_time,total_time) { var result = ""; var nl = "<br/>"; if (document.getElementById("short_aff").checked == false) { // juste pour l'orthographe //------------------------------------ if (nb_fois_err >= 2) var txt1 = nb_fois_err+" erreurs"; else var txt1 = nb_fois_err+" erreur"; if (nb_err >= 2) var txt2 = nb_err+" fautes"; else var txt2 = nb_err+" faute"; //------------------------------------ //on complète la variable de résultats result += "Temps : "+ total_time +nl +"Vous avez fait "+txt1+" ("+txt2+" de frappe)."+nl +'Précision : <span title="Précision : > 97 :) ; 92-97 :| ; < 92 :(" id="precision_col" style="color:red"><strong>'+precision+" %</strong></span>"+nl +"Coups par seconde : "+cps+nl //+'Mots par minute : <span title="Ce chiffre n’est coloré que pour représenter une vitesse à laquelle la frappe devient agréable — 50 mots par minute. Dès que vous atteindrez — ou dépasserez — cette vitesse régulièrement, vous aurez une grande aisance avec le clavier." id="mpm_col" style="color:orange"><strong>'+mpm+"</strong></span>"+nl; +'Mots par minute : <span id="mpm_col" style="color:orange"><strong>'+mpm+"</strong></span>"+nl +'Fluidité : <span id="fl_col" style="color:red"><strong>'+fl+' %</strong></span>'+nl; // +nl+'<input style="border:none;background-color:none;width:100%" type="text" onclick="this.select()" value="texte nº '+text_nb+' ; '+mpm+'mpm ; Fluid '+fl+'% ; '+txt1+'"/>'+nl; //si il y a des erreurs if (nb_err != 0) { result += nl+"Sans erreurs, vous auriez pu atteindre <strong>"+mpm_top+"</strong> mots par minute."+nl //on donne la vitesse + "Temps perdu en erreurs : "+ lost_time //le temps perdu + " soit " + lost_time_percent + "%" +nl; //et le pourcentage de temps perdu } } else { result += 'Texte nº'+text_nb+' en '+total_time+' à '+mpm+'mpm ('+cps+'cps ; précision : '+precision+'%) ; fluidité : '+fl+'.'+nl; } //résultats sur la précision if (precision >= 97) { result += nl+"Félicitations ! Votre précision est excellente."; //petite phrase d'encouragement result = result.replace('id="precision_col" style="color:red"','id="precision_col" style="color:green"'); //et on passe la précision en vert } else if (precision > 92) { result += nl+"Votre précision est correcte."; //petite phrase pour dire que c'est bon (mais sans plus) result = result.replace('id="precision_col" style="color:red"','id="precision_col" style="color:orange"');//et on passe la précision en orange } else result += nl+"Essayez de gagner en précision et la vitesse augmentera."; //petite phrase pour dire que ça sert à rien de taper comme un dinque //résultats sur la vitesse if (mpm >= 50) { if (mpm > 90) result += nl+"Vous vous entrainez pour un concours !?"; else result += nl+"Félicitations ! Votre vitesse de frappe est excellente."; //petite phrase d'encouragement result = result.replace('id="mpm_col" style="color:orange"','id="mpm_col" style="color:green"'); //et on passe la vitesse en vert } //résultats sur la fluidité if (fl >= 65) { if (fl > 90) result+= nl+"Vous tapez avec beaucoup de régularité ! On pourrait croire que vous êtes un robot !"; result = result.replace('id="fl_col" style="color:red"','id="fl_col" style="color:green"'); //mise en vert parce que c'est bien } else { result += nl+"Vous n'êtes pas très régulier dans votre frappe."; //sinon petite phrase parce que c'est pas trop bon } //result += '<hr><input type="button" class="full_width" onclick="make_ghost_from_session()" value="Créer un fantôme local temporaire"/><br/><input type="button" class="full_width" onclick="this.onclick=make_ghost_from_session_and_save_it()" value="Créer un fantôme et l\'enregistrer sur le serveur"/><div id="result_ghost"></div>' //affichage des stats de la session document.getElementById("resultats").innerHTML = result; //on affiche document.getElementById("resultats").style.backgroundColor = "#f0fff0"; //on colorise document.getElementById("resultats").style.border = "1px solid black"; //on met une bordure } //cette fonction permet de sauvegarder la totalité de la zone de résultats et de la restaurer ensuite si besoin var old_result = new Array; //le tableau ou est enregistré la zone de résultats var val_result_bol = false; //true si on a déjà fait un sauvegarde function val_result(a) { if (a == "save" && val_result_bol == false) //on sauvegarde { old_result[0] = document.getElementById("resultats").innerHTML; old_result[1] = document.getElementById("resultats").style.backgroundColor; old_result[2] = document.getElementById("resultats").style.border; val_result_bol = true; } if (a == "resto" && val_result_bol == true) //on restaure { document.getElementById("resultats").innerHTML = old_result[0]; document.getElementById("resultats").style.backgroundColor = old_result[1]; document.getElementById("resultats").style.border = old_result[2]; val_result_bol = false; } if (a == "reset") // permet de supprimer la sauvegarde de la zone de résultats { old_result[0] = ""; old_result[1] = "inherit"; old_result[2] = "inherit"; } } // cette fonction permet de sauver les préférences des options en enregistrant des cookies function save_opt() { var id_ = ""; // le nom temporaire de l'ID de l'input var check_ = ""; // l'état temporaire du checkbox de l'input // url pour la requete var url = "save_pref.php?"; // un tableau de tous les inputs qui se trouvent dans les options var list = document.getElementById("options").getElementsByTagName("input"); for (var i=0 ; i<list.length ; i++) { id_ = document.getElementById("options").getElementsByTagName("input")[i].id; check_ = document.getElementById(id_).checked; url += "&"+id_+"="+check_; } val_result("save"); // sauvegarde du champ de résultats var req_rep = request(url,"resultats"); // affichage du retour de la requête document.getElementById("resultats").innerHTML="<strong>"+req_rep+"</strong>"; document.getElementById("resultats").style.border = "none"; document.getElementById("resultats").style.backgroundColor = "inherit"; setTimeout('val_result("resto")',1500); // restauration du champ de résultats dans 1s } // pour afficher ou cacher le cadre des options function view_options() { if (document.getElementById("view_options").style.display == "none") { document.getElementById("view_options").style.display = "block"; return "Cacher les options"; } else { document.getElementById("view_options").style.display = "none"; return "Afficher les options"; } } // cette fonction permet d'avoir des raccourcis clavier esc_key = false; function vidactyl(e) { var touche = window.event ? e.keyCode : e.which; //on regarde quelle touche est frappée if (touche == 27) // c'est la touche échap { if (esc_key == true) { esc_key = false; val_result("resto"); if (document.getElementById("txt").readOnly == false) document.getElementById("txt").focus(); } else { esc_key = true; document.getElementById("txt").blur(); val_result("save"); document.getElementById("resultats").innerHTML="<p><strong>Mode commande :</strong></p>n : nouveau texte<br/>r : recommencer le texte"; document.getElementById("resultats").style.border = "none"; document.getElementById("resultats").style.backgroundColor = "inherit"; } } else { if (esc_key == true) { esc_key = false; // dans tous les cas ça évite d'avoir des action alors qu'on est en train de taper du texte switch(touche) { case 78: new_text("new"); break; case 82: new_text(); break; case 68: var a=""; var b=""; var err=0; document.getElementById("resultats").innerHTML = ""; for (var i=0;i<list_f.length;i++) { a=list_f[i].val; b=le_texte.substring(0,list_f[i].val.length); if (a!=b) { err++; a='<span style="color:red">'+a+'</span>'; document.getElementById("resultats").innerHTML+=b+'<br/>'+a+'<br/><br/>'; } else { a='<span style="color:green">'+a+'</span>'; document.getElementById("resultats").innerHTML+=b+'<br/>'+a+'<br/><br/>'; } } break; default: esc_key = false; val_result("resto"); if (document.getElementById("txt").readOnly == false) document.getElementById("txt").focus(); break; } } else { esc_key = false; val_result("resto"); if (document.getElementById("txt").readOnly == false) document.getElementById("txt").focus(); } } }
tazzon/dactylotest
dactylotest/js/functions_page_test.js
JavaScript
agpl-3.0
19,609
# # Copyright (C) 2012 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # class Course < ActiveRecord::Base include Context include Workflow attr_accessible :name, :section, :account, :group_weighting_scheme, :start_at, :conclude_at, :grading_standard_id, :is_public, :publish_grades_immediately, :allow_student_wiki_edits, :allow_student_assignment_edits, :hashtag, :show_public_context_messages, :syllabus_body, :allow_student_forum_attachments, :default_wiki_editing_roles, :allow_student_organized_groups, :course_code, :default_view, :show_all_discussion_entries, :open_enrollment, :allow_wiki_comments, :turnitin_comments, :self_enrollment, :license, :indexed, :enrollment_term, :abstract_course, :root_account, :storage_quota, :storage_quota_mb, :restrict_enrollments_to_course_dates, :grading_standard, :grading_standard_enabled, :locale, :settings serialize :tab_configuration serialize :settings, Hash belongs_to :root_account, :class_name => 'Account' belongs_to :abstract_course belongs_to :enrollment_term belongs_to :grading_standard belongs_to :template_course, :class_name => 'Course' has_many :templated_courses, :class_name => 'Course', :foreign_key => 'template_course_id' has_many :course_sections has_many :active_course_sections, :class_name => 'CourseSection', :conditions => {:workflow_state => 'active'} has_many :enrollments, :include => [:user, :course], :conditions => ['enrollments.workflow_state != ?', 'deleted'], :dependent => :destroy has_many :current_enrollments, :class_name => 'Enrollment', :conditions => ['enrollments.workflow_state != ? AND enrollments.workflow_state != ? AND enrollments.workflow_state != ? AND enrollments.workflow_state != ?', 'rejected', 'completed', 'deleted', 'inactive'], :include => :user has_many :prior_enrollments, :class_name => 'Enrollment', :include => [:user, :course], :conditions => "enrollments.workflow_state = 'completed'" has_many :students, :through => :student_enrollments, :source => :user, :order => User.sortable_name_order_by_clause has_many :all_students, :through => :all_student_enrollments, :source => :user, :order => User.sortable_name_order_by_clause has_many :participating_students, :through => :enrollments, :source => :user, :conditions => "enrollments.type = 'StudentEnrollment' and enrollments.workflow_state = 'active'" has_many :student_enrollments, :class_name => 'StudentEnrollment', :conditions => ['enrollments.workflow_state != ? AND enrollments.workflow_state != ? AND enrollments.workflow_state != ? AND enrollments.workflow_state != ?', 'deleted', 'completed', 'rejected', 'inactive'], :include => :user #, :conditions => "type = 'StudentEnrollment'" has_many :all_student_enrollments, :class_name => 'StudentEnrollment', :conditions => ['enrollments.workflow_state != ?', 'deleted'], :include => :user has_many :detailed_enrollments, :class_name => 'Enrollment', :conditions => ['enrollments.workflow_state != ?', 'deleted'], :include => {:user => {:pseudonym => :communication_channel}} has_many :teachers, :through => :teacher_enrollments, :source => :user has_many :teacher_enrollments, :class_name => 'TeacherEnrollment', :conditions => ['enrollments.workflow_state != ?', 'deleted'], :include => :user has_many :tas, :through => :ta_enrollments, :source => :user has_many :ta_enrollments, :class_name => 'TaEnrollment', :conditions => ['enrollments.workflow_state != ?', 'deleted'], :include => :user has_many :designers, :through => :designer_enrollments, :source => :user has_many :designer_enrollments, :class_name => 'DesignerEnrollment', :conditions => ['enrollments.workflow_state != ?', 'deleted'], :include => :user has_many :observers, :through => :observer_enrollments, :source => :user has_many :observer_enrollments, :class_name => 'ObserverEnrollment', :conditions => ['enrollments.workflow_state != ?', 'deleted'], :include => :user has_many :instructors, :through => :enrollments, :source => :user, :conditions => "enrollments.type = 'TaEnrollment' or enrollments.type = 'TeacherEnrollment'" has_many :instructor_enrollments, :class_name => 'Enrollment', :conditions => "(enrollments.type = 'TaEnrollment' or enrollments.type = 'TeacherEnrollment')" has_many :participating_instructors, :through => :enrollments, :source => :user, :conditions => "(enrollments.type = 'TaEnrollment' or enrollments.type = 'TeacherEnrollment') and enrollments.workflow_state = 'active'" has_many :admins, :through => :enrollments, :source => :user, :conditions => "enrollments.type = 'TaEnrollment' or enrollments.type = 'TeacherEnrollment' or enrollments.type = 'DesignerEnrollment'" has_many :admin_enrollments, :class_name => 'Enrollment', :conditions => "(enrollments.type = 'TaEnrollment' or enrollments.type = 'TeacherEnrollment' or enrollments.type = 'DesignerEnrollment')" has_many :participating_admins, :through => :enrollments, :source => :user, :conditions => "(enrollments.type = 'TaEnrollment' or enrollments.type = 'TeacherEnrollment' or enrollments.type = 'DesignerEnrollment') and enrollments.workflow_state = 'active'" has_many :learning_outcomes, :through => :learning_outcome_tags, :source => :learning_outcome_content, :conditions => "content_tags.content_type = 'LearningOutcome'" has_many :learning_outcome_tags, :as => :context, :class_name => 'ContentTag', :conditions => ['content_tags.tag_type = ? AND content_tags.workflow_state != ?', 'learning_outcome_association', 'deleted'] has_many :created_learning_outcomes, :class_name => 'LearningOutcome', :as => :context has_many :learning_outcome_groups, :as => :context has_many :course_account_associations has_many :non_unique_associated_accounts, :source => :account, :through => :course_account_associations, :order => 'course_account_associations.depth' has_many :users, :through => :enrollments, :source => :user has_many :group_categories, :as => :context, :conditions => ['deleted_at IS NULL'] has_many :all_group_categories, :class_name => 'GroupCategory', :as => :context has_many :groups, :as => :context has_many :active_groups, :as => :context, :class_name => 'Group', :conditions => ['groups.workflow_state != ?', 'deleted'] has_many :assignment_groups, :as => :context, :dependent => :destroy, :order => 'assignment_groups.position, assignment_groups.name' has_many :assignments, :as => :context, :dependent => :destroy, :order => 'assignments.created_at' has_many :calendar_events, :as => :context, :conditions => ['calendar_events.workflow_state != ?', 'cancelled'], :dependent => :destroy has_many :submissions, :through => :assignments, :order => 'submissions.updated_at DESC', :include => :quiz_submission, :dependent => :destroy has_many :discussion_topics, :as => :context, :conditions => ['discussion_topics.workflow_state != ?', 'deleted'], :include => :user, :dependent => :destroy, :order => 'discussion_topics.position DESC, discussion_topics.created_at DESC' has_many :active_discussion_topics, :as => :context, :class_name => 'DiscussionTopic', :conditions => ['discussion_topics.workflow_state != ?', 'deleted'], :include => :user has_many :all_discussion_topics, :as => :context, :class_name => "DiscussionTopic", :include => :user, :dependent => :destroy has_many :discussion_entries, :through => :discussion_topics, :include => [:discussion_topic, :user], :dependent => :destroy has_many :announcements, :as => :context, :class_name => 'Announcement', :dependent => :destroy has_many :active_announcements, :as => :context, :class_name => 'Announcement', :conditions => ['discussion_topics.workflow_state != ?', 'deleted'], :order => 'created_at DESC' has_many :attachments, :as => :context, :dependent => :destroy, :extend => Attachment::FindInContextAssociation has_many :active_images, :as => :context, :class_name => 'Attachment', :conditions => ["attachments.file_state != ? AND attachments.content_type LIKE 'image%'", 'deleted'], :order => 'attachments.display_name', :include => :thumbnail has_many :active_assignments, :as => :context, :class_name => 'Assignment', :conditions => ['assignments.workflow_state != ?', 'deleted'], :order => 'assignments.title, assignments.position' has_many :folders, :as => :context, :dependent => :destroy, :order => 'folders.name' has_many :active_folders, :class_name => 'Folder', :as => :context, :conditions => ['folders.workflow_state != ?', 'deleted'], :order => 'folders.name' has_many :active_folders_with_sub_folders, :class_name => 'Folder', :as => :context, :include => [:active_sub_folders], :conditions => ['folders.workflow_state != ?', 'deleted'], :order => 'folders.name' has_many :active_folders_detailed, :class_name => 'Folder', :as => :context, :include => [:active_sub_folders, :active_file_attachments], :conditions => ['folders.workflow_state != ?', 'deleted'], :order => 'folders.name' has_many :messages, :as => :context, :dependent => :destroy has_many :context_external_tools, :as => :context, :dependent => :destroy, :order => 'name' belongs_to :wiki has_many :default_wiki_wiki_pages, :class_name => 'WikiPage', :through => :wiki, :source => :wiki_pages, :conditions => ['wiki_pages.workflow_state != ?', 'deleted'], :order => 'wiki_pages.view_count DESC' has_many :wiki_namespaces, :as => :context, :dependent => :destroy has_many :quizzes, :as => :context, :dependent => :destroy, :order => 'lock_at, title' has_many :active_quizzes, :class_name => 'Quiz', :as => :context, :include => :assignment, :conditions => ['quizzes.workflow_state != ?', 'deleted'], :order => 'created_at' has_many :assessment_questions, :through => :assessment_question_banks has_many :assessment_question_banks, :as => :context, :include => [:assessment_questions, :assessment_question_bank_users] def inherited_assessment_question_banks(include_self = false) self.account.inherited_assessment_question_banks(true, *(include_self ? [self] : [])) end has_many :external_feeds, :as => :context, :dependent => :destroy belongs_to :default_grading_standard, :class_name => 'GradingStandard', :foreign_key => 'grading_standard_id' has_many :grading_standards, :as => :context has_one :gradebook_upload, :as => :context, :dependent => :destroy has_many :web_conferences, :as => :context, :order => 'created_at DESC', :dependent => :destroy has_many :rubrics, :as => :context has_many :rubric_associations, :as => :context, :include => :rubric, :dependent => :destroy has_many :tags, :class_name => 'ContentTag', :as => 'context', :order => 'LOWER(title)', :conditions => {:tag_type => 'default'}, :dependent => :destroy has_many :collaborations, :as => :context, :order => 'title, created_at', :dependent => :destroy has_one :scribd_account, :as => :scribdable has_many :short_message_associations, :as => :context, :include => :short_message, :dependent => :destroy has_many :short_messages, :through => :short_message_associations, :dependent => :destroy has_many :grading_standards, :as => :context has_many :context_modules, :as => :context, :order => :position, :dependent => :destroy has_many :active_context_modules, :as => :context, :class_name => 'ContextModule', :conditions => {:workflow_state => 'active'} has_many :context_module_tags, :class_name => 'ContentTag', :as => 'context', :order => :position, :conditions => ['tag_type = ?', 'context_module'], :dependent => :destroy has_many :media_objects, :as => :context has_many :page_views, :as => :context has_many :role_overrides, :as => :context has_many :content_exports has_many :course_imports has_many :alerts, :as => :context, :include => :criteria has_many :appointment_groups, :as => :context has_many :appointment_participants, :class_name => 'CalendarEvent', :foreign_key => :effective_context_code, :primary_key => :asset_string, :conditions => "workflow_state = 'locked' AND parent_calendar_event_id IS NOT NULL" attr_accessor :import_source before_save :assign_uuid before_save :assert_defaults before_save :set_update_account_associations_if_changed before_save :update_enrollments_later after_save :update_final_scores_on_weighting_scheme_change after_save :update_account_associations_if_changed before_validation :verify_unique_sis_source_id validates_length_of :syllabus_body, :maximum => maximum_long_text_length, :allow_nil => true, :allow_blank => true validates_locale :allow_nil => true sanitize_field :syllabus_body, Instructure::SanitizeField::SANITIZE include StickySisFields are_sis_sticky :name, :course_code, :start_at, :conclude_at, :restrict_enrollments_to_course_dates, :enrollment_term_id has_a_broadcast_policy def self.skip_updating_account_associations(&block) if @skip_updating_account_assocations block.call else begin @skip_updating_account_associations = true block.call ensure @skip_updating_account_associations = false end end end def self.skip_updating_account_associations? !!@skip_updating_account_associations end def set_update_account_associations_if_changed @should_update_account_associations = self.root_account_id_changed? || self.account_id_changed? @should_delay_account_associations = !self.new_record? true end def update_account_associations_if_changed send_now_or_later_if_production(@should_delay_account_associations ? :later : :now, :update_account_associations) if @should_update_account_associations && !self.class.skip_updating_account_associations? end def module_based? Rails.cache.fetch(['module_based_course', self].cache_key) do self.context_modules.active.any?{|m| m.completion_requirements && !m.completion_requirements.empty? } end end def verify_unique_sis_source_id return true unless self.sis_source_id existing_course = self.root_account.all_courses.find_by_sis_source_id(self.sis_source_id) return true if !existing_course || existing_course.id == self.id self.errors.add(:sis_source_id, t('errors.sis_in_use', "SIS ID \"%{sis_id}\" is already in use", :sis_id => self.sis_source_id)) false end def public_license? license && license != 'private' end def self.licenses ActiveSupport::OrderedHash[ 'private', { :readable_license => t('#cc.private', 'Private (Copyrighted)'), :license_url => "http://en.wikipedia.org/wiki/Copyright" }, 'cc_by_nc_nd', { :readable_license => t('#cc.by_nc_nd', 'CC Attribution Non-Commercial No Derivatives'), :license_url => "http://creativecommons.org/licenses/by-nc-nd/3.0/" }, 'cc_by_nc_sa', { :readable_license => t('#cc.by_nc_sa', 'CC Attribution Non-Commercial Share Alike'), :license_url => "http://creativecommons.org/licenses/by-nc-sa/3.0" }, 'cc_by_nc', { :readable_license => t('#cc.by_nc', 'CC Attribution Non-Commercial'), :license_url => "http://creativecommons.org/licenses/by-nc/3.0" }, 'cc_by_nd', { :readable_license => t('#cc.by_nd', 'CC Attribution No Derivatives'), :license_url => "http://creativecommons.org/licenses/by-nd/3.0" }, 'cc_by_sa', { :readable_license => t('#cc.by_sa', 'CC Attribution Share Alike'), :license_url => "http://creativecommons.org/licenses/by-sa/3.0" }, 'cc_by', { :readable_license => t('#cc.by', 'CC Attribution'), :license_url => "http://creativecommons.org/licenses/by/3.0" }, 'public_domain', { :readable_license => t('#cc.public_domain', 'Public Domain'), :license_url => "http://en.wikipedia.org/wiki/Public_domain" }, ] end def license_data licenses = self.class.licenses licenses[license] || licenses['private'] end def license_url license_data[:license_url] end def readable_license license_data[:readable_license] end def self.update_account_associations(courses_or_course_ids, opts = {}) return [] if courses_or_course_ids.empty? opts.reverse_merge! :account_chain_cache => {} account_chain_cache = opts[:account_chain_cache] # Split it up into manageable chunks user_ids_to_update_account_associations = [] if courses_or_course_ids.length > 500 opts = opts.dup opts.reverse_merge! :skip_user_account_associations => true courses_or_course_ids.uniq.compact.each_slice(500) do |courses_or_course_ids_slice| user_ids_to_update_account_associations += update_account_associations(courses_or_course_ids_slice, opts) end else if courses_or_course_ids.first.is_a? Course courses = courses_or_course_ids Course.send(:preload_associations, courses, :course_sections => :nonxlist_course) course_ids = courses.map(&:id) else course_ids = courses_or_course_ids courses = Course.find(:all, :conditions => {:id => course_ids }, :include => { :course_sections => :nonxlist_course }) end course_ids_to_update_user_account_associations = [] CourseAccountAssociation.transaction do current_associations = {} to_delete = [] CourseAccountAssociation.find(:all, :conditions => { :course_id => course_ids }).each do |aa| key = [aa.course_section_id, aa.account_id] # duplicates current_course_associations = current_associations[aa.course_id] ||= {} if current_course_associations.has_key?(key) to_delete << aa.id next end current_course_associations[key] = [aa.id, aa.depth] end courses.each do |course| did_an_update = false current_course_associations = current_associations[course.id] || {} # Courses are tied to accounts directly and through sections and crosslisted courses (course.course_sections + [nil]).each do |section| next if section && !section.active? section.course = course if section starting_account_ids = [course.account_id, section.try(:account_id), section.try(:nonxlist_course).try(:account_id)].compact.uniq account_ids_with_depth = User.calculate_account_associations_from_accounts(starting_account_ids, account_chain_cache).map account_ids_with_depth.each do |account_id_with_depth| account_id = account_id_with_depth[0] depth = account_id_with_depth[1] key = [section.try(:id), account_id] association = current_course_associations[key] if association.nil? # new association, create it CourseAccountAssociation.create! do |aa| aa.course_id = course.id aa.course_section_id = section.try(:id) aa.account_id = account_id aa.depth = depth end did_an_update = true else if association[1] != depth CourseAccountAssociation.update_all("depth=#{depth}", :id => association[0]) did_an_update = true end # remove from list of existing current_course_associations.delete(key) end end end did_an_update ||= !current_course_associations.empty? if did_an_update course.course_account_associations.reset course.non_unique_associated_accounts.reset course_ids_to_update_user_account_associations << course.id end end to_delete += current_associations.map { |k, v| v.map { |k2, v2| v2[0] } }.flatten unless to_delete.empty? CourseAccountAssociation.delete_all(:id => to_delete) end end user_ids_to_update_account_associations = Enrollment.find(:all, :select => 'user_id', :group => :user_id, :conditions => [ 'course_id IN(?) AND workflow_state <> ?', course_ids_to_update_user_account_associations, 'deleted' ]).map(&:user_id) unless course_ids_to_update_user_account_associations.empty? end User.update_account_associations(user_ids_to_update_account_associations, :account_chain_cache => account_chain_cache) unless user_ids_to_update_account_associations.empty? || opts[:skip_user_account_associations] user_ids_to_update_account_associations end def has_outcomes Rails.cache.fetch(['has_outcomes', self].cache_key) do self.learning_outcomes.count > 0 end end def update_account_associations Course.update_account_associations([self]) end def associated_accounts self.non_unique_associated_accounts.uniq end # objects returned from this query will give you an additional attribute "page_views_count" that you can use, so: # Account.first.courses.most_active(10).first.page_views_count #=> "466" named_scope :most_active, lambda { |limit| { :select => "courses.*, (SELECT COUNT(*) FROM page_views WHERE context_id = courses.id AND context_type = 'Course') AS page_views_count", :order => "page_views_count DESC", :limit => limit } } named_scope :recently_started, lambda { {:conditions => ['start_at < ? and start_at > ?', Time.now.utc, 1.month.ago], :order => 'start_at DESC', :limit => 10} } named_scope :recently_ended, lambda { {:conditions => ['conclude_at < ? and conclude_at > ?', Time.now.utc, 1.month.ago], :order => 'start_at DESC', :limit => 10} } named_scope :recently_created, lambda { {:conditions => ['created_at > ?', 1.month.ago], :order => 'created_at DESC', :limit => 50, :include => :teachers} } named_scope :for_term, lambda {|term| term ? {:conditions => ['courses.enrollment_term_id = ?', term.id]} : {} } named_scope :active_first, lambda { {:order => "CASE WHEN courses.workflow_state='available' THEN 0 ELSE 1 END, name"} } named_scope :limit, lambda {|limit| {:limit => limit } } named_scope :name_like, lambda { |name| { :conditions => wildcard('courses.name', 'courses.sis_source_id', 'courses.course_code', name) } } named_scope :needs_account, lambda{|account, limit| {:conditions => {:account_id => nil, :root_account_id => account.id}, :limit => limit } } named_scope :active, lambda{ {:conditions => ['courses.workflow_state != ?', 'deleted'] } } named_scope :least_recently_updated, lambda{|limit| {:order => 'updated_at', :limit => limit } } named_scope :manageable_by_user, lambda{|user_id| { :select => 'DISTINCT courses.*', :joins => "INNER JOIN ( SELECT caa.course_id, au.user_id FROM course_account_associations AS caa INNER JOIN accounts AS a ON a.id = caa.account_id AND a.workflow_state = 'active' INNER JOIN account_users AS au ON au.account_id = a.id AND au.user_id = #{user_id.to_i} UNION SELECT courses.id AS course_id, e.user_id FROM courses INNER JOIN enrollments AS e ON e.course_id = courses.id AND e.user_id = #{user_id.to_i} AND e.workflow_state = 'active' AND e.type IN ('TeacherEnrollment', 'TaEnrollment', 'DesignerEnrollment') WHERE courses.workflow_state <> 'deleted') as course_users ON course_users.course_id = courses.id" } } named_scope :not_deleted, {:conditions => ['workflow_state != ?', 'deleted']} named_scope :with_enrollments, lambda { { :conditions => ["exists (#{Enrollment.active.send(:construct_finder_sql, {:select => "1", :conditions => ["enrollments.course_id = courses.id"]})})"] } } set_broadcast_policy do |p| p.dispatch :grade_weight_changed p.to { participating_students } p.whenever { |record| (record.available? && @grade_weight_changed) || record.changed_in_state(:available, :fields => :group_weighting_scheme) } p.dispatch :new_course p.to { self.root_account.account_users } p.whenever { |record| record.root_account && ((record.just_created && record.name != Course.default_name) || (record.prior_version.name == Course.default_name && record.name != Course.default_name)) } end def self.default_name # TODO i18n t('default_name', "My Course") end def users_not_in_groups_sql(groups, opts={}) ["SELECT DISTINCT u.id, u.name#{", #{opts[:order_by]}" if opts[:order_by].present?} FROM users u INNER JOIN enrollments e ON e.user_id = u.id WHERE e.course_id = ? AND e.workflow_state NOT IN ('rejected', 'completed', 'deleted') AND e.type = 'StudentEnrollment' #{"AND NOT EXISTS (SELECT * FROM group_memberships gm WHERE gm.user_id = u.id AND gm.group_id IN (#{groups.map(&:id).join ','}))" unless groups.empty?} #{"ORDER BY #{opts[:order_by]}" if opts[:order_by].present?} #{"#{opts[:order_by_dir]}" if opts[:order_by_dir]}", self.id] end def users_not_in_groups(groups) User.find_by_sql(users_not_in_groups_sql(groups)) end def paginate_users_not_in_groups(groups, page, per_page = 15) User.paginate_by_sql(users_not_in_groups_sql(groups, :order_by => "#{User.sortable_name_order_by_clause('u')}", :order_by_dir => "ASC"), :page => page, :per_page => per_page) end def instructors_in_charge_of(user_id) section_ids = current_enrollments.find(:all, :select => 'course_section_id, course_id, user_id, limit_privileges_to_course_section', :conditions => {:course_id => self.id, :user_id => user_id}).map(&:course_section_id).compact.uniq if section_ids.empty? participating_instructors else participating_instructors.for_course_section(section_ids) end end def user_is_teacher?(user) return unless user cache_key = [self, user, "course_user_is_teacher"].cache_key res = Rails.cache.read(cache_key) if res.nil? res = user.cached_current_enrollments.any? { |e| e.course_id == self.id && e.participating_instructor? } Rails.cache.write(cache_key, res) end res end memoize :user_is_teacher? def user_is_student?(user) return unless user cache_key = [self, user, "course_user_is_student"].cache_key res = Rails.cache.read(cache_key) if res.nil? res = !self.student_enrollments.find_by_user_id(user.id).nil? Rails.cache.write(cache_key, res) end res end memoize :user_is_student? def grade_weight_changed! @grade_weight_changed = true self.save! @grade_weight_changed = false end def membership_for_user(user) self.enrollments.find_by_user_id(user && user.id) end def assert_defaults Hashtag.find_or_create_by_hashtag(self.hashtag) if self.hashtag && self.hashtag != "" self.tab_configuration ||= [] unless self.tab_configuration == [] self.name = nil if self.name && self.name.strip.empty? self.name ||= t('missing_name', "Unnamed Course") self.course_code = nil if self.course_code == "" || (self.name_changed? && self.course_code && self.name_was && self.name_was.start_with?(self.course_code)) if !self.course_code && self.name res = [] split = self.name.split(/\s/) res << split[0] res << split[1..-1].find{|txt| txt.match(/\d/) } rescue nil self.course_code = res.compact.join(" ") end @group_weighting_scheme_changed = self.group_weighting_scheme_changed? self.indexed = nil unless self.is_public if self.account_id && self.account_id_changed? # This is a bit tricky. Basically, it ensures a is the current account; # if account is not loaded, it will not double load (because it's # already cached). If it's already loaded, and correct, it again will # only use the cache. If it's already loaded and the wrong one, it will # force reload a = self.account(self.account && self.account.id != self.account_id) self.root_account_id = a.root_account_id if a self.root_account_id ||= a.id if a # Ditto self.root_account(self.root_account && self.root_account.id != self.root_account_id) end if self.root_account_id && self.root_account_id_changed? a = self.account(self.account && self.account.id != self.account_id) self.account_id = nil if self.account_id && self.account_id != self.root_account_id && a && a.root_account_id != self.root_account_id self.account_id ||= self.root_account_id end self.root_account_id ||= Account.default.id self.account_id ||= self.root_account_id self.enrollment_term = nil if self.enrollment_term.try(:root_account_id) != self.root_account_id self.enrollment_term ||= self.root_account.default_enrollment_term self.publish_grades_immediately = true if self.publish_grades_immediately == nil self.allow_student_wiki_edits = (self.default_wiki_editing_roles || "").split(',').include?('students') true end def update_course_section_names return if @course_name_was == self.name || !@course_name_was sections = self.course_sections fields_to_possibly_rename = [:name, :section_code, :long_section_code] sections.each do |section| something_changed = false fields_to_possibly_rename.each do |field| section.send("#{field}=", section.default_section ? self.name : (section.send(field) || self.name).sub(@course_name_was, self.name) ) something_changed = true if section.send(field) != section.send("#{field}_was") end if something_changed attr_hash = {:updated_at => Time.now.utc} fields_to_possibly_rename.each { |key| attr_hash[key] = section.send(key) } CourseSection.update_all(attr_hash, {:id => section.id}) end end end def update_enrollments_later self.update_enrolled_users if !self.new_record? && !(self.changes.keys & ['workflow_state', 'name', 'course_code', 'start_at', 'conclude_at', 'enrollment_term_id']).empty? true end def update_enrolled_users if self.completed? Enrollment.update_all({:workflow_state => 'completed'}, "course_id=#{self.id} AND workflow_state IN('active', 'invited')") appointment_participants.active.current.update_all(:workflow_state => 'deleted') appointment_groups.each(&:clear_cached_available_slots!) elsif self.deleted? Enrollment.update_all({:workflow_state => 'deleted'}, "course_id=#{self.id} AND workflow_state!='deleted'") end if self.root_account_id_changed? Enrollment.update_all({:root_account_id => self.root_account_id}, :course_id => self.id) end case Enrollment.connection.adapter_name when 'MySQL' Enrollment.connection.execute("UPDATE users, enrollments SET users.updated_at=NOW(), enrollments.updated_at=NOW() WHERE users.id=enrollments.user_id AND enrollments.course_id=#{self.id}") else Enrollment.update_all({:updated_at => Time.now.utc}, :course_id => self.id) User.update_all({:updated_at => Time.now.utc}, "id IN (SELECT user_id FROM enrollments WHERE course_id=#{self.id})") end end def self_enrollment_allowed? !!(self.account && self.account.self_enrollment_allowed?(self)) end def self_enrollment_code Digest::MD5.hexdigest("#{uuid}_for_#{id}") end memoize :self_enrollment_code def update_final_scores_on_weighting_scheme_change if @group_weighting_scheme_changed Enrollment.send_later_if_production(:recompute_final_score, self.students.map(&:id), self.id) end end def recompute_student_scores Enrollment.recompute_final_score(self.students.map(&:id), self.id) end handle_asynchronously_if_production :recompute_student_scores def home_page WikiNamespace.default_for_context(self).wiki.wiki_page end def context_code raise "DONT USE THIS, use .short_name instead" unless ENV['RAILS_ENV'] == "production" end def allow_media_comments? true || [].include?(self.id) end def short_name course_code end def short_name=(val) write_attribute(:course_code, val) end # Allows the account to be set directly belongs_to :account def wiki res = self.wiki_id && Wiki.find_by_id(self.wiki_id) unless res res = WikiNamespace.default_for_context(self).wiki self.wiki_id = res.id if res self.save end res end # A universal lookup for all messages. def messages Message.for(self) end def do_complete self.conclude_at ||= Time.now end def do_unconclude self.conclude_at = nil end def do_offer self.start_at ||= Time.now send_later_if_production(:invite_uninvited_students) end def invite_uninvited_students self.enrollments.find_all_by_workflow_state("creation_pending").each do |e| e.invite! end end def hashtag_model Hashtag.find_by_hashtag(self.hashtag) if self.hashtag end workflow do state :created do event :claim, :transitions_to => :claimed event :offer, :transitions_to => :available event :complete, :transitions_to => :completed end state :claimed do event :offer, :transitions_to => :available event :complete, :transitions_to => :completed end state :available do event :complete, :transitions_to => :completed end state :completed do event :unconclude, :transitions_to => :available end state :deleted end alias_method :destroy!, :destroy def destroy self.workflow_state = 'deleted' save! end def call_event(event) self.send(event) if self.current_state.events.include? event.to_sym end def claim_with_teacher(user) raise "Must provide a valid teacher" unless user return unless self.state == :created e = enroll_user(user, 'TeacherEnrollment', :enrollment_state => 'active') #teacher(user) claim e end def self.require_assignment_groups(contexts) courses = contexts.select{|c| c.is_a?(Course) } hash = {} courses.each{|c| hash[c.id] = {:found => false, :course => c} } groups = AssignmentGroup.find(:all, {:select => "id, context_id, context_type", :conditions => {:context_type => "Course", :context_id => courses.map(&:id)}}) groups.each{|c| hash[c.context_id][:found] = true } hash.select{|id, obj| !obj[:found] }.each{|id, obj| obj[:course].require_assignment_group rescue nil } end def require_assignment_group has_group = Rails.cache.read(['has_assignment_group', self].cache_key) return if has_group && ENV['RAILS_ENV'] == 'production' if self.assignment_groups.active.empty? self.assignment_groups.create(:name => t('#assignment_group.default_name', "Assignments")) end Rails.cache.write(['has_assignment_group', self].cache_key, true) end def self.create_unique(uuid=nil, account_id=nil, root_account_id=nil) uuid ||= AutoHandle.generate_securish_uuid course = find_or_initialize_by_uuid(uuid) course = Course.new if course.deleted? course.name = self.default_name if course.new_record? course.short_name = t('default_short_name', "Course-101") if course.new_record? course.account_id = account_id || root_account_id course.root_account_id = root_account_id course.save! course end def <=>(other) self.id <=> other.id end def quota Rails.cache.fetch(['default_quota', self].cache_key) do storage_quota end end def storage_quota_mb storage_quota / 1.megabyte end def storage_quota_mb=(val) self.storage_quota = val.try(:to_i).try(:megabytes) end def storage_quota return read_attribute(:storage_quota) || (self.account.default_storage_quota rescue nil) || Setting.get_cached('course_default_quota', 500.megabytes.to_s).to_i end def storage_quota=(val) val = val.to_f val = nil if val <= 0 if account && account.default_storage_quota == val val = nil end write_attribute(:storage_quota, val) end def assign_uuid self.uuid ||= AutoHandle.generate_securish_uuid end protected :assign_uuid def full_name name end def to_atom Atom::Entry.new do |entry| entry.title = self.name entry.updated = self.updated_at entry.published = self.created_at entry.links << Atom::Link.new(:rel => 'alternate', :href => "/#{context_url_prefix}/courses/#{self.id}") end end set_policy do given { |user| self.available? && self.is_public } can :read RoleOverride.permissions.each_key do |permission| given {|user, session| self.enrollment_allows(user, session, permission) || self.account_membership_allows(user, session, permission) } can permission end given { |user, session| session && session[:enrollment_uuid] && (hash = Enrollment.course_user_state(self, session[:enrollment_uuid]) || {}) && (hash[:enrollment_state] == "invited" || hash[:enrollment_state] == "active" && hash[:user_state] == "pre_registered") && (self.available? || self.completed? || self.claimed? && hash[:is_admin]) } can :read given { |user| (self.available? || self.completed?) && user && user.cached_current_enrollments.any?{|e| e.course_id == self.id && [:active, :invited, :completed].include?(e.state_based_on_date) } } can :read given { |user| self.available? && user && user.cached_current_enrollments.any?{|e| e.course_id == self.id && e.participating_student? } } can :read and can :participate_as_student and can :read_grades given { |user| (self.available? || self.completed?) && user && user.cached_not_ended_enrollments.any?{|e| e.course_id == self.id && e.participating_observer? && e.associated_user_id} } can :read_grades given { |user, session| self.available? && self.teacherless? && user && user.cached_not_ended_enrollments.any?{|e| e.course_id == self.id && e.participating_student? } && (!session || !session["role_course_#{self.id}"]) } can :update and can :delete and RoleOverride.teacherless_permissions.each{|p| can p } # Active teachers given { |user, session| (self.available? || self.created? || self.claimed?) && user && user.cached_not_ended_enrollments.any?{|e| e.course_id == self.id && e.participating_admin? } && (!session || !session["role_course_#{self.id}"]) } can :read_as_admin and can :read and can :manage and can :update given { |user, session| !self.deleted? && !self.sis_source_id && user && user.cached_not_ended_enrollments.any?{|e| e.course_id == self.id && e.participating_admin? } && (!session || !session["role_course_#{self.id}"]) } can :delete # Prior users given { |user| !self.deleted? && user && self.prior_enrollments.map(&:user_id).include?(user.id) } can :read # Teacher of a concluded course given { |user| !self.deleted? && user && (self.prior_enrollments.select{|e| e.admin? }.map(&:user_id).include?(user.id) || user.cached_not_ended_enrollments.any? { |e| e.course_id == self.id && e.admin? }) } can :read_as_admin and can :read_roster and can :read_prior_roster and can :read_forum given { |user| !self.deleted? && user && (self.prior_enrollments.select{|e| e.instructor? }.map(&:user_id).include?(user.id) || user.cached_not_ended_enrollments.any? { |e| e.course_id == self.id && e.instructor? }) } can :read_user_notes and can :view_all_grades given { |user| !self.deleted? && !self.sis_source_id && user && (self.prior_enrollments.select{|e| e.admin? }.map(&:user_id).include?(user.id) || user.cached_not_ended_enrollments.any? { |e| e.course_id == self.id && e.admin? && e.state_based_on_date == :completed })} can :delete # Student of a concluded course given { |user| !self.deleted? && user && (self.prior_enrollments.select{|e| e.student? || e.assigned_observer? }.map(&:user_id).include?(user.id) || user.cached_not_ended_enrollments.any? { |e| e.course_id == self.id && (e.student? || e.assigned_observer?) && e.state_based_on_date == :completed }) } can :read and can :read_grades and can :read_forum # Viewing as different role type given { |user, session| session && session["role_course_#{self.id}"] } can :read # Admin given { |user, session| self.account_membership_allows(user, session) } can :read_as_admin given { |user, session| self.account_membership_allows(user, session, :manage_courses) } can :read_as_admin and can :manage and can :update and can :delete given { |user, session| self.account_membership_allows(user, session, :read_course_content) } can :read given { |user, session| !self.deleted? && self.sis_source_id && self.account_membership_allows(user, session, :manage_sis) } can :delete # Admins with read_roster can see prior enrollments (can't just check read_roster directly, # because students can't see prior enrollments) given { |user, session| self.account_membership_allows(user, session, :read_roster) } can :read_prior_roster end def enrollment_allows(user, session, permission) return false unless user && permission @enrollment_lookup ||= {} @enrollment_lookup[user.id] ||= if session && temp_type = session["role_course_#{self.id}"] [Enrollment.typed_enrollment(temp_type).new(:course => self, :user => user, :workflow_state => 'active')] else self.enrollments.active_or_pending.for_user(user).reject { |e| [:inactive, :completed].include?(e.state_based_on_date)} end @enrollment_lookup[user.id].any? {|e| e.has_permission_to?(permission) } end def self.find_all_by_context_code(codes) ids = codes.map{|c| c.match(/\Acourse_(\d+)\z/)[1] rescue nil }.compact Course.find(:all, :conditions => {:id => ids}, :include => :current_enrollments) end def end_at conclude_at end def end_at_changed? conclude_at_changed? end def recently_ended? conclude_at && conclude_at < Time.now.utc && conclude_at > 1.month.ago end def state_sortable case state when :invited 1 when :creation_pending 1 when :active 0 when :deleted 5 when :course_inactivated 3 when :rejected 4 when :completed 2 else 6 end end def has_outcomes? self.learning_outcomes.count > 0 end def account_chain self.account.account_chain end def account_chain_ids account_chain.map(&:id) end memoize :account_chain_ids def institution_name return self.root_account.name if self.root_account_id != Account.default.id return (self.account || self.root_account).name end memoize :institution_name def account_users_for(user) @associated_account_ids ||= (self.associated_accounts + [Account.site_admin]).map { |a| a.active? ? a.id: nil }.compact @account_users ||= {} @account_users[user] ||= AccountUser.find(:all, :conditions => { :account_id => @associated_account_ids, :user_id => user.id }) if user @account_users[user] ||= nil @account_users[user] end def account_membership_allows(user, session, permission = nil) return false unless user return false if session && session["role_course_#{self.id}"] @membership_allows ||= {} @membership_allows[[user.id, permission]] ||= self.account_users_for(user).any? { |au| permission.nil? || au.has_permission_to?(permission) } end def teacherless? # TODO: I need a better test for teacherless courses... in the mean time we'll just do this return false @teacherless_course ||= Rails.cache.fetch(['teacherless_course', self].cache_key) do !self.sis_source_id && self.teacher_enrollments.empty? end end def wiki_namespace WikiNamespace.default_for_context(self) end def grade_publishing_status_translation(status, message) status = "unpublished" if status.blank? case status when 'error' if message.present? message = t('grade_publishing_status.error_with_message', "Error: %{message}", :message => message) else message = t('grade_publishing_status.error', "Error") end when 'unpublished' if message.present? message = t('grade_publishing_status.unpublished_with_message', "Unpublished: %{message}", :message => message) else message = t('grade_publishing_status.unpublished', "Unpublished") end when 'pending' if message.present? message = t('grade_publishing_status.pending_with_message', "Pending: %{message}", :message => message) else message = t('grade_publishing_status.pending', "Pending") end when 'publishing' if message.present? message = t('grade_publishing_status.publishing_with_message', "Publishing: %{message}", :message => message) else message = t('grade_publishing_status.publishing', "Publishing") end when 'published' if message.present? message = t('grade_publishing_status.published_with_message', "Published: %{message}", :message => message) else message = t('grade_publishing_status.published', "Published") end when 'unpublishable' if message.present? message = t('grade_publishing_status.unpublishable_with_message', "Unpublishable: %{message}", :message => message) else message = t('grade_publishing_status.unpublishable', "Unpublishable") end else if message.present? message = t('grade_publishing_status.unknown_with_message', "Unknown status, %{status}: %{message}", :message => message, :status => status) else message = t('grade_publishing_status.unknown', "Unknown status, %{status}", :status => status) end end message end memoize :grade_publishing_status_translation def grade_publishing_statuses found_statuses = [].to_set enrollments = student_enrollments.group_by do |e| found_statuses.add e.grade_publishing_status grade_publishing_status_translation(e.grade_publishing_status, e.grade_publishing_message) end overall_status = "error" overall_status = "unpublished" unless found_statuses.size > 0 overall_status = (%w{error unpublished pending publishing published unpublishable}).detect{|s| found_statuses.include?(s)} || overall_status return enrollments, overall_status end def should_kick_off_grade_publishing_timeout? settings = Canvas::Plugin.find!('grade_export').settings settings[:success_timeout].to_i > 0 && Canvas::Plugin.value_to_boolean(settings[:wait_for_success]) end def self.valid_grade_export_types @valid_grade_export_types ||= { "instructure_csv" => { :name => t('grade_export_types.instructure_csv', "Instructure formatted CSV"), :callback => lambda { |course, enrollments, publishing_user, publishing_pseudonym| course.generate_grade_publishing_csv_output(enrollments, publishing_user, publishing_pseudonym) }, :requires_grading_standard => false, :requires_publishing_pseudonym => false } } end def allows_grade_publishing_by(user) return false unless Canvas::Plugin.find!('grade_export').enabled? settings = Canvas::Plugin.find!('grade_export').settings format_settings = Course.valid_grade_export_types[settings[:format_type]] return false unless format_settings return false if user.sis_pseudonym_for(self).nil? and format_settings[:requires_publishing_pseudonym] return true end def publish_final_grades(publishing_user) # we want to set all the publishing statuses to 'pending' immediately, # and then as a delayed job, actually go publish them. raise "final grade publishing disabled" unless Canvas::Plugin.find!('grade_export').enabled? settings = Canvas::Plugin.find!('grade_export').settings last_publish_attempt_at = Time.now.utc self.student_enrollments.update_all :grade_publishing_status => "pending", :grade_publishing_message => nil, :last_publish_attempt_at => last_publish_attempt_at send_later_if_production(:send_final_grades_to_endpoint, publishing_user) send_at(last_publish_attempt_at + settings[:success_timeout].to_i.seconds, :expire_pending_grade_publishing_statuses, last_publish_attempt_at) if should_kick_off_grade_publishing_timeout? end def send_final_grades_to_endpoint(publishing_user) # actual grade publishing logic is here, but you probably want # 'publish_final_grades' self.recompute_student_scores_without_send_later enrollments = self.student_enrollments.scoped({:include => [:user, :course_section]}).find(:all, :order => User.sortable_name_order_by_clause('users')) errors = [] posts_to_make = [] posted_enrollment_ids = [] all_enrollment_ids = enrollments.map(&:id) begin raise "final grade publishing disabled" unless Canvas::Plugin.find!('grade_export').enabled? settings = Canvas::Plugin.find!('grade_export').settings raise "endpoint undefined" if settings[:publish_endpoint].blank? format_settings = Course.valid_grade_export_types[settings[:format_type]] raise "unknown format type: #{settings[:format_type]}" unless format_settings raise "grade publishing requires a grading standard" if !self.grading_standard_enabled? && format_settings[:requires_grading_standard] publishing_pseudonym = publishing_user.sis_pseudonym_for(self) raise "publishing disallowed for this publishing user" if publishing_pseudonym.nil? and format_settings[:requires_publishing_pseudonym] callback = Course.valid_grade_export_types[settings[:format_type]][:callback] posts_to_make = callback.call(self, enrollments, publishing_user, publishing_pseudonym) rescue => e Enrollment.update_all({ :grade_publishing_status => "error", :grade_publishing_message => "#{e}"}, { :id => all_enrollment_ids }) raise e end posts_to_make.each do |enrollment_ids, res, mime_type| begin posted_enrollment_ids += enrollment_ids SSLCommon.post_data(settings[:publish_endpoint], res, mime_type) Enrollment.update_all({ :grade_publishing_status => (should_kick_off_grade_publishing_timeout? ? "publishing" : "published"), :grade_publishing_message => nil }, { :id => enrollment_ids }) rescue => e errors << e Enrollment.update_all({ :grade_publishing_status => "error", :grade_publishing_message => "#{e}"}, { :id => enrollment_ids }) end end Enrollment.update_all({ :grade_publishing_status => "unpublishable", :grade_publishing_message => nil }, { :id => (all_enrollment_ids.to_set - posted_enrollment_ids.to_set).to_a }) raise errors[0] if errors.size > 0 end def generate_grade_publishing_csv_output(enrollments, publishing_user, publishing_pseudonym) enrollment_ids = [] res = FasterCSV.generate do |csv| row = ["publisher_id", "publisher_sis_id", "section_id", "section_sis_id", "student_id", "student_sis_id", "enrollment_id", "enrollment_status", "score"] row << "grade" if self.grading_standard_enabled? csv << row enrollments.each do |enrollment| next unless enrollment.computed_final_score enrollment_ids << enrollment.id pseudonym_sis_ids = enrollment.user.pseudonyms.active.find_all_by_account_id(self.root_account_id).map{|p| p.sis_user_id} pseudonym_sis_ids = [nil] if pseudonym_sis_ids.empty? pseudonym_sis_ids.each do |pseudonym_sis_id| row = [publishing_user.try(:id), publishing_pseudonym.try(:sis_user_id), enrollment.course_section.id, enrollment.course_section.sis_source_id, enrollment.user.id, pseudonym_sis_id, enrollment.id, enrollment.workflow_state, enrollment.computed_final_score] row << enrollment.computed_final_grade if self.grading_standard_enabled? csv << row end end end return [[enrollment_ids, res, "text/csv"]] end def expire_pending_grade_publishing_statuses(last_publish_attempt_at) self.student_enrollments.scoped(:conditions => ["grade_publishing_status IN ('pending', 'publishing') AND last_publish_attempt_at = ?", last_publish_attempt_at]).update_all :grade_publishing_status => 'error', :grade_publishing_message => "Timed out." end def gradebook_to_csv(options = {}) if options[:assignment_id] assignments = [self.assignments.active.gradeable.find(options[:assignment_id])] else group_order = {} self.assignment_groups.active.each_with_index{|group, idx| group_order[group.id] = idx} assignments = self.assignments.active.gradeable.find(:all).sort_by{|a| [a.due_at ? 1 : 0, a.due_at || 0, group_order[a.assignment_group_id] || 0, a.position || 0, a.title || ""]} end single = assignments.length == 1 student_enrollments = self.student_enrollments.scoped({:include => [:user, :course_section]}).find(:all, :order => User.sortable_name_order_by_clause('users')) # remove duplicate enrollments for students enrolled in multiple sections seen_users = [] student_enrollments.reject! { |e| seen_users.include?(e.user_id) ? true : (seen_users << e.user_id; false) } submissions = self.submissions.inject({}) { |h, sub| h[[sub.user_id, sub.assignment_id]] = sub; h } read_only = t('csv.read_only_field', '(read only)') t 'csv.student', 'Student' t 'csv.id', 'ID' t 'csv.sis_user_id', 'SIS User ID' t 'csv.sis_login_id', 'SIS Login ID' t 'csv.section', 'Section' t 'csv.comments', 'Comments' t 'csv.current_score', 'Current Score' t 'csv.final_score', 'Final Score' t 'csv.final_grade', 'Final Grade' t 'csv.points_possible', 'Points Possible' res = FasterCSV.generate do |csv| #First row row = ["Student", "ID"] row.concat(["SIS User ID", "SIS Login ID"]) if options[:include_sis_id] row << "Section" row.concat(assignments.map{|a| single ? [a.title_with_id, 'Comments'] : a.title_with_id}) row.concat(["Current Score", "Final Score"]) row.concat(["Final Grade"]) if self.grading_standard_enabled? csv << row.flatten #Possible muted row if assignments.any?(&:muted) #This is is not translated since we look for this exact string when we upload to gradebook. row = ['Muted assignments do not impact Current and Final score columns', '', ''] row.concat(['', '']) if options[:include_sis_id] row.concat(assignments.map{|a| single ? [(a.muted ? 'Muted': ''), ''] : (a.muted ? 'Muted' : '')}) row.concat(['', '']) row.concat(['']) if self.grading_standard_enabled? csv << row.flatten end #Second Row row = [" Points Possible", "", ""] row.concat(["", ""]) if options[:include_sis_id] row.concat(assignments.map{|a| single ? [a.points_possible, ''] : a.points_possible}) row.concat([read_only, read_only]) row.concat([read_only]) if self.grading_standard_enabled? csv << row.flatten student_enrollments.each do |student_enrollment| student = student_enrollment.user student_section = (student_enrollment.course_section.display_name rescue nil) || "" student_submissions = assignments.map do |a| submission = submissions[[student.id, a.id]] score = submission && submission.score ? submission.score : "" data = [score, ''] rescue ["", ''] single ? data : data[0] end #Last Row row = [student.last_name_first, student.id] row.concat([student.pseudonym.try(:sis_user_id), student.pseudonym.try(:unique_id)]) if options[:include_sis_id] row << student_section row.concat(student_submissions) row.concat([student_enrollment.computed_current_score, student_enrollment.computed_final_score]) if self.grading_standard_enabled? row.concat([score_to_grade(student_enrollment.computed_final_score)]) end csv << row.flatten end end end # included to make it easier to work with api, which returns # sis_source_id as sis_course_id. alias_attribute :sis_course_id, :sis_source_id def grading_standard_title if self.grading_standard_enabled? self.grading_standard.try(:title) || t('default_grading_scheme_name', "Default Grading Scheme") else nil end end def score_to_grade(score) return nil unless self.grading_standard_enabled? && score scheme = self.grading_standard.try(:data) || GradingStandard.default_grading_standard GradingStandard.score_to_grade(scheme, score) end def participants (participating_admins + participating_students).uniq end def enroll_user(user, type='StudentEnrollment', opts={}) enrollment_state = opts[:enrollment_state] section = opts[:section] limit_privileges_to_course_section = opts[:limit_privileges_to_course_section] section ||= self.default_section enrollment_state ||= self.available? ? "invited" : "creation_pending" enrollment_state = 'invited' if enrollment_state == 'creation_pending' && (type == 'TeacherEnrollment' || type == 'TaEnrollment' || type == 'DesignerEnrollment') e = self.enrollments.find_by_user_id_and_type(user.id, type) if user e.attributes = { :workflow_state => 'invited', :course_section => section, :limit_privileges_to_course_section => limit_privileges_to_course_section } if e && (e.completed? || e.rejected?) e ||= self.send(type.underscore.pluralize).build(:user => user, :workflow_state => enrollment_state, :course_section => section, :limit_privileges_to_course_section => limit_privileges_to_course_section) if e.changed? if opts[:no_notify] e.save_without_broadcasting else e.save end end e.user = user self.claim if self.created? && e && e.admin? user.try(:touch) unless opts[:skip_touch_user] e end def enroll_student(user, opts={}) enroll_user(user, 'StudentEnrollment', opts) end def enroll_ta(user) enroll_user(user, 'TaEnrollment') end def enroll_designer(user) enroll_user(user, 'DesignerEnrollment') end def enroll_teacher(user) enroll_user(user, 'TeacherEnrollment') end def resubmission_for(asset_string) instructors.each{|u| u.ignored_item_changed!(asset_string, 'grading') } end def grading_standard_enabled !!self.grading_standard_id end alias_method :grading_standard_enabled?, :grading_standard_enabled def grading_standard_enabled=(val) if Canvas::Plugin.value_to_boolean(val) self.grading_standard_id ||= 0 else self.grading_standard = self.grading_standard_id = nil end end def gradebook_json hash = self.as_json(:include_root => false) submissions = Hash.new { |h,k| h[k] = [] } self.submissions.each { |s| submissions[s.user_id] << s } hash['active_assignments'] = self.active_assignments.map{|a| a.as_json(:include_root => false) } hash['students'] = self.students.map do |user| res = user.as_json(:include_root => false) res['submissions'] = submissions[user.id].map{|s| s.as_json(:include_root => false) } res end hash.to_json end def add_aggregate_entries(entries, feed) if feed.feed_purpose == 'announcements' entries.each do |entry| user = entry.user || feed.user # If already existed and has been updated if entry.entry_changed? && entry.asset entry.asset.update_attributes( :title => entry.title, :message => entry.message ) elsif !entry.asset announcement = self.announcements.build( :title => entry.title, :message => entry.message ) announcement.user = user announcement.save entry.update_attributes(:asset => announcement) end end elsif feed.feed_purpose == 'calendar' entries.each do |entry| user = entry.user || feed.user # If already existed and has been updated if entry.entry_changed? && entry.asset event = entry.asset event.attributes = { :title => entry.title, :description => entry.message, :start_at => entry.start_at, :end_at => entry.end_at } event.workflow_state = 'cancelled' if entry.cancelled? event.save elsif entry.active? && !entry.asset event = self.calendar_events.build( :title => entry.title, :description => entry.message, :start_at => entry.start_at, :end_at => entry.end_at ) event.workflow_state = 'read_only' event.workflow_state = 'cancelled' if entry.cancelled? event.save entry.update_attributes(:asset => event) end end end end def readable_default_wiki_editing_roles roles = self.default_wiki_editing_roles || "teachers" case roles when 'teachers' t('wiki_permissions.only_teachers', 'Only Teachers') when 'teachers,students' t('wiki_permissions.teachers_students', 'Teacher and Students') when 'teachers,students,public' t('wiki_permissions.all', 'Anyone') else t('wiki_permissions.only_teachers', 'Only Teachers') end end def default_section self.course_sections.active.find_or_create_by_default_section(true) do |section| section.course = self section.root_account = self.root_account end end def assert_section if self.course_sections.active.empty? default = self.default_section default.workflow_state = 'active' default.save end end def file_structure_for(user) User.file_structure_for(self, user) end def merge_in(course, options = {}, import = nil) return [] if course == self res = merge_into_course(course, options, import) course.course_sections.active.each do |section| if options[:all_sections] || options[section.asset_string.to_sym] section.move_to_course(self) end end res end def self.copy_authorized_content(html, to_context, user) return html unless to_context pairs = [] content_types_to_copy = ['files'] matches = html.scan(/\/(courses|groups|users)\/(\d+)\/(\w+)/) do |match| pairs << [match[0].singularize, match[1].to_i] if content_types_to_copy.include?(match[2]) end pairs = pairs.select{|p| p[0] != to_context.class.to_s || p[1] != to_context.id } pairs.uniq.each do |context_type, id| context = Context.find_by_asset_string("#{context_type}_#{id}") rescue nil if context if context.grants_right?(user, nil, :manage_content) html = self.migrate_content_links(html, context, to_context, content_types_to_copy) else html = self.migrate_content_links(html, context, to_context, content_types_to_copy, user) end end end html end def turnitin_settings # check if somewhere up the account chain turnitin is enabled and # has valid settings self.account.turnitin_settings end def turnitin_pledge self.account.closest_turnitin_pledge end def all_turnitin_comments comments = self.account.closest_turnitin_comments || "" if self.turnitin_comments && !self.turnitin_comments.empty? comments += "\n\n" if comments && !comments.empty? comments += self.turnitin_comments end self.extend TextHelper format_message(comments).first end def turnitin_enabled? !!self.turnitin_settings end def self.find_or_create_for_new_context(obj_class, new_context, old_context, old_id) association_name = obj_class.table_name old_item = old_context.send(association_name).find_by_id(old_id) res = new_context.send(association_name).first(:conditions => { :cloned_item_id => old_item.cloned_item_id}, :order => 'id desc') if old_item if !res && old_item # make sure it's active by re-finding it with the active scope ... active old_item = old_context.send(association_name).active.find_by_id(old_item.id) res = old_item.clone_for(new_context) if old_item res.save if res end res end def self.migrate_content_links(html, from_context, to_context, supported_types=nil, user_to_check_for_permission=nil) return html unless html.present? && to_context from_name = from_context.class.name.tableize to_name = to_context.class.name.tableize @merge_mappings ||= {} rewriter = UserContent::HtmlRewriter.new(from_context, user_to_check_for_permission) limit_migrations_to_listed_types = !!supported_types rewriter.allowed_types = %w(assignments calendar_events discussion_topics collaborations files conferences quizzes groups modules) rewriter.set_default_handler do |match| new_url = match.url next(new_url) if supported_types && !supported_types.include?(match.type) new_id = @merge_mappings["#{match.obj_class.name.underscore}_#{match.obj_id}"] next(new_url) unless rewriter.user_can_view_content? { match.obj_class.find_by_id(match.obj_id) } if !new_id && to_context != from_context new_obj = self.find_or_create_for_new_context(match.obj_class, to_context, from_context, match.obj_id) new_id = new_obj.id if new_obj end if !limit_migrations_to_listed_types || new_id new_url = new_url.gsub("#{match.type}/#{match.obj_id}", new_id ? "#{match.type}/#{new_id}" : "#{match.type}") end new_url.gsub("/#{from_name}/#{from_context.id}", "/#{to_name}/#{to_context.id}") end rewriter.set_unknown_handler do |match| match.url.gsub("/#{from_name}/#{from_context.id}", "/#{to_name}/#{to_context.id}") end html = rewriter.translate_content(html) if !limit_migrations_to_listed_types # for things like calendar urls, swap out the old context id with the new one regex = Regexp.new("include_contexts=[^\\s&]*#{from_context.asset_string}") html = html.gsub(regex) do |match| match.gsub("#{from_context.asset_string}", "#{to_context.asset_string}") end # swap out the old host with the new host html = html.gsub(HostUrl.context_host(from_context), HostUrl.context_host(to_context)) end html end def migrate_content_links(html, from_course) Course.migrate_content_links(html, from_course, self) end attr_accessor :merge_results def log_merge_result(text) @merge_results ||= [] logger.debug text @merge_results << text end def warn_merge_result(text) log_merge_result(text) end def bool_res(val) Canvas::Plugin.value_to_boolean(val) end def process_migration_files(data, migration) return unless data['all_files_export'] && data['all_files_export']['file_path'] return unless File.exist?(data['all_files_export']['file_path']) self.attachment_path_id_lookup ||= {} params = migration.migration_settings[:migration_ids_to_import] valid_paths = [] (data['file_map'] || {}).each do |id, file| if !migration.context.attachments.detect { |f| f.migration_id == file['migration_id'] } || migration.migration_settings[:files_import_allow_rename] path = file['path_name'].starts_with?('/') ? file['path_name'][1..-1] : file['path_name'] self.attachment_path_id_lookup[path] = file['migration_id'] if params[:copy][:files] valid_paths << path if (bool_res(params[:copy][:files][file['migration_id'].to_sym]) rescue false) else valid_paths << path end end end valid_paths = [0] if valid_paths.empty? && params[:copy] && params[:copy][:files] logger.debug "adding #{valid_paths.length} files" total = valid_paths.length if valid_paths != [0] current = 0 last = current callback = Proc.new do current += 1 if (current - last) > 10 last = current migration.fast_update_progress((current.to_f/total) * 18.0) end end unzip_opts = { :course => migration.context, :filename => data['all_files_export']['file_path'], :valid_paths => valid_paths, :callback => callback, :logger => logger, :rename_files => migration.migration_settings[:files_import_allow_rename], :migration_id_map => self.attachment_path_id_lookup, } if root_path = migration.migration_settings[:files_import_root_path] unzip_opts[:root_directory] = Folder.assert_path( root_path, migration.context) end unzipper = UnzipAttachment.new(unzip_opts) migration.fast_update_progress(1.0) unzipper.process end end private :process_migration_files def import_media_objects(mo_attachments, migration) wait_for_completion = (migration && migration.migration_settings[:worker_class] == CC::Importer::Canvas::Converter.name) unless mo_attachments.blank? MediaObject.add_media_files(mo_attachments, wait_for_completion) end end def import_from_migration(data, params, migration) params ||= {:copy=>{}} logger.debug "starting import" @full_migration_hash = data @external_url_hash = {} @migration_results = [] @content_migration = migration (data['web_link_categories'] || []).map{|c| c['links'] }.flatten.each do |link| @external_url_hash[link['link_id']] = link end ActiveRecord::Base.skip_touch_context @imported_migration_items = [] # These only need to be processed once Attachment.skip_media_object_creation do process_migration_files(data, migration); migration.fast_update_progress(18) Attachment.process_migration(data, migration); migration.fast_update_progress(20) mo_attachments = self.imported_migration_items.find_all { |i| i.is_a?(Attachment) && i.media_entry_id.present? } import_media_objects(mo_attachments, migration) end # needs to happen after the files are processed, so that they are available in the syllabus import_settings_from_migration(data); migration.fast_update_progress(21) migration.fast_update_progress(30) question_data = AssessmentQuestion.process_migration(data, migration); migration.fast_update_progress(35) Group.process_migration(data, migration); migration.fast_update_progress(36) LearningOutcome.process_migration(data, migration); migration.fast_update_progress(37) Rubric.process_migration(data, migration); migration.fast_update_progress(38) @assignment_group_no_drop_assignments = {} AssignmentGroup.process_migration(data, migration); migration.fast_update_progress(39) ExternalFeed.process_migration(data, migration); migration.fast_update_progress(39.5) GradingStandard.process_migration(data, migration); migration.fast_update_progress(40) Quiz.process_migration(data, migration, question_data); migration.fast_update_progress(50) ContextExternalTool.process_migration(data, migration); migration.fast_update_progress(54) #These need to be ran twice because they can reference each other DiscussionTopic.process_migration(data, migration);migration.fast_update_progress(55) WikiPage.process_migration(data, migration);migration.fast_update_progress(60) Assignment.process_migration(data, migration);migration.fast_update_progress(65) ContextModule.process_migration(data, migration);migration.fast_update_progress(70) # and second time... DiscussionTopic.process_migration(data, migration);migration.fast_update_progress(75) WikiPage.process_migration(data, migration);migration.fast_update_progress(80) Assignment.process_migration(data, migration);migration.fast_update_progress(85) #These aren't referenced by anything, but reference other things CalendarEvent.process_migration(data, migration);migration.fast_update_progress(90) WikiPage.process_migration_course_outline(data, migration);migration.fast_update_progress(95) begin #Adjust dates if bool_res(params[:copy][:shift_dates]) shift_options = (bool_res(params[:copy][:shift_dates]) rescue false) ? params[:copy] : {} shift_options = shift_date_options(self, shift_options) @imported_migration_items.each do |event| if event.is_a?(Assignment) event.due_at = shift_date(event.due_at, shift_options) event.lock_at = shift_date(event.lock_at, shift_options) event.unlock_at = shift_date(event.unlock_at, shift_options) event.peer_reviews_due_at = shift_date(event.peer_reviews_due_at, shift_options) event.save_without_broadcasting! elsif event.is_a?(DiscussionTopic) event.delayed_post_at = shift_date(event.delayed_post_at, shift_options) event.save_without_broadcasting! elsif event.is_a?(CalendarEvent) event.start_at = shift_date(event.start_at, shift_options) event.end_at = shift_date(event.end_at, shift_options) event.save_without_broadcasting! elsif event.is_a?(Quiz) event.due_at = shift_date(event.due_at, shift_options) event.lock_at = shift_date(event.lock_at, shift_options) event.unlock_at = shift_date(event.unlock_at, shift_options) event.save! end end end rescue add_migration_warning("Couldn't adjust the due dates.", $!) end migration.progress=100 migration.migration_settings ||= {} migration.migration_settings[:imported_assets] = @imported_migration_items.map(&:asset_string) migration.workflow_state = :imported migration.save ActiveRecord::Base.skip_touch_context(false) self.touch @imported_migration_items end attr_accessor :imported_migration_items, :full_migration_hash, :external_url_hash, :content_migration attr_accessor :folder_name_lookups, :attachment_path_id_lookup, :assignment_group_no_drop_assignments def import_settings_from_migration(data) return unless data[:course] settings = data[:course] self.conclude_at = Canvas::Migration::MigratorHelper.get_utc_time_from_timestamp(settings[:conclude_at]) if settings[:conclude_at] self.start_at = Canvas::Migration::MigratorHelper.get_utc_time_from_timestamp(settings[:start_at]) if settings[:start_at] self.syllabus_body = ImportedHtmlConverter.convert(settings[:syllabus_body], self) if settings[:syllabus_body] atts = Course.clonable_attributes atts -= Canvas::Migration::MigratorHelper::COURSE_NO_COPY_ATTS settings.slice(*atts.map(&:to_s)).each do |key, val| self.send("#{key}=", val) end end def add_migration_warning(message, exception='') return unless @content_migration @content_migration.add_warning(message, exception) end def backup_to_json backup.to_json end def backup res = [] res += self.folders.active res += self.attachments.active res += self.assignment_groups.active res += self.assignments.active res += self.submissions res += self.quizzes res += self.discussion_topics.active res += self.discussion_entries.active res += self.wiki.wiki_pages.active res += self.calendar_events.active res end def may_have_links_to_migrate(item) @to_migrate_links ||= [] @to_migrate_links << item end def map_merge(old_item, new_item) @merge_mappings ||= {} @merge_mappings[old_item.asset_string] = new_item && new_item.id end def merge_mapped_id(old_item) @merge_mappings ||= {} return nil unless old_item return @merge_mappings[old_item] if old_item.is_a?(String) @merge_mappings[old_item.asset_string] end def same_dates?(old, new, columns) old && new && columns.all?{|column| old.respond_to?(column) && new.respond_to?(column) && old.send(column) == new.send(column) } end attr_accessor :merge_mappings COPY_OPTIONS = [:all_course_settings, :all_assignments, :all_external_tools, :all_files, :all_topics, :all_calendar_events, :all_quizzes, :all_wiki_pages, :all_modules, :all_outcomes] def merge_into_course(course, options, course_import = nil) @merge_mappings = {} @merge_results = [] to_shift_dates = [] @to_migrate_links = [] added_items = [] delete_placeholder = nil if bool_res(options[:course_settings]) || bool_res(options[:all_course_settings]) #Copy the course settings too course.attributes.slice(*Course.clonable_attributes.map(&:to_s)).keys.each do |attr| self.send("#{attr}=", course.send(attr)) end may_have_links_to_migrate(self) self.save end if self.assignment_groups.length == 1 && self.assignment_groups.first.name == t('#assignment_group.default_name', "Assignments") && self.assignment_groups.first.assignments.empty? delete_placeholder = self.assignment_groups.first self.group_weighting_scheme = course.group_weighting_scheme elsif self.assignment_groups.length == 0 self.group_weighting_scheme = course.group_weighting_scheme end # There are groups to migrate course.assignment_groups.active.each do |group| if bool_res(options[:everything]) || bool_res(options[:all_assignments]) || bool_res(options[group.asset_string.to_sym]) new_group = group.clone_for(self) added_items << new_group new_group.save_without_broadcasting! map_merge(group, new_group) end end course.context_external_tools.active.each do |old_tool| course_import.tick(82) if course_import if bool_res(options[:everything]) || bool_res(options[:all_external_tools]) || bool_res(options[old_tool.asset_string.to_sym]) new_tool = old_tool.clone_for(self) new_tool.save added_items << new_tool end end course.assignments.no_graded_quizzes_or_topics.active.select{|a| a.assignment_group_id }.each do |assignment| course_import.tick(15) if course_import if bool_res(options[:everything]) || bool_res(options[:all_assignments]) || bool_res(options[assignment.asset_string.to_sym]) new_assignment = assignment.clone_for(self, nil, :migrate => false) to_shift_dates << new_assignment if new_assignment.clone_updated || same_dates?(assignment, new_assignment, [:due_at, :lock_at, :unlock_at, :peer_reviews_due_at]) added_items << new_assignment new_assignment.save_without_broadcasting! map_merge(assignment, new_assignment) end end # next, attachments map_merge(Folder.root_folders(course).first, Folder.root_folders(self).first) course.attachments.all(:conditions => "file_state <> 'deleted'").each do |file| course_import.tick(30) if course_import if bool_res(options[:everything] ) || bool_res(options[:all_files] ) || bool_res(options[file.asset_string.to_sym] ) new_file = file.clone_for(self) added_items << new_file new_folder_id = merge_mapped_id(file.folder) # make sure the file has somewhere to go if !new_folder_id # gather mapping of needed folders from old course to new course old_folders = [] old_folders << file.folder new_folders = [] new_folders << old_folders.last.clone_for(self, nil, options.merge({:include_subcontent => false})) while old_folders.last.parent_folder && old_folders.last.parent_folder.parent_folder_id && !merge_mapped_id(old_folders.last.parent_folder) old_folders << old_folders.last.parent_folder new_folders << old_folders.last.clone_for(self, nil, options.merge({:include_subcontent => false})) end added_items += new_folders old_folders.reverse! new_folders.reverse! # try to use folders that already match if possible final_new_folders = [] parent_folder = Folder.root_folders(self).first old_folders.each_with_index do |folder, idx| if f = parent_folder.active_sub_folders.find_by_name(folder.name) final_new_folders << f else final_new_folders << new_folders[idx] end parent_folder = final_new_folders.last end # add or update the folder structure needed for the file final_new_folders.first.parent_folder_id ||= merge_mapped_id(old_folders.first.parent_folder) || Folder.root_folders(self).first.id old_folders.each_with_index do |folder, idx| final_new_folders[idx].save! map_merge(folder, final_new_folders[idx]) final_new_folders[idx + 1].parent_folder_id ||= final_new_folders[idx].id if final_new_folders[idx + 1] end new_folder_id = merge_mapped_id(file.folder) end new_file.folder_id = new_folder_id new_file.save_without_broadcasting! map_merge(file, new_file) end end course.discussion_topics.active.each do |topic| course_import.tick(40) if course_import if bool_res(options[:everything] ) || bool_res(options[:all_topics] ) || bool_res(options[topic.asset_string.to_sym] ) || (topic.assignment_id && bool_res(options["assignment_#{topic.assignment_id}"])) include_entries = options["discussion_topic_#{topic.id}_entries"] == "1" new_topic = topic.clone_for(self, nil, :migrate => bool_res(options["#{topic.asset_string}_entries".to_sym] ), :include_entries => include_entries) to_shift_dates << new_topic if new_topic.delayed_post_at && (new_topic.clone_updated || same_dates?(topic, new_topic, [:delayed_post_at])) to_shift_dates << new_topic.assignment if new_topic.assignment && (new_topic.assignment_clone_updated || same_dates?(topic.assignment, new_topic.assignment, [:due_at, :lock_at, :unlock_at, :peer_reviews_due_at])) added_items << new_topic added_items << new_topic.assignment if new_topic.assignment new_topic.save_without_broadcasting! map_merge(topic, new_topic) end end course.calendar_events.active.each do |event| course_import.tick(50) if course_import if bool_res(options[:everything] ) || bool_res(options[:all_calendar_events] ) || bool_res(options[event.asset_string.to_sym] ) new_event = event.clone_for(self, nil, :migrate => false) to_shift_dates << new_event if new_event.clone_updated || same_dates?(event, new_event, [:start_at, :end_at]) added_items << new_event new_event.save_without_broadcasting! map_merge(event, new_event) end end course.quizzes.active.each do |quiz| course_import.tick(60) if course_import if bool_res(options[:everything] ) || bool_res(options[:all_quizzes] ) || bool_res(options[quiz.asset_string.to_sym] ) || (quiz.assignment_id && bool_res(options["assignment_#{quiz.assignment_id}"])) new_quiz = quiz.clone_for(self) to_shift_dates << new_quiz if new_quiz.clone_updated || same_dates?(quiz, new_quiz, [:due_at, :lock_at, :unlock_at]) added_items << new_quiz added_items << new_quiz.assignment if new_quiz.assignment new_quiz.save! map_merge(quiz, new_quiz) end end course.wiki_namespaces.each do |wiki_namespace| wiki_namespace.wiki.wiki_pages.each do |page| course_import.tick(70) if course_import if bool_res(options[:everything] ) || bool_res(options[:all_wiki_pages] ) || bool_res(options[page.asset_string.to_sym] ) if page.title.blank? next if page.body.blank? page.title = t('#wiki_page.missing_name', "Unnamed Page") end new_page = page.clone_for(self, nil, :migrate => false, :old_context => course) added_items << new_page new_page.wiki_id = self.wiki.id new_page.ensure_unique_title log_merge_result("Wiki Page \"#{page.title}\" renamed to \"#{new_page.title}\"") if new_page.title != page.title new_page.save_without_broadcasting! map_merge(page, new_page) end end end course.context_modules.active.each do |mod| course_import.tick(80) if course_import if bool_res(options[:everything] ) || bool_res(options[:all_modules] ) || bool_res(options[mod.asset_string.to_sym] ) new_mod = mod.clone_for(self) to_shift_dates << new_mod if new_mod.clone_updated || same_dates?(mod, new_mod, [:unlock_at, :start_at, :end_at]) new_mod.save! added_items << new_mod map_merge(mod, new_mod) end end orig_root = LearningOutcomeGroup.default_for(course) new_root = LearningOutcomeGroup.default_for(self) orig_root.sorted_content.each do |item| course_import.tick(85) if course_import use_outcome = lambda {|lo| bool_res(options[:everything] ) || bool_res(options[:all_outcomes] ) || bool_res(options[lo.asset_string.to_sym] ) } if item.is_a? LearningOutcome next unless use_outcome[item] lo = item.clone_for(self, new_root) added_items << lo else f = item.clone_for(self, new_root, use_outcome) added_items << f if f end end # Groups could be created by objects with attached assignments as well. (like quizzes/topics) # So don't delete the placeholder until everything has been cloned delete_placeholder.destroy if delete_placeholder && self.assignment_groups.length > 1 @to_migrate_links.uniq.each do |obj| course_import.tick(90) if course_import if obj.is_a?(Assignment) obj.description = migrate_content_links(obj.description, course) elsif obj.is_a?(CalendarEvent) obj.description = migrate_content_links(obj.description, course) elsif obj.is_a?(DiscussionTopic) obj.message = migrate_content_links(obj.message, course) obj.discussion_entries.each do |entry| entry.message = migrate_content_links(obj.message, course) entry.save_without_broadcasting! end elsif obj.is_a?(WikiPage) obj.body = migrate_content_links(obj.body, course) elsif obj.is_a?(Quiz) obj.description = migrate_content_links(obj.description, course) elsif obj.is_a?(Course) obj.syllabus_body = migrate_content_links(obj.syllabus_body, course) end obj.save_without_broadcasting! rescue obj.save! end if !to_shift_dates.empty? && bool_res(options[:shift_dates]) log_merge_result("Moving events to new dates") shift_options = (bool_res(options[:shift_dates]) rescue false) ? options : {} shift_options = shift_date_options(course, shift_options) to_shift_dates.uniq.each do |event| course_import.tick(100) if course_import if event.is_a?(Assignment) event.due_at = shift_date(event.due_at, shift_options) event.lock_at = shift_date(event.lock_at, shift_options) event.unlock_at = shift_date(event.unlock_at, shift_options) event.peer_reviews_due_at = shift_date(event.peer_reviews_due_at, shift_options) elsif event.is_a?(DiscussionTopic) event.delayed_post_at = shift_date(event.delayed_post_at, shift_options) log_merge_result("The Topic \"#{event.title}\" won't be posted until #{event.delayed_post_at.to_s}") elsif event.is_a?(CalendarEvent) event.start_at = shift_date(event.start_at, shift_options) event.end_at = shift_date(event.end_at, shift_options) elsif event.is_a?(Quiz) event.due_at = shift_date(event.due_at, shift_options) event.lock_at = shift_date(event.lock_at, shift_options) event.unlock_at = shift_date(event.unlock_at, shift_options) elsif event.is_a?(ContextModule) event.unlock_at = shift_date(event.unlock_at, shift_options) event.start_at = shift_date(event.start_at, shift_options) event.end_at = shift_date(event.end_at, shift_options) end event.respond_to?(:save_without_broadcasting!) ? event.save_without_broadcasting! : event.save! end self.start_at ||= shift_options[:new_start_date] self.conclude_at ||= shift_options[:new_end_date] end self.save if course_import course_import.added_item_codes = added_items.map{|i| i.asset_string } course_import.log = merge_results course_import.save! end added_items.map{|i| i.asset_string } end def self.clonable_attributes [ :group_weighting_scheme, :grading_standard_id, :is_public, :publish_grades_immediately, :allow_student_wiki_edits, :allow_student_assignment_edits, :hashtag, :show_public_context_messages, :syllabus_body, :allow_student_forum_attachments, :default_wiki_editing_roles, :allow_student_organized_groups, :default_view, :show_all_discussion_entries, :open_enrollment, :storage_quota, :tab_configuration, :allow_wiki_comments, :turnitin_comments, :self_enrollment, :license, :indexed, :settings ] end def clone_for(account, opts={}) new_course = Course.new root_account = account.root_account self.attributes.delete_if{|k,v| [:id, :section, :account_id, :workflow_state, :created_at, :updated_at, :root_account_id, :enrollment_term_id, :sis_source_id, :sis_batch_id].include?(k.to_sym) }.each do |key, val| new_course.send("#{key}=", val) end new_course.workflow_state = 'created' new_course.name = opts[:name] if opts[:name] new_course.account_id = account.id new_course.root_account_id = root_account.id new_course.enrollment_term_id = opts[:enrollment_term_id] new_course.abstract_course_id = self.abstract_course_id new_course.save! if opts[:copy_content] new_course.send_later(:merge_into_course, self, :everything => true) end new_course end def assert_assignment_group has_group = Rails.cache.fetch(['has_assignment_group', self.id].cache_key) do self.assignment_groups.active.count > 0 end if !has_group group = self.assignment_groups.new :name => t('#assignment_group.default_name', "Assignments"), :position => 1 group.save end end def shift_date_options(course, options={}) result = {} result[:old_start_date] = Date.parse(options[:old_start_date]) rescue course.real_start_date result[:old_end_date] = Date.parse(options[:old_end_date]) rescue course.real_end_date result[:new_start_date] = Date.parse(options[:new_start_date]) rescue self.real_start_date result[:new_end_date] = Date.parse(options[:new_end_date]) rescue self.real_end_date result[:day_substitutions] = options[:day_substitutions] result end def shift_date(time, options={}) return nil unless time time = ActiveSupport::TimeWithZone.new(time.utc, Time.zone) old_date = time.to_date new_date = old_date.clone old_start_date = options[:old_start_date] old_end_date = options[:old_end_date] new_start_date = options[:new_start_date] new_end_date = options[:new_end_date] return time unless old_start_date && old_end_date && new_start_date && new_end_date old_full_diff = old_end_date - old_start_date old_event_diff = old_date - old_start_date old_event_percent = old_full_diff > 0 ? old_event_diff.to_f / old_full_diff.to_f : 0 new_full_diff = new_end_date - new_start_date new_event_diff = (new_full_diff.to_f * old_event_percent).to_i new_date = new_start_date + new_event_diff options[:day_substitutions] ||= {} options[:day_substitutions][old_date.wday.to_s] ||= old_date.wday.to_s if options[:day_substitutions] && options[:day_substitutions][old_date.wday.to_s] if new_date.wday != options[:day_substitutions][old_date.wday.to_s].to_i new_date += (options[:day_substitutions][old_date.wday.to_s].to_i - new_date.wday) % 7 new_date -= 7 unless new_date - 7 < new_start_date end end new_time = ActiveSupport::TimeWithZone.new(Time.utc(new_date.year, new_date.month, new_date.day, (time.hour rescue 0), (time.min rescue 0)), Time.zone) - Time.zone.utc_offset log_merge_result("Events for #{old_date.to_s} moved to #{new_date.to_s}") new_time end def real_start_date return self.start_at.to_date if self.start_at all_dates.min end def all_dates (self.calendar_events.active + self.assignments.active).inject([]) {|list, e| list << e.end_at if e.end_at list << e.start_at if e.start_at list }.compact.flatten.map{|d| d.to_date }.uniq rescue [] end def real_end_date return self.conclude_at.to_date if self.conclude_at all_dates.max end def is_a_context? true end def self.serialization_excludes; [:uuid]; end def page_views_by_day(options={}) conditions = { :context_id => self.id, :context_type => self.class.to_s } if options[:dates] conditions.merge!({ :created_at => (options[:dates].first)..(options[:dates].last) }) end PageView.count( :group => "date(created_at)", :conditions => conditions ) end memoize :page_views_by_day def section_visibilities_for(user) Rails.cache.fetch(['section_visibilities_for', user, self].cache_key) do Enrollment.find(:all, :select => "course_section_id, limit_privileges_to_course_section, type, associated_user_id", :conditions => ['user_id = ? AND course_id = ? AND workflow_state != ?', user.id, self.id, 'deleted']).map{|e| {:course_section_id => e.course_section_id, :limit_privileges_to_course_section => e.limit_privileges_to_course_section, :type => e.type, :associated_user_id => e.associated_user_id } } end end memoize :section_visibilities_for def visibility_limited_to_course_sections?(user, visibilities = section_visibilities_for(user)) !visibilities.any?{|s| !s[:limit_privileges_to_course_section] } end # returns a scope, not an array of users/enrollments def students_visible_to(user, include_priors=false) enrollments_visible_to(user, include_priors, true) end def enrollments_visible_to(user, include_priors=false, return_users=false, limit_to_section_ids=nil) visibilities = section_visibilities_for(user) if return_users scope = include_priors ? self.all_students : self.students else scope = include_priors ? self.all_student_enrollments : self.student_enrollments end if limit_to_section_ids scope = scope.scoped(:conditions => { 'enrollments.course_section_id' => limit_to_section_ids.to_a }) end # See also Users#messageable_users (same logic used to get users across multiple courses) case enrollment_visibility_level_for(user, visibilities) when :full then scope when :sections then scope.scoped({:conditions => "enrollments.course_section_id IN (#{visibilities.map{|s| s[:course_section_id]}.join(",")})"}) when :restricted then scope.scoped({:conditions => "enrollments.user_id IN (#{(visibilities.map{|s| s[:associated_user_id]}.compact + [user.id]).join(",")})"}) else scope.scoped({:conditions => "FALSE"}) end end def sections_visible_to(user, sections = active_course_sections) visibilities = section_visibilities_for(user) section_ids = visibilities.map{ |s| s[:course_section_id] } case enrollment_visibility_level_for(user, visibilities) when :full if visibilities.all?{ |v| ['StudentEnrollment', 'ObserverEnrollment'].include? v[:type] } return sections.find_all_by_id(section_ids) else return sections end when :sections return sections.find_all_by_id(section_ids) end [] end def enrollment_visibility_level_for(user, visibilities = section_visibilities_for(user)) if visibilities.empty? # i.e. not enrolled if self.grants_rights?(user, nil, :manage_grades, :manage_students, :manage_admin_users, :read_roster) :full else :none end elsif visibilities.all?{ |e| e[:type] == 'ObserverEnrollment' } :restricted # e.g. observers shouldn't see anyone but the observed elsif visibility_limited_to_course_sections?(user, visibilities) :sections else :full end end def page_view_data(options={}) # if they dont supply a date range then use the first day returned by page_views_by_day (which should be the first day that there is pageview statistics gathered) dates = options[:dates].nil? ? [page_views_by_day.sort.first.first.to_datetime, Time.now] : options[:dates] days = [] dates.first.to_datetime.upto(dates.last) do |d| # this * 1000 part is because the Highcharts expects something like what Date.UTC(2006, 2, 28) would give you, # which is MILLISECONDS from the unix epoch, ruby's to_f gives you SECONDS since then. days << [ (d.at_beginning_of_day.to_f * 1000).to_i , page_views_by_day[d.to_date.to_s].to_i ] end days end memoize :page_view_data def unpublished? self.created? || self.claimed? end def only_wiki_is_public self.respond_to?(:wiki_is_public) && self.wiki_is_public && !self.is_public end def reply_from(opts) user = opts[:user] message = opts[:text].strip user = nil unless user && self.context.users.include?(user) if !user raise "Only comment participants may reply to messages" elsif !message || message.empty? raise "Message body cannot be blank" else recipients = self.teachers.map(&:id) - [user.id] conversation = user.initiate_conversation(recipients) conversation.add_message(message) end end def tab_configuration super.map {|h| h.with_indifferent_access } rescue [] end TAB_HOME = 0 TAB_SYLLABUS = 1 TAB_PAGES = 2 TAB_ASSIGNMENTS = 3 TAB_QUIZZES = 4 TAB_GRADES = 5 TAB_PEOPLE = 6 TAB_GROUPS = 7 TAB_DISCUSSIONS = 8 TAB_CHAT = 9 TAB_MODULES = 10 TAB_FILES = 11 TAB_CONFERENCES = 12 TAB_SETTINGS = 13 TAB_ANNOUNCEMENTS = 14 TAB_OUTCOMES = 15 TAB_COLLABORATIONS = 16 def self.default_tabs [ { :id => TAB_HOME, :label => t('#tabs.home', "Home"), :css_class => 'home', :href => :course_path }, { :id => TAB_ANNOUNCEMENTS, :label => t('#tabs.announcements', "Announcements"), :css_class => 'announcements', :href => :course_announcements_path }, { :id => TAB_ASSIGNMENTS, :label => t('#tabs.assignments', "Assignments"), :css_class => 'assignments', :href => :course_assignments_path }, { :id => TAB_DISCUSSIONS, :label => t('#tabs.discussions', "Discussions"), :css_class => 'discussions', :href => :course_discussion_topics_path }, { :id => TAB_GRADES, :label => t('#tabs.grades', "Grades"), :css_class => 'grades', :href => :course_grades_path }, { :id => TAB_PEOPLE, :label => t('#tabs.people', "People"), :css_class => 'people', :href => :course_users_path }, { :id => TAB_CHAT, :label => t('#tabs.chat', "Chat"), :css_class => 'chat', :href => :course_chat_path }, { :id => TAB_PAGES, :label => t('#tabs.pages', "Pages"), :css_class => 'pages', :href => :course_wiki_pages_path }, { :id => TAB_FILES, :label => t('#tabs.files', "Files"), :css_class => 'files', :href => :course_files_path }, { :id => TAB_SYLLABUS, :label => t('#tabs.syllabus', "Syllabus"), :css_class => 'syllabus', :href => :syllabus_course_assignments_path }, { :id => TAB_OUTCOMES, :label => t('#tabs.outcomes', "Outcomes"), :css_class => 'outcomes', :href => :course_outcomes_path }, { :id => TAB_QUIZZES, :label => t('#tabs.quizzes', "Quizzes"), :css_class => 'quizzes', :href => :course_quizzes_path }, { :id => TAB_MODULES, :label => t('#tabs.modules', "Modules"), :css_class => 'modules', :href => :course_context_modules_path }, { :id => TAB_CONFERENCES, :label => t('#tabs.conferences', "Conferences"), :css_class => 'conferences', :href => :course_conferences_path }, { :id => TAB_COLLABORATIONS, :label => t('#tabs.collaborations', "Collaborations"), :css_class => 'collaborations', :href => :course_collaborations_path }, { :id => TAB_SETTINGS, :label => t('#tabs.settings', "Settings"), :css_class => 'settings', :href => :course_settings_path }, ] end def external_tool_tabs(opts) tools = self.context_external_tools.active.having_setting('course_navigation') account_ids = self.account_chain_ids tools += ContextExternalTool.active.having_setting('course_navigation').find_all_by_context_type_and_context_id('Account', account_ids) tools.sort_by(&:id).map do |tool| { :id => tool.asset_string, :label => tool.label_for(:course_navigation, opts[:language]), :css_class => tool.asset_string, :href => :course_external_tool_path, :visibility => tool.settings[:course_navigation][:visibility], :external => true, :hidden => tool.settings[:course_navigation][:default] == 'disabled', :args => [self.id, tool.id] } end end def tabs_available(user=nil, opts={}) # We will by default show everything in default_tabs, unless the teacher has configured otherwise. tabs = self.tab_configuration.compact default_tabs = Course.default_tabs settings_tab = default_tabs[-1] external_tabs = external_tool_tabs(opts) tabs = tabs.map do |tab| default_tab = default_tabs.find {|t| t[:id] == tab[:id] } || external_tabs.find{|t| t[:id] == tab[:id] } if default_tab tab[:label] = default_tab[:label] tab[:href] = default_tab[:href] tab[:css_class] = default_tab[:css_class] tab[:args] = default_tab[:args] tab[:visibility] = default_tab[:visibility] tab[:external] = default_tab[:external] default_tabs.delete_if {|t| t[:id] == tab[:id] } external_tabs.delete_if {|t| t[:id] == tab[:id] } tab else # Remove any tabs we don't know about in default_tabs (in case we removed them or something, like Groups) nil end end tabs.compact! tabs += default_tabs tabs += external_tabs # Ensure that Settings is always at the bottom tabs.delete_if {|t| t[:id] == TAB_SETTINGS } tabs << settings_tab tabs.each do |tab| tab[:hidden_unused] = true if tab[:id] == TAB_MODULES && !active_record_types[:modules] tab[:hidden_unused] = true if tab[:id] == TAB_FILES && !active_record_types[:files] tab[:hidden_unused] = true if tab[:id] == TAB_QUIZZES && !active_record_types[:quizzes] tab[:hidden_unused] = true if tab[:id] == TAB_ASSIGNMENTS && !active_record_types[:assignments] tab[:hidden_unused] = true if tab[:id] == TAB_PAGES && !active_record_types[:pages] && !allow_student_wiki_edits tab[:hidden_unused] = true if tab[:id] == TAB_CONFERENCES && !active_record_types[:conferences] && !self.grants_right?(user, nil, :create_conferences) tab[:hidden_unused] = true if tab[:id] == TAB_ANNOUNCEMENTS && !active_record_types[:announcements] tab[:hidden_unused] = true if tab[:id] == TAB_OUTCOMES && !active_record_types[:outcomes] end # remove tabs that the user doesn't have access to unless opts[:for_reordering] unless self.grants_rights?(user, opts[:session], :read, :manage_content).values.any? tabs.delete_if { |t| t[:id] == TAB_HOME } tabs.delete_if { |t| t[:id] == TAB_ANNOUNCEMENTS } tabs.delete_if { |t| t[:id] == TAB_PAGES } tabs.delete_if { |t| t[:id] == TAB_OUTCOMES } tabs.delete_if { |t| t[:id] == TAB_CONFERENCES } tabs.delete_if { |t| t[:id] == TAB_COLLABORATIONS } tabs.delete_if { |t| t[:id] == TAB_MODULES } end unless self.grants_rights?(user, opts[:session], :participate_as_student, :manage_content).values.any? tabs.delete_if{ |t| t[:visibility] == 'members' } end unless self.grants_rights?(user, opts[:session], :read, :manage_content, :manage_assignments).values.any? tabs.delete_if { |t| t[:id] == TAB_ASSIGNMENTS } tabs.delete_if { |t| t[:id] == TAB_SYLLABUS } tabs.delete_if { |t| t[:id] == TAB_QUIZZES } end tabs.delete_if{ |t| t[:visibility] == 'admins' } unless self.grants_right?(user, opts[:session], :manage_content) if self.grants_rights?(user, opts[:session], :manage_content, :manage_assignments).values.any? tabs.detect { |t| t[:id] == TAB_ASSIGNMENTS }[:manageable] = true tabs.detect { |t| t[:id] == TAB_SYLLABUS }[:manageable] = true tabs.detect { |t| t[:id] == TAB_QUIZZES }[:manageable] = true end tabs.delete_if { |t| t[:hidden] && t[:external] } tabs.delete_if { |t| t[:id] == TAB_GRADES } unless self.grants_rights?(user, opts[:session], :read_grades, :view_all_grades, :manage_grades).values.any? tabs.detect { |t| t[:id] == TAB_GRADES }[:manageable] = true if self.grants_rights?(user, opts[:session], :view_all_grades, :manage_grades).values.any? tabs.delete_if { |t| t[:id] == TAB_PEOPLE } unless self.grants_rights?(user, opts[:session], :read_roster, :manage_students, :manage_admin_users).values.any? tabs.detect { |t| t[:id] == TAB_PEOPLE }[:manageable] = true if self.grants_rights?(user, opts[:session], :manage_students, :manage_admin_users).values.any? tabs.delete_if { |t| t[:id] == TAB_FILES } unless self.grants_rights?(user, opts[:session], :read, :manage_files).values.any? tabs.detect { |t| t[:id] == TAB_FILES }[:manageable] = true if self.grants_right?(user, opts[:session], :managed_files) tabs.delete_if { |t| t[:id] == TAB_DISCUSSIONS } unless self.grants_rights?(user, opts[:session], :read_forum, :moderate_forum, :post_to_forum).values.any? tabs.detect { |t| t[:id] == TAB_DISCUSSIONS }[:manageable] = true if self.grants_right?(user, opts[:session], :moderate_forum) tabs.delete_if { |t| t[:id] == TAB_SETTINGS } unless self.grants_right?(user, opts[:session], :read_as_admin) if !user || !self.grants_right?(user, nil, :manage_content) # remove some tabs for logged-out users or non-students if self.grants_right?(user, nil, :read_as_admin) tabs.delete_if {|t| [TAB_CHAT].include?(t[:id]) } elsif !self.grants_right?(user, nil, :participate_as_student) tabs.delete_if {|t| [TAB_PEOPLE, TAB_CHAT].include?(t[:id]) } end # remove hidden tabs from students tabs.delete_if {|t| (t[:hidden] || (t[:hidden_unused] && !opts[:include_hidden_unused])) && !t[:manageable] } end end # Uncommenting these lines will always put hidden links after visible links # tabs.each_with_index{|t, i| t[:sort_index] = i } # tabs = tabs.sort_by{|t| [t[:hidden_unused] || t[:hidden] ? 1 : 0, t[:sort_index]] } if !self.tab_configuration || self.tab_configuration.empty? tabs end memoize :tabs_available def allow_wiki_comments read_attribute(:allow_wiki_comments) end def account_name self.account.name rescue nil end def term_name self.enrollment_term.name rescue nil end def enable_user_notes root_account.enable_user_notes rescue false end def equella_settings account = self.account while account settings = account.equella_settings return settings if settings account = account.parent_account end end # This will move the course to be in the specified account. # All enrollments, sections, and other objects attached to the course will also be updated. def move_to_account(new_root_account, new_sub_account=nil) self.account = new_sub_account || new_root_account self.save if new_sub_account self.root_account = new_root_account user_ids = [] CourseSection.find(:all, :conditions=>"course_id = #{self.id}").each do |cs| cs.update_attribute(:root_account_id, new_root_account.id) end Enrollment.find(:all, :conditions=>"course_id = #{self.id}").each do |e| e.update_attribute(:root_account_id, new_root_account.id) user_ids << e.user_id end self.save User.update_account_associations(user_ids) end cattr_accessor :settings_options self.settings_options = {} def self.add_setting(setting, opts=nil) self.settings_options[setting.to_sym] = opts || {} end # these settings either are or could be easily added to # the course settings page add_setting :hide_final_grade, :boolean => true def settings=(hash) if hash.is_a?(Hash) hash.each do |key, val| if settings_options[key.to_sym] opts = settings_options[key.to_sym] if opts[:boolean] settings[key.to_sym] = (val == true || val == 'true' || val == '1' || val == 'on') elsif opts[:hash] new_hash = {} if val.is_a?(Hash) val.each do |inner_key, inner_val| if opts[:values].include?(inner_key.to_sym) new_hash[inner_key.to_sym] = inner_val.to_s end end end settings[key.to_sym] = new_hash.empty? ? nil : new_hash else settings[key.to_sym] = val.to_s end end end end settings end def settings result = self.read_attribute(:settings) return result if result return self.write_attribute(:settings, {}) unless frozen? {}.freeze end def reset_content Course.transaction do new_course = Course.new self.attributes.delete_if{|k,v| [:id, :created_at, :updated_at, :syllabus_body, :wiki_id, :default_view, :tab_configuration].include?(k.to_sym) }.each do |key, val| new_course.write_attribute(key, val) end # The order here is important; we have to set our sis id to nil and save first # so that the new course can be saved, then we need the new course saved to # get its id to move over sections and enrollments. Setting this course to # deleted has to be last otherwise it would set all the enrollments to # deleted before they got moved self.uuid = self.sis_source_id = self.sis_batch_id = nil; self.save! Course.process_as_sis { new_course.save! } self.course_sections.update_all(:course_id => new_course.id) # we also want to bring along prior enrollments, so don't use the enrollments # association case Enrollment.connection.adapter_name when 'MySQL' Enrollment.connection.execute("UPDATE users, enrollments SET users.updated_at=#{Course.sanitize(Time.now.utc)}, enrollments.updated_at=#{Course.sanitize(Time.now.utc)}, enrollments.course_id=#{new_course.id} WHERE users.id=enrollments.user_id AND enrollments.course_id=#{self.id}") else Enrollment.update_all({:course_id => new_course.id, :updated_at => Time.now.utc}, :course_id => self.id) User.update_all({:updated_at => Time.now.utc}, "id IN (SELECT user_id FROM enrollments WHERE course_id=#{new_course.id})") end self.replacement_course_id = new_course.id self.workflow_state = 'deleted' self.save! Course.find(new_course.id) end end def open_registration_for?(user, session = nil) root_account.open_registration_for?(user, session) end def has_open_course_imports? self.course_imports.scoped(:conditions => { :workflow_state => ['created', 'started'] }).count > 0 end end
ottenhoff/canvas-lms
app/models/course.rb
Ruby
agpl-3.0
112,956
#!/bin/bash # this script builds the project with a given profile if [[ $0 != ./deploy/* ]]; then echo "Please run this script from the root of our repository!" exit -1 fi PROFILE="$1" BRANCH_NAME="$2" if [ "${PROFILE}" = "unused" ]; then PROFILE="dev" fi if [ "${BRANCH_NAME}" = "test" ]; then PROFILE="test" fi if [ "${BRANCH_NAME}" = "master" ]; then PROFILE="prod" fi if [ -z ${PROFILE} ]; then echo "Please provide a valid profile e.g.: $0 dev" exit -1 fi echo "Going to run maven build with profile: ${PROFILE}" mvn --settings ./.github/workflows/.github.settings.xml --no-transfer-progress -P${PROFILE} clean javadoc:javadoc install if [ $? -ne 0 ]; then echo "Maven build failed!" exit -1 fi
dzhw/metadatamanagement
deploy/build.sh
Shell
agpl-3.0
722
header { width: 100%; padding-top: 6px; padding-bottom: 20px; padding-left: 15px; color: white; } header a:hover { color: #B3B1B1;; text-decoration: none; } header a:active { color: #B3B1B1;; } header a { color: #B3B1B1; } .barrier { font-size: 24px; } nav { /*list-style: none;*/ float: right; margin-top: -32px; } body { padding-top: 40px; padding-bottom: 40px; background-color: #f5f5f5; background-image: url('/static/img/black_lozenge.png') } .space_below { margin-bottom: 10px; } .enclosure { width: 100%; padding: 19px 29px 29px; background-color: #fff; border: 1px solid #e5e5e5; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05); box-shadow: 0 1px 2px rgba(0,0,0,.05); } /*.form-signin input[type="text"], .form-signin input[type="password"] { font-size: 16px; height: auto; margin-bottom: 15px; padding: 7px 9px; } */
galaxy-team/website
static/css/custom.css
CSS
agpl-3.0
1,144
package syncleus.dann.solve.vacuum; import java.util.Collections; import java.util.HashSet; import java.util.Set; import syncleus.dann.plan.agent.Action; import syncleus.dann.search.framework.ActionsFunction; /** * Specifies the actions available to the agent at state s * * @author Andrew Brown */ public class VacuumWorldActions implements ActionsFunction { private static final Set<Action> _actions; static { Set<Action> actions = new HashSet<Action>(); actions.add(VacuumEnvironment.ACTION_SUCK); actions.add(VacuumEnvironment.ACTION_MOVE_LEFT); actions.add(VacuumEnvironment.ACTION_MOVE_RIGHT); // Ensure cannot be modified. _actions = Collections.unmodifiableSet(actions); } /** * Returns possible actions given this state * * @param s * @return possible actions given this state. */ @Override public Set<Action> actions(Object s) { return _actions; } }
automenta/java_dann
src/syncleus/dann/solve/vacuum/VacuumWorldActions.java
Java
agpl-3.0
902
FactoryGirl.define do factory :router do context 'Router01' routes [{ exten: '_X200', priority: 1}, {exten: '_X100', priority: 2}] end end
digitalhelpersleague/asterism
spec/factories/routers.rb
Ruby
agpl-3.0
151
<?php namespace Ladb\CoreBundle\Manager\Knowledge; use Ladb\CoreBundle\Entity\Knowledge\Book; use Ladb\CoreBundle\Utils\ReviewableUtils; class BookManager extends AbstractKnowledgeManager { const NAME = 'ladb_core.knowledge_book_manager'; public function delete(Book $book, $withWitness = true, $flush = true) { // Delete reviews $reviewableUtils = $this->get(ReviewableUtils::NAME); $reviewableUtils->deleteReviews($book, false); parent::deleteKnowledge($book, $withWitness, $flush); } }
lairdubois/lairdubois
src/Ladb/CoreBundle/Manager/Knowledge/BookManager.php
PHP
agpl-3.0
507
{- ORMOLU_DISABLE -} -- Example 13 - the rounded union of a cube and a sphere. import Control.Applicative (pure) import Graphics.Implicit out = union [ cube False (pure 20) -- same as (V3 20 20 20) , translate (pure 20) $ sphere 15 ] main = writeSTL 1 "example13.stl" out
colah/ImplicitCAD
Examples/example13.hs
Haskell
agpl-3.0
282
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import time from datetime import date, datetime, timedelta from optparse import make_option import openid.store.nonce from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection, transaction from django.utils.translation import ugettext as _ from identityprovider.models import Account, EmailAddress SESSION_SQL = """DELETE FROM django_session WHERE session_key = ANY(SELECT session_key FROM django_session WHERE expire_date < CURRENT_TIMESTAMP LIMIT %s)""" NONCES_SQL = """DELETE FROM openidnonce WHERE timestamp = ANY(SELECT timestamp FROM openidnonce WHERE timestamp < %s LIMIT %s)""" NO_ITEMS = """No items selected to clean up. Please select at least one of: --sessions --nonces --testdata """ class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-s', '--sessions', dest='sessions', default=False, action='store_true', help='Cleanup sessions.'), make_option('-n', '--nonces', dest='nonces', default=False, action='store_true', help='Cleanup nonces.'), make_option('-t', '--testdata', dest='testdata', default=False, action='store_true', help='Cleanup test data.'), make_option('-l', '--limit', dest='limit', default=10000, action='store', help='Number of rows to process per batch.'), make_option('-d', '--date-created', dest='date_created', default=None, action='store', help='Cleanup records created before this date.'), ) help = _("""Clean unnecessary/stalled data from database.""") def handle(self, *args, **options): limit = int(options['limit']) nonce_expire_stamp = int(time.time()) - openid.store.nonce.SKEW test_email_pattern = settings.EMAIL_ADDRESS_PATTERN.replace( '+', '\+').replace('.', '\.') % "[^@]+" if options['date_created'] is None: date_created = date.today() + timedelta(days=1) else: parsed = datetime.strptime(options['date_created'], '%Y-%m-%d') date_created = parsed.date() queries = { 'sessions': SESSION_SQL % limit, 'nonces': NONCES_SQL % (nonce_expire_stamp, limit), } verbosity = int(options['verbosity']) testdata = options.get('testdata') if testdata: self.clean_testdata(test_email_pattern, date_created, limit, verbosity) selected_queries = [query for query in queries if options.get(query)] if not selected_queries and not testdata: self.stdout.write(NO_ITEMS) for item in selected_queries: if verbosity >= 1: self.stdout.write("\nCleaning %s..." % item) cursor = connection.cursor() cursor.execute(queries[item]) while cursor.rowcount > 0: if verbosity >= 2: self.stdout.write(".") cursor.execute(queries[item]) transaction.commit_unless_managed() def clean_testdata(self, email_pattern, date_created, limit, verbosity=0): kwargs = {'email__iregex': email_pattern, 'date_created__lt': date_created} if verbosity >= 1: self.stdout.write("\nCleaning accounts...\n") while True: email_ids = EmailAddress.objects.filter(**kwargs).values_list( 'pk')[:limit] accounts = Account.objects.filter(emailaddress__in=email_ids) if not accounts: break if verbosity >= 2: self.stdout.write("\tDeleting %d accounts..." % ( accounts.count(),)) accounts.delete() if verbosity >= 2: self.stdout.write('\t [OK]\n')
miing/mci_migo
identityprovider/management/commands/cleanup.py
Python
agpl-3.0
4,126
.jasp-no-select { -webkit-user-select: none; } body { font-family: sans-serif ; margin: 0 ; cursor: default; } body:not(.windows) { font-size: 12px ; } body.windows { font-size: 12px ; } body.selected { background-color: #E8E8E8 ; } h1, .h1-toolbar .jasp-menu { font-size: 175% ; } h2, .h2-toolbar .jasp-menu { font-size: 150% ; } h3, .h3-toolbar .jasp-menu { font-size: 125% ; margin-top: .5em; margin-bottom: .5em; } h4, .h4-toolbar .jasp-menu { font-size: 115% ; margin-top: .5em; margin-bottom: .5em; } h5, .h5-toolbar .jasp-menu { font-size: 105% ; margin-top: .5em; margin-bottom: .5em; } h6, .h6-toolbar .jasp-menu { font-size: 100% ; margin-top: .5em; margin-bottom: .5em; } .jasp-display-item { background-color: rgba(224, 224, 224, 0) ; border: 1px solid rgba(105, 105, 105, 0) ; border-radius : 6px ; margin-top: 0.6em ; margin-bottom: 0.6em ; /*margin-left: 0.6em ;*/ padding-left: 0.6em ; margin-right: 0.6em ; padding-right: 0.6em ; } .jasp-display-item-flat { padding-left: 0; } .jasp-table-primitive { padding-left: 0.6em ; } .jasp-collapsed { max-width: 70em; min-width: 40em; background-color: rgba(224, 224, 224, 0.5) ; border: 1px solid rgba(105, 105, 105, 1) ; } table { font-style: normal ; border-collapse: collapse ; margin-bottom: 2em ; cursor: default; } th { vertical-align: bottom ; font-weight: normal ; } th[colspan="2"] { padding-left : 1em ; padding-right: 1em ; } td.value { padding-left : 1em ; padding-right: 0 ; } td.symbol { text-align: left ; padding-right: 1em ; padding-left: 0 ; } td { text-align: right ; vertical-align: top ; } thead tr:nth-child(2) th:not(.separator) { min-width: 4em ; } th.separator, td.separator { padding-left: 0px ; padding-right: 0px ; } thead tr:first-child th { padding: 6px 10px ; font-style: bold ; text-align: left ; padding-left: 0 ; } thead th { text-align: center; white-space: nowrap; padding-top: .25em ; padding-bottom: .25em ; } tbody th { text-align: left; } tbody th, tbody td { border-bottom : none ; border-top : none; white-space: nowrap; } thead tr th { border-bottom: thin solid ; } thead tr.over-title th:empty { border-bottom: none; } thead tr.over-title-space th { border-bottom: none; padding: 0 .25em 0 .25em; } thead tr.over-title-space th:last-child { border-bottom: none; padding: 0 0 0 .25em; } div.over-title-space { padding-top: .25em; padding-bottom: .25em; vertical-align: middle; margin: 0 0 0 0; text-align: center; border-bottom: thin solid; } div.over-title-space:empty { border-bottom: none; } tbody tr:last-child th, tbody tr:last-child td { border-bottom: 2px solid ; } tbody tr td.new-sub-group-row { padding-top: .4em ; } tbody tr td.new-group-row, tbody tr:first-child td { padding-top: .9em ; } tbody tr:nth-last-child(2) td.last-group-row, tbody tr:nth-last-child(2) td, tbody tr:nth-last-child(2) th { margin-bottom: .8em ; } .jasp-analysis tbody tr:nth-child(even) th:not(.row-span), .jasp-analysis tbody tr:nth-child(even) td:not(.row-span) { background: rgb(235, 235, 235) } .jasp-analysis.selected tbody tr:nth-child(odd) th, .jasp-analysis.selected tbody tr:nth-child(odd) td { background: #FFF } td.text { text-align: left ; } tfoot td { text-align: left; } .chart > g > rect { fill: #C9C682 } svg > text { font-family: sans-serif ; font-weight: bold; font-size: 120% ; } .jasp-collection-image { display: inline-block; } .jasp-image { /*border: 2px solid transparent ; border-radius : 2px ; padding: 0px ;*/ position: relative ; } .jasp-image-image { width: 100% ; height: 100% ; } .error-state .jasp-image-image { opacity: 0.33 ; } .etch-editor-panel { position:fixed; top:0; width:100%; z-index:100; } .jasp-image-resizer { background-color : #BFD9F7 ; border: 1px solid #7C95CB ; border-radius : 3px ; margin: 0px ; } .jasp-image-resizable { border: 2px solid #BFD9F7 ; border-radius : 2px ; } .jasp_top_level { margin-left: 1.7em ; margin-right: 1.7em ; } .jasp-analysis { margin: 0 .7em .7em .7em ; padding: 0 1em 1em 1em ; position: relative; } #instructions { margin: .7em ; padding: 1em ; /*display: inline-block ;*/ } .jasp-analysis.unselected:not(.jasp-menu-selected) { background-color: #E8E8E8 ; } .jasp-analysis.selected:not(.jasp-menu-selected) { background-color: white ; } div.toolbar { display: block ; position: relative; } div.image-status { position: absolute ; top : 0 ; left: 0 ; width: 100% ; height: 100% ; background-repeat:no-repeat; background-position: center center; visibility: hidden ; z-index: 50 ; } div.status { width: 16px ; height: 16px ; background-size : 100% ; display: inline-block ; margin-left : 6px ; visibility: hidden ; } div.status.running { background : url(images/running.gif) no-repeat ; visibility: visible ; } div.status.waiting { background : url(images/waiting.gif) no-repeat ; visibility: visible ; } div.image-status.running { background-image : url('images/running-large.gif') ; visibility: visible ; } div.image-status.waiting { background-image : url('images/waiting-large.png') ; visibility: visible ; } .error-state { color: silver ; } .exception .error-message-box { border-width: 3px; border-style: double; } .analysis-error { position: absolute; top: 60px; left: 40px; right: 40px; margin-left: auto; margin-right: auto; } .analysis-error.analysis-error-top-max { top: 200px; } .error-message-positioner { height: 0px ; overflow: visible ; position: relative; top: 10px ; float: left ; z-index: 100 ; } .jasp-image-holder .error-message-positioner { position: absolute ; top: 25% ; } .error-message-symbol { float: left; margin-right: .3em; } .error-message-box { z-index: 100 ; padding: 1em ; border-radius: .4em ; min-width: 300px ; white-space: normal; } .error-message-message { } .stack-trace-selector div, .stack-trace-selector span { cursor: pointer ; display: inline-block ; vertical-align: middle ; } .stack-trace-arrow { background: center no-repeat url("images/expand.png") ; background-size: 70% ; width: 16px ; height: 16px ; margin-left: 2px ; } .stack-trace { display: none ; } td.squash-left { width: 99% ; } #intro { padding: 1em 2em ; margin: 50px auto ; min-width: 300px ; max-width: 500px ; width: 50% ; border: 3px dashed #3CAAE7 ; border-radius: 10px ; color: #3CAAE7 ; } .jasp-hide { display: none; visibility: hidden ; } .jasp-image-holder { position: relative ; } .jasp-resize { background: top left no-repeat url(images/resizer.png); right: 2px; cursor: nw-resize; bottom: 2px; position: absolute; width: 16px; height: 16px; } .jasp-closer { background: top left no-repeat url(images/closer.png); right: 2px; top: 2px; position: -webkit-sticky; position: sticky; width: 16px; height: 16px; bottom: 2px; float: right; } .jasp-toolbar h1, .jasp-toolbar h2, .jasp-toolbar h3, .jasp-toolbar h4, .jasp-toolbar h5, .jasp-toolbar h6, .jasp-toolbar div , .jasp-toolbar span { display: inline-block; vertical-align: middle; } .jasp-menu { background: center no-repeat url(images/menu-indicator.svg); background-size: 70% ; width: 16px ; height: 16px ; margin-left: 4px ; } .jasp-collapsed .jasp-menu { background: center no-repeat url(images/expand.png); background-size: 70% ; width: 16px ; height: 16px ; margin-left: 4px ; } .jasp-toolbar { display: block ; } .toolbar-clickable { cursor: pointer; } .toolbar-editing { cursor: text; border-top: 1px solid rgb(205, 205, 205); border-bottom: 1px solid rgb(205, 205, 205) ; } .jasp-menu-selected { background-color : #BFD9F7 ; } .jasp-editable { padding-top: .5em ; padding-bottom: .5em ; background-color : inherit ; word-wrap: break-word; } .jasp-editable, .jasp-editable * { cursor: text; } .jasp-notes { border-top: 1px solid rgb(205, 205, 205); border-bottom: 1px solid rgb(205, 205, 205) ; border-radius : 0 ; color: rgb(0, 122, 204) ; max-width: 70em; min-width: 40em; position: relative ; margin-top: 0.6em ; margin-bottom: 0.6em ; } [contenteditable]:focus { outline: 0px solid transparent; } .jasp-ghost-text { font-weight: bold ; color: rgb(214, 214, 214); cursor: text; padding-top: .5em ; padding-bottom: .5em ; } pre { display: inline; } .in-toolbar, .jasp-editable { min-width: 1em; } /*.jasp-indent { margin-left: .5em ; padding-left: 0.8em ; }*/
aknight1-uva/jasp-desktop
JASP-Desktop/html/css/theme-jasp.css
CSS
agpl-3.0
8,566
/*! * Bootstrap v4.0.0-beta (https://getbootstrap.com) * Copyright 2011-2017 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.') } (function ($) { var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] >= 4)) { throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0') } })(jQuery); (function () { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): util.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Util = function ($) { /** * ------------------------------------------------------------------------ * Private TransitionEnd Helpers * ------------------------------------------------------------------------ */ var transition = false; var MAX_UID = 1000000; var TransitionEndEvent = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' // shoutout AngusCroll (https://goo.gl/pxwQGp) };function toType(obj) { return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); } function isElement(obj) { return (obj[0] || obj).nodeType; } function getSpecialTransitionEndEvent() { return { bindType: transition.end, delegateType: transition.end, handle: function handle(event) { if ($(event.target).is(this)) { return event.handleObj.handler.apply(this, arguments); // eslint-disable-line prefer-rest-params } return undefined; } }; } function transitionEndTest() { if (window.QUnit) { return false; } var el = document.createElement('bootstrap'); for (var name in TransitionEndEvent) { if (el.style[name] !== undefined) { return { end: TransitionEndEvent[name] }; } } return false; } function transitionEndEmulator(duration) { var _this = this; var called = false; $(this).one(Util.TRANSITION_END, function () { called = true; }); setTimeout(function () { if (!called) { Util.triggerTransitionEnd(_this); } }, duration); return this; } function setTransitionEndSupport() { transition = transitionEndTest(); $.fn.emulateTransitionEnd = transitionEndEmulator; if (Util.supportsTransitionEnd()) { $.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent(); } } /** * -------------------------------------------------------------------------- * Public Util Api * -------------------------------------------------------------------------- */ var Util = { TRANSITION_END: 'bsTransitionEnd', getUID: function getUID(prefix) { do { // eslint-disable-next-line no-bitwise prefix += ~~(Math.random() * MAX_UID); // "~~" acts like a faster Math.floor() here } while (document.getElementById(prefix)); return prefix; }, getSelectorFromElement: function getSelectorFromElement(element) { var selector = element.getAttribute('data-target'); if (!selector || selector === '#') { selector = element.getAttribute('href') || ''; } try { var $selector = $(selector); return $selector.length > 0 ? selector : null; } catch (error) { return null; } }, reflow: function reflow(element) { return element.offsetHeight; }, triggerTransitionEnd: function triggerTransitionEnd(element) { $(element).trigger(transition.end); }, supportsTransitionEnd: function supportsTransitionEnd() { return Boolean(transition); }, typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) { for (var property in configTypes) { if (configTypes.hasOwnProperty(property)) { var expectedTypes = configTypes[property]; var value = config[property]; var valueType = value && isElement(value) ? 'element' : toType(value); if (!new RegExp(expectedTypes).test(valueType)) { throw new Error(componentName.toUpperCase() + ': ' + ('Option "' + property + '" provided type "' + valueType + '" ') + ('but expected type "' + expectedTypes + '".')); } } } } }; setTransitionEndSupport(); return Util; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): alert.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Alert = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'alert'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.alert'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 150; var Selector = { DISMISS: '[data-dismiss="alert"]' }; var Event = { CLOSE: 'close' + EVENT_KEY, CLOSED: 'closed' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY }; var ClassName = { ALERT: 'alert', FADE: 'fade', SHOW: 'show' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Alert = function () { function Alert(element) { _classCallCheck(this, Alert); this._element = element; } // getters // public Alert.prototype.close = function close(element) { element = element || this._element; var rootElement = this._getRootElement(element); var customEvent = this._triggerCloseEvent(rootElement); if (customEvent.isDefaultPrevented()) { return; } this._removeElement(rootElement); }; Alert.prototype.dispose = function dispose() { $.removeData(this._element, DATA_KEY); this._element = null; }; // private Alert.prototype._getRootElement = function _getRootElement(element) { var selector = Util.getSelectorFromElement(element); var parent = false; if (selector) { parent = $(selector)[0]; } if (!parent) { parent = $(element).closest('.' + ClassName.ALERT)[0]; } return parent; }; Alert.prototype._triggerCloseEvent = function _triggerCloseEvent(element) { var closeEvent = $.Event(Event.CLOSE); $(element).trigger(closeEvent); return closeEvent; }; Alert.prototype._removeElement = function _removeElement(element) { var _this2 = this; $(element).removeClass(ClassName.SHOW); if (!Util.supportsTransitionEnd() || !$(element).hasClass(ClassName.FADE)) { this._destroyElement(element); return; } $(element).one(Util.TRANSITION_END, function (event) { return _this2._destroyElement(element, event); }).emulateTransitionEnd(TRANSITION_DURATION); }; Alert.prototype._destroyElement = function _destroyElement(element) { $(element).detach().trigger(Event.CLOSED).remove(); }; // static Alert._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var $element = $(this); var data = $element.data(DATA_KEY); if (!data) { data = new Alert(this); $element.data(DATA_KEY, data); } if (config === 'close') { data[config](this); } }); }; Alert._handleDismiss = function _handleDismiss(alertInstance) { return function (event) { if (event) { event.preventDefault(); } alertInstance.close(this); }; }; _createClass(Alert, null, [{ key: 'VERSION', get: function get() { return VERSION; } }]); return Alert; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document).on(Event.CLICK_DATA_API, Selector.DISMISS, Alert._handleDismiss(new Alert())); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Alert._jQueryInterface; $.fn[NAME].Constructor = Alert; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Alert._jQueryInterface; }; return Alert; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): button.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Button = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'button'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.button'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var ClassName = { ACTIVE: 'active', BUTTON: 'btn', FOCUS: 'focus' }; var Selector = { DATA_TOGGLE_CARROT: '[data-toggle^="button"]', DATA_TOGGLE: '[data-toggle="buttons"]', INPUT: 'input', ACTIVE: '.active', BUTTON: '.btn' }; var Event = { CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY, FOCUS_BLUR_DATA_API: 'focus' + EVENT_KEY + DATA_API_KEY + ' ' + ('blur' + EVENT_KEY + DATA_API_KEY) /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Button = function () { function Button(element) { _classCallCheck(this, Button); this._element = element; } // getters // public Button.prototype.toggle = function toggle() { var triggerChangeEvent = true; var addAriaPressed = true; var rootElement = $(this._element).closest(Selector.DATA_TOGGLE)[0]; if (rootElement) { var input = $(this._element).find(Selector.INPUT)[0]; if (input) { if (input.type === 'radio') { if (input.checked && $(this._element).hasClass(ClassName.ACTIVE)) { triggerChangeEvent = false; } else { var activeElement = $(rootElement).find(Selector.ACTIVE)[0]; if (activeElement) { $(activeElement).removeClass(ClassName.ACTIVE); } } } if (triggerChangeEvent) { if (input.hasAttribute('disabled') || rootElement.hasAttribute('disabled') || input.classList.contains('disabled') || rootElement.classList.contains('disabled')) { return; } input.checked = !$(this._element).hasClass(ClassName.ACTIVE); $(input).trigger('change'); } input.focus(); addAriaPressed = false; } } if (addAriaPressed) { this._element.setAttribute('aria-pressed', !$(this._element).hasClass(ClassName.ACTIVE)); } if (triggerChangeEvent) { $(this._element).toggleClass(ClassName.ACTIVE); } }; Button.prototype.dispose = function dispose() { $.removeData(this._element, DATA_KEY); this._element = null; }; // static Button._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var data = $(this).data(DATA_KEY); if (!data) { data = new Button(this); $(this).data(DATA_KEY, data); } if (config === 'toggle') { data[config](); } }); }; _createClass(Button, null, [{ key: 'VERSION', get: function get() { return VERSION; } }]); return Button; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) { event.preventDefault(); var button = event.target; if (!$(button).hasClass(ClassName.BUTTON)) { button = $(button).closest(Selector.BUTTON); } Button._jQueryInterface.call($(button), 'toggle'); }).on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) { var button = $(event.target).closest(Selector.BUTTON)[0]; $(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type)); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Button._jQueryInterface; $.fn[NAME].Constructor = Button; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Button._jQueryInterface; }; return Button; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): carousel.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Carousel = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'carousel'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.carousel'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 600; var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key var TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch var Default = { interval: 5000, keyboard: true, slide: false, pause: 'hover', wrap: true }; var DefaultType = { interval: '(number|boolean)', keyboard: 'boolean', slide: '(boolean|string)', pause: '(string|boolean)', wrap: 'boolean' }; var Direction = { NEXT: 'next', PREV: 'prev', LEFT: 'left', RIGHT: 'right' }; var Event = { SLIDE: 'slide' + EVENT_KEY, SLID: 'slid' + EVENT_KEY, KEYDOWN: 'keydown' + EVENT_KEY, MOUSEENTER: 'mouseenter' + EVENT_KEY, MOUSELEAVE: 'mouseleave' + EVENT_KEY, TOUCHEND: 'touchend' + EVENT_KEY, LOAD_DATA_API: 'load' + EVENT_KEY + DATA_API_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY }; var ClassName = { CAROUSEL: 'carousel', ACTIVE: 'active', SLIDE: 'slide', RIGHT: 'carousel-item-right', LEFT: 'carousel-item-left', NEXT: 'carousel-item-next', PREV: 'carousel-item-prev', ITEM: 'carousel-item' }; var Selector = { ACTIVE: '.active', ACTIVE_ITEM: '.active.carousel-item', ITEM: '.carousel-item', NEXT_PREV: '.carousel-item-next, .carousel-item-prev', INDICATORS: '.carousel-indicators', DATA_SLIDE: '[data-slide], [data-slide-to]', DATA_RIDE: '[data-ride="carousel"]' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Carousel = function () { function Carousel(element, config) { _classCallCheck(this, Carousel); this._items = null; this._interval = null; this._activeElement = null; this._isPaused = false; this._isSliding = false; this.touchTimeout = null; this._config = this._getConfig(config); this._element = $(element)[0]; this._indicatorsElement = $(this._element).find(Selector.INDICATORS)[0]; this._addEventListeners(); } // getters // public Carousel.prototype.next = function next() { if (!this._isSliding) { this._slide(Direction.NEXT); } }; Carousel.prototype.nextWhenVisible = function nextWhenVisible() { // Don't call next when the page isn't visible if (!document.hidden) { this.next(); } }; Carousel.prototype.prev = function prev() { if (!this._isSliding) { this._slide(Direction.PREV); } }; Carousel.prototype.pause = function pause(event) { if (!event) { this._isPaused = true; } if ($(this._element).find(Selector.NEXT_PREV)[0] && Util.supportsTransitionEnd()) { Util.triggerTransitionEnd(this._element); this.cycle(true); } clearInterval(this._interval); this._interval = null; }; Carousel.prototype.cycle = function cycle(event) { if (!event) { this._isPaused = false; } if (this._interval) { clearInterval(this._interval); this._interval = null; } if (this._config.interval && !this._isPaused) { this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval); } }; Carousel.prototype.to = function to(index) { var _this3 = this; this._activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0]; var activeIndex = this._getItemIndex(this._activeElement); if (index > this._items.length - 1 || index < 0) { return; } if (this._isSliding) { $(this._element).one(Event.SLID, function () { return _this3.to(index); }); return; } if (activeIndex === index) { this.pause(); this.cycle(); return; } var direction = index > activeIndex ? Direction.NEXT : Direction.PREV; this._slide(direction, this._items[index]); }; Carousel.prototype.dispose = function dispose() { $(this._element).off(EVENT_KEY); $.removeData(this._element, DATA_KEY); this._items = null; this._config = null; this._element = null; this._interval = null; this._isPaused = null; this._isSliding = null; this._activeElement = null; this._indicatorsElement = null; }; // private Carousel.prototype._getConfig = function _getConfig(config) { config = $.extend({}, Default, config); Util.typeCheckConfig(NAME, config, DefaultType); return config; }; Carousel.prototype._addEventListeners = function _addEventListeners() { var _this4 = this; if (this._config.keyboard) { $(this._element).on(Event.KEYDOWN, function (event) { return _this4._keydown(event); }); } if (this._config.pause === 'hover') { $(this._element).on(Event.MOUSEENTER, function (event) { return _this4.pause(event); }).on(Event.MOUSELEAVE, function (event) { return _this4.cycle(event); }); if ('ontouchstart' in document.documentElement) { // if it's a touch-enabled device, mouseenter/leave are fired as // part of the mouse compatibility events on first tap - the carousel // would stop cycling until user tapped out of it; // here, we listen for touchend, explicitly pause the carousel // (as if it's the second time we tap on it, mouseenter compat event // is NOT fired) and after a timeout (to allow for mouse compatibility // events to fire) we explicitly restart cycling $(this._element).on(Event.TOUCHEND, function () { _this4.pause(); if (_this4.touchTimeout) { clearTimeout(_this4.touchTimeout); } _this4.touchTimeout = setTimeout(function (event) { return _this4.cycle(event); }, TOUCHEVENT_COMPAT_WAIT + _this4._config.interval); }); } } }; Carousel.prototype._keydown = function _keydown(event) { if (/input|textarea/i.test(event.target.tagName)) { return; } switch (event.which) { case ARROW_LEFT_KEYCODE: event.preventDefault(); this.prev(); break; case ARROW_RIGHT_KEYCODE: event.preventDefault(); this.next(); break; default: return; } }; Carousel.prototype._getItemIndex = function _getItemIndex(element) { this._items = $.makeArray($(element).parent().find(Selector.ITEM)); return this._items.indexOf(element); }; Carousel.prototype._getItemByDirection = function _getItemByDirection(direction, activeElement) { var isNextDirection = direction === Direction.NEXT; var isPrevDirection = direction === Direction.PREV; var activeIndex = this._getItemIndex(activeElement); var lastItemIndex = this._items.length - 1; var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex; if (isGoingToWrap && !this._config.wrap) { return activeElement; } var delta = direction === Direction.PREV ? -1 : 1; var itemIndex = (activeIndex + delta) % this._items.length; return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex]; }; Carousel.prototype._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) { var targetIndex = this._getItemIndex(relatedTarget); var fromIndex = this._getItemIndex($(this._element).find(Selector.ACTIVE_ITEM)[0]); var slideEvent = $.Event(Event.SLIDE, { relatedTarget: relatedTarget, direction: eventDirectionName, from: fromIndex, to: targetIndex }); $(this._element).trigger(slideEvent); return slideEvent; }; Carousel.prototype._setActiveIndicatorElement = function _setActiveIndicatorElement(element) { if (this._indicatorsElement) { $(this._indicatorsElement).find(Selector.ACTIVE).removeClass(ClassName.ACTIVE); var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)]; if (nextIndicator) { $(nextIndicator).addClass(ClassName.ACTIVE); } } }; Carousel.prototype._slide = function _slide(direction, element) { var _this5 = this; var activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0]; var activeElementIndex = this._getItemIndex(activeElement); var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement); var nextElementIndex = this._getItemIndex(nextElement); var isCycling = Boolean(this._interval); var directionalClassName = void 0; var orderClassName = void 0; var eventDirectionName = void 0; if (direction === Direction.NEXT) { directionalClassName = ClassName.LEFT; orderClassName = ClassName.NEXT; eventDirectionName = Direction.LEFT; } else { directionalClassName = ClassName.RIGHT; orderClassName = ClassName.PREV; eventDirectionName = Direction.RIGHT; } if (nextElement && $(nextElement).hasClass(ClassName.ACTIVE)) { this._isSliding = false; return; } var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName); if (slideEvent.isDefaultPrevented()) { return; } if (!activeElement || !nextElement) { // some weirdness is happening, so we bail return; } this._isSliding = true; if (isCycling) { this.pause(); } this._setActiveIndicatorElement(nextElement); var slidEvent = $.Event(Event.SLID, { relatedTarget: nextElement, direction: eventDirectionName, from: activeElementIndex, to: nextElementIndex }); if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.SLIDE)) { $(nextElement).addClass(orderClassName); Util.reflow(nextElement); $(activeElement).addClass(directionalClassName); $(nextElement).addClass(directionalClassName); $(activeElement).one(Util.TRANSITION_END, function () { $(nextElement).removeClass(directionalClassName + ' ' + orderClassName).addClass(ClassName.ACTIVE); $(activeElement).removeClass(ClassName.ACTIVE + ' ' + orderClassName + ' ' + directionalClassName); _this5._isSliding = false; setTimeout(function () { return $(_this5._element).trigger(slidEvent); }, 0); }).emulateTransitionEnd(TRANSITION_DURATION); } else { $(activeElement).removeClass(ClassName.ACTIVE); $(nextElement).addClass(ClassName.ACTIVE); this._isSliding = false; $(this._element).trigger(slidEvent); } if (isCycling) { this.cycle(); } }; // static Carousel._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = $.extend({}, Default, $(this).data()); if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') { $.extend(_config, config); } var action = typeof config === 'string' ? config : _config.slide; if (!data) { data = new Carousel(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'number') { data.to(config); } else if (typeof action === 'string') { if (data[action] === undefined) { throw new Error('No method named "' + action + '"'); } data[action](); } else if (_config.interval) { data.pause(); data.cycle(); } }); }; Carousel._dataApiClickHandler = function _dataApiClickHandler(event) { var selector = Util.getSelectorFromElement(this); if (!selector) { return; } var target = $(selector)[0]; if (!target || !$(target).hasClass(ClassName.CAROUSEL)) { return; } var config = $.extend({}, $(target).data(), $(this).data()); var slideIndex = this.getAttribute('data-slide-to'); if (slideIndex) { config.interval = false; } Carousel._jQueryInterface.call($(target), config); if (slideIndex) { $(target).data(DATA_KEY).to(slideIndex); } event.preventDefault(); }; _createClass(Carousel, null, [{ key: 'VERSION', get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }]); return Carousel; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document).on(Event.CLICK_DATA_API, Selector.DATA_SLIDE, Carousel._dataApiClickHandler); $(window).on(Event.LOAD_DATA_API, function () { $(Selector.DATA_RIDE).each(function () { var $carousel = $(this); Carousel._jQueryInterface.call($carousel, $carousel.data()); }); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Carousel._jQueryInterface; $.fn[NAME].Constructor = Carousel; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Carousel._jQueryInterface; }; return Carousel; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): collapse.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Collapse = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'collapse'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.collapse'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 600; var Default = { toggle: true, parent: '' }; var DefaultType = { toggle: 'boolean', parent: 'string' }; var Event = { SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY, HIDE: 'hide' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY }; var ClassName = { SHOW: 'show', COLLAPSE: 'collapse', COLLAPSING: 'collapsing', COLLAPSED: 'collapsed' }; var Dimension = { WIDTH: 'width', HEIGHT: 'height' }; var Selector = { ACTIVES: '.show, .collapsing', DATA_TOGGLE: '[data-toggle="collapse"]' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Collapse = function () { function Collapse(element, config) { _classCallCheck(this, Collapse); this._isTransitioning = false; this._element = element; this._config = this._getConfig(config); this._triggerArray = $.makeArray($('[data-toggle="collapse"][href="#' + element.id + '"],' + ('[data-toggle="collapse"][data-target="#' + element.id + '"]'))); var tabToggles = $(Selector.DATA_TOGGLE); for (var i = 0; i < tabToggles.length; i++) { var elem = tabToggles[i]; var selector = Util.getSelectorFromElement(elem); if (selector !== null && $(selector).filter(element).length > 0) { this._triggerArray.push(elem); } } this._parent = this._config.parent ? this._getParent() : null; if (!this._config.parent) { this._addAriaAndCollapsedClass(this._element, this._triggerArray); } if (this._config.toggle) { this.toggle(); } } // getters // public Collapse.prototype.toggle = function toggle() { if ($(this._element).hasClass(ClassName.SHOW)) { this.hide(); } else { this.show(); } }; Collapse.prototype.show = function show() { var _this6 = this; if (this._isTransitioning || $(this._element).hasClass(ClassName.SHOW)) { return; } var actives = void 0; var activesData = void 0; if (this._parent) { actives = $.makeArray($(this._parent).children().children(Selector.ACTIVES)); if (!actives.length) { actives = null; } } if (actives) { activesData = $(actives).data(DATA_KEY); if (activesData && activesData._isTransitioning) { return; } } var startEvent = $.Event(Event.SHOW); $(this._element).trigger(startEvent); if (startEvent.isDefaultPrevented()) { return; } if (actives) { Collapse._jQueryInterface.call($(actives), 'hide'); if (!activesData) { $(actives).data(DATA_KEY, null); } } var dimension = this._getDimension(); $(this._element).removeClass(ClassName.COLLAPSE).addClass(ClassName.COLLAPSING); this._element.style[dimension] = 0; if (this._triggerArray.length) { $(this._triggerArray).removeClass(ClassName.COLLAPSED).attr('aria-expanded', true); } this.setTransitioning(true); var complete = function complete() { $(_this6._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).addClass(ClassName.SHOW); _this6._element.style[dimension] = ''; _this6.setTransitioning(false); $(_this6._element).trigger(Event.SHOWN); }; if (!Util.supportsTransitionEnd()) { complete(); return; } var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); var scrollSize = 'scroll' + capitalizedDimension; $(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION); this._element.style[dimension] = this._element[scrollSize] + 'px'; }; Collapse.prototype.hide = function hide() { var _this7 = this; if (this._isTransitioning || !$(this._element).hasClass(ClassName.SHOW)) { return; } var startEvent = $.Event(Event.HIDE); $(this._element).trigger(startEvent); if (startEvent.isDefaultPrevented()) { return; } var dimension = this._getDimension(); this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + 'px'; Util.reflow(this._element); $(this._element).addClass(ClassName.COLLAPSING).removeClass(ClassName.COLLAPSE).removeClass(ClassName.SHOW); if (this._triggerArray.length) { for (var i = 0; i < this._triggerArray.length; i++) { var trigger = this._triggerArray[i]; var selector = Util.getSelectorFromElement(trigger); if (selector !== null) { var $elem = $(selector); if (!$elem.hasClass(ClassName.SHOW)) { $(trigger).addClass(ClassName.COLLAPSED).attr('aria-expanded', false); } } } } this.setTransitioning(true); var complete = function complete() { _this7.setTransitioning(false); $(_this7._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).trigger(Event.HIDDEN); }; this._element.style[dimension] = ''; if (!Util.supportsTransitionEnd()) { complete(); return; } $(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION); }; Collapse.prototype.setTransitioning = function setTransitioning(isTransitioning) { this._isTransitioning = isTransitioning; }; Collapse.prototype.dispose = function dispose() { $.removeData(this._element, DATA_KEY); this._config = null; this._parent = null; this._element = null; this._triggerArray = null; this._isTransitioning = null; }; // private Collapse.prototype._getConfig = function _getConfig(config) { config = $.extend({}, Default, config); config.toggle = Boolean(config.toggle); // coerce string values Util.typeCheckConfig(NAME, config, DefaultType); return config; }; Collapse.prototype._getDimension = function _getDimension() { var hasWidth = $(this._element).hasClass(Dimension.WIDTH); return hasWidth ? Dimension.WIDTH : Dimension.HEIGHT; }; Collapse.prototype._getParent = function _getParent() { var _this8 = this; var parent = $(this._config.parent)[0]; var selector = '[data-toggle="collapse"][data-parent="' + this._config.parent + '"]'; $(parent).find(selector).each(function (i, element) { _this8._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]); }); return parent; }; Collapse.prototype._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) { if (element) { var isOpen = $(element).hasClass(ClassName.SHOW); if (triggerArray.length) { $(triggerArray).toggleClass(ClassName.COLLAPSED, !isOpen).attr('aria-expanded', isOpen); } } }; // static Collapse._getTargetFromElement = function _getTargetFromElement(element) { var selector = Util.getSelectorFromElement(element); return selector ? $(selector)[0] : null; }; Collapse._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var $this = $(this); var data = $this.data(DATA_KEY); var _config = $.extend({}, Default, $this.data(), (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config); if (!data && _config.toggle && /show|hide/.test(config)) { _config.toggle = false; } if (!data) { data = new Collapse(this, _config); $this.data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](); } }); }; _createClass(Collapse, null, [{ key: 'VERSION', get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }]); return Collapse; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) { if (!/input|textarea/i.test(event.target.tagName)) { event.preventDefault(); } var $trigger = $(this); var selector = Util.getSelectorFromElement(this); $(selector).each(function () { var $target = $(this); var data = $target.data(DATA_KEY); var config = data ? 'toggle' : $trigger.data(); Collapse._jQueryInterface.call($target, config); }); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Collapse._jQueryInterface; $.fn[NAME].Constructor = Collapse; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Collapse._jQueryInterface; }; return Collapse; }(jQuery); /* global Popper */ /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): dropdown.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Dropdown = function ($) { /** * Check for Popper dependency * Popper - https://popper.js.org */ if (typeof Popper === 'undefined') { throw new Error('Bootstrap dropdown require Popper.js (https://popper.js.org)'); } /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'dropdown'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.dropdown'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key var SPACE_KEYCODE = 32; // KeyboardEvent.which value for space key var TAB_KEYCODE = 9; // KeyboardEvent.which value for tab key var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key var RIGHT_MOUSE_BUTTON_WHICH = 3; // MouseEvent.which value for the right button (assuming a right-handed mouse) var REGEXP_KEYDOWN = new RegExp(ARROW_UP_KEYCODE + '|' + ARROW_DOWN_KEYCODE + '|' + ESCAPE_KEYCODE); var Event = { HIDE: 'hide' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY, CLICK: 'click' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY, KEYDOWN_DATA_API: 'keydown' + EVENT_KEY + DATA_API_KEY, KEYUP_DATA_API: 'keyup' + EVENT_KEY + DATA_API_KEY }; var ClassName = { DISABLED: 'disabled', SHOW: 'show', DROPUP: 'dropup', MENURIGHT: 'dropdown-menu-right', MENULEFT: 'dropdown-menu-left' }; var Selector = { DATA_TOGGLE: '[data-toggle="dropdown"]', FORM_CHILD: '.dropdown form', MENU: '.dropdown-menu', NAVBAR_NAV: '.navbar-nav', VISIBLE_ITEMS: '.dropdown-menu .dropdown-item:not(.disabled)' }; var AttachmentMap = { TOP: 'top-start', TOPEND: 'top-end', BOTTOM: 'bottom-start', BOTTOMEND: 'bottom-end' }; var Default = { placement: AttachmentMap.BOTTOM, offset: 0, flip: true }; var DefaultType = { placement: 'string', offset: '(number|string)', flip: 'boolean' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Dropdown = function () { function Dropdown(element, config) { _classCallCheck(this, Dropdown); this._element = element; this._popper = null; this._config = this._getConfig(config); this._menu = this._getMenuElement(); this._inNavbar = this._detectNavbar(); this._addEventListeners(); } // getters // public Dropdown.prototype.toggle = function toggle() { if (this._element.disabled || $(this._element).hasClass(ClassName.DISABLED)) { return; } var parent = Dropdown._getParentFromElement(this._element); var isActive = $(this._menu).hasClass(ClassName.SHOW); Dropdown._clearMenus(); if (isActive) { return; } var relatedTarget = { relatedTarget: this._element }; var showEvent = $.Event(Event.SHOW, relatedTarget); $(parent).trigger(showEvent); if (showEvent.isDefaultPrevented()) { return; } var element = this._element; // for dropup with alignment we use the parent as popper container if ($(parent).hasClass(ClassName.DROPUP)) { if ($(this._menu).hasClass(ClassName.MENULEFT) || $(this._menu).hasClass(ClassName.MENURIGHT)) { element = parent; } } this._popper = new Popper(element, this._menu, this._getPopperConfig()); // if this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html if ('ontouchstart' in document.documentElement && !$(parent).closest(Selector.NAVBAR_NAV).length) { $('body').children().on('mouseover', null, $.noop); } this._element.focus(); this._element.setAttribute('aria-expanded', true); $(this._menu).toggleClass(ClassName.SHOW); $(parent).toggleClass(ClassName.SHOW).trigger($.Event(Event.SHOWN, relatedTarget)); }; Dropdown.prototype.dispose = function dispose() { $.removeData(this._element, DATA_KEY); $(this._element).off(EVENT_KEY); this._element = null; this._menu = null; if (this._popper !== null) { this._popper.destroy(); } this._popper = null; }; Dropdown.prototype.update = function update() { this._inNavbar = this._detectNavbar(); if (this._popper !== null) { this._popper.scheduleUpdate(); } }; // private Dropdown.prototype._addEventListeners = function _addEventListeners() { var _this9 = this; $(this._element).on(Event.CLICK, function (event) { event.preventDefault(); event.stopPropagation(); _this9.toggle(); }); }; Dropdown.prototype._getConfig = function _getConfig(config) { var elementData = $(this._element).data(); if (elementData.placement !== undefined) { elementData.placement = AttachmentMap[elementData.placement.toUpperCase()]; } config = $.extend({}, this.constructor.Default, $(this._element).data(), config); Util.typeCheckConfig(NAME, config, this.constructor.DefaultType); return config; }; Dropdown.prototype._getMenuElement = function _getMenuElement() { if (!this._menu) { var parent = Dropdown._getParentFromElement(this._element); this._menu = $(parent).find(Selector.MENU)[0]; } return this._menu; }; Dropdown.prototype._getPlacement = function _getPlacement() { var $parentDropdown = $(this._element).parent(); var placement = this._config.placement; // Handle dropup if ($parentDropdown.hasClass(ClassName.DROPUP) || this._config.placement === AttachmentMap.TOP) { placement = AttachmentMap.TOP; if ($(this._menu).hasClass(ClassName.MENURIGHT)) { placement = AttachmentMap.TOPEND; } } else if ($(this._menu).hasClass(ClassName.MENURIGHT)) { placement = AttachmentMap.BOTTOMEND; } return placement; }; Dropdown.prototype._detectNavbar = function _detectNavbar() { return $(this._element).closest('.navbar').length > 0; }; Dropdown.prototype._getPopperConfig = function _getPopperConfig() { var popperConfig = { placement: this._getPlacement(), modifiers: { offset: { offset: this._config.offset }, flip: { enabled: this._config.flip } } // Disable Popper.js for Dropdown in Navbar };if (this._inNavbar) { popperConfig.modifiers.applyStyle = { enabled: !this._inNavbar }; } return popperConfig; }; // static Dropdown._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' ? config : null; if (!data) { data = new Dropdown(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](); } }); }; Dropdown._clearMenus = function _clearMenus(event) { if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH || event.type === 'keyup' && event.which !== TAB_KEYCODE)) { return; } var toggles = $.makeArray($(Selector.DATA_TOGGLE)); for (var i = 0; i < toggles.length; i++) { var parent = Dropdown._getParentFromElement(toggles[i]); var context = $(toggles[i]).data(DATA_KEY); var relatedTarget = { relatedTarget: toggles[i] }; if (!context) { continue; } var dropdownMenu = context._menu; if (!$(parent).hasClass(ClassName.SHOW)) { continue; } if (event && (event.type === 'click' && /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) && $.contains(parent, event.target)) { continue; } var hideEvent = $.Event(Event.HIDE, relatedTarget); $(parent).trigger(hideEvent); if (hideEvent.isDefaultPrevented()) { continue; } // if this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support if ('ontouchstart' in document.documentElement) { $('body').children().off('mouseover', null, $.noop); } toggles[i].setAttribute('aria-expanded', 'false'); $(dropdownMenu).removeClass(ClassName.SHOW); $(parent).removeClass(ClassName.SHOW).trigger($.Event(Event.HIDDEN, relatedTarget)); } }; Dropdown._getParentFromElement = function _getParentFromElement(element) { var parent = void 0; var selector = Util.getSelectorFromElement(element); if (selector) { parent = $(selector)[0]; } return parent || element.parentNode; }; Dropdown._dataApiKeydownHandler = function _dataApiKeydownHandler(event) { if (!REGEXP_KEYDOWN.test(event.which) || /button/i.test(event.target.tagName) && event.which === SPACE_KEYCODE || /input|textarea/i.test(event.target.tagName)) { return; } event.preventDefault(); event.stopPropagation(); if (this.disabled || $(this).hasClass(ClassName.DISABLED)) { return; } var parent = Dropdown._getParentFromElement(this); var isActive = $(parent).hasClass(ClassName.SHOW); if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) || isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) { if (event.which === ESCAPE_KEYCODE) { var toggle = $(parent).find(Selector.DATA_TOGGLE)[0]; $(toggle).trigger('focus'); } $(this).trigger('click'); return; } var items = $(parent).find(Selector.VISIBLE_ITEMS).get(); if (!items.length) { return; } var index = items.indexOf(event.target); if (event.which === ARROW_UP_KEYCODE && index > 0) { // up index--; } if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // down index++; } if (index < 0) { index = 0; } items[index].focus(); }; _createClass(Dropdown, null, [{ key: 'VERSION', get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }, { key: 'DefaultType', get: function get() { return DefaultType; } }]); return Dropdown; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document).on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, Dropdown._dataApiKeydownHandler).on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler).on(Event.CLICK_DATA_API + ' ' + Event.KEYUP_DATA_API, Dropdown._clearMenus).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) { event.preventDefault(); event.stopPropagation(); Dropdown._jQueryInterface.call($(this), 'toggle'); }).on(Event.CLICK_DATA_API, Selector.FORM_CHILD, function (e) { e.stopPropagation(); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Dropdown._jQueryInterface; $.fn[NAME].Constructor = Dropdown; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Dropdown._jQueryInterface; }; return Dropdown; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): modal.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Modal = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'modal'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.modal'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 300; var BACKDROP_TRANSITION_DURATION = 150; var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key var Default = { backdrop: true, keyboard: true, focus: true, show: true }; var DefaultType = { backdrop: '(boolean|string)', keyboard: 'boolean', focus: 'boolean', show: 'boolean' }; var Event = { HIDE: 'hide' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY, FOCUSIN: 'focusin' + EVENT_KEY, RESIZE: 'resize' + EVENT_KEY, CLICK_DISMISS: 'click.dismiss' + EVENT_KEY, KEYDOWN_DISMISS: 'keydown.dismiss' + EVENT_KEY, MOUSEUP_DISMISS: 'mouseup.dismiss' + EVENT_KEY, MOUSEDOWN_DISMISS: 'mousedown.dismiss' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY }; var ClassName = { SCROLLBAR_MEASURER: 'modal-scrollbar-measure', BACKDROP: 'modal-backdrop', OPEN: 'modal-open', FADE: 'fade', SHOW: 'show' }; var Selector = { DIALOG: '.modal-dialog', DATA_TOGGLE: '[data-toggle="modal"]', DATA_DISMISS: '[data-dismiss="modal"]', FIXED_CONTENT: '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top', NAVBAR_TOGGLER: '.navbar-toggler' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Modal = function () { function Modal(element, config) { _classCallCheck(this, Modal); this._config = this._getConfig(config); this._element = element; this._dialog = $(element).find(Selector.DIALOG)[0]; this._backdrop = null; this._isShown = false; this._isBodyOverflowing = false; this._ignoreBackdropClick = false; this._originalBodyPadding = 0; this._scrollbarWidth = 0; } // getters // public Modal.prototype.toggle = function toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); }; Modal.prototype.show = function show(relatedTarget) { var _this10 = this; if (this._isTransitioning) { return; } if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) { this._isTransitioning = true; } var showEvent = $.Event(Event.SHOW, { relatedTarget: relatedTarget }); $(this._element).trigger(showEvent); if (this._isShown || showEvent.isDefaultPrevented()) { return; } this._isShown = true; this._checkScrollbar(); this._setScrollbar(); $(document.body).addClass(ClassName.OPEN); this._setEscapeEvent(); this._setResizeEvent(); $(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, function (event) { return _this10.hide(event); }); $(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () { $(_this10._element).one(Event.MOUSEUP_DISMISS, function (event) { if ($(event.target).is(_this10._element)) { _this10._ignoreBackdropClick = true; } }); }); this._showBackdrop(function () { return _this10._showElement(relatedTarget); }); }; Modal.prototype.hide = function hide(event) { var _this11 = this; if (event) { event.preventDefault(); } if (this._isTransitioning || !this._isShown) { return; } var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE); if (transition) { this._isTransitioning = true; } var hideEvent = $.Event(Event.HIDE); $(this._element).trigger(hideEvent); if (!this._isShown || hideEvent.isDefaultPrevented()) { return; } this._isShown = false; this._setEscapeEvent(); this._setResizeEvent(); $(document).off(Event.FOCUSIN); $(this._element).removeClass(ClassName.SHOW); $(this._element).off(Event.CLICK_DISMISS); $(this._dialog).off(Event.MOUSEDOWN_DISMISS); if (transition) { $(this._element).one(Util.TRANSITION_END, function (event) { return _this11._hideModal(event); }).emulateTransitionEnd(TRANSITION_DURATION); } else { this._hideModal(); } }; Modal.prototype.dispose = function dispose() { $.removeData(this._element, DATA_KEY); $(window, document, this._element, this._backdrop).off(EVENT_KEY); this._config = null; this._element = null; this._dialog = null; this._backdrop = null; this._isShown = null; this._isBodyOverflowing = null; this._ignoreBackdropClick = null; this._scrollbarWidth = null; }; Modal.prototype.handleUpdate = function handleUpdate() { this._adjustDialog(); }; // private Modal.prototype._getConfig = function _getConfig(config) { config = $.extend({}, Default, config); Util.typeCheckConfig(NAME, config, DefaultType); return config; }; Modal.prototype._showElement = function _showElement(relatedTarget) { var _this12 = this; var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE); if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) { // don't move modals dom position document.body.appendChild(this._element); } this._element.style.display = 'block'; this._element.removeAttribute('aria-hidden'); this._element.scrollTop = 0; if (transition) { Util.reflow(this._element); } $(this._element).addClass(ClassName.SHOW); if (this._config.focus) { this._enforceFocus(); } var shownEvent = $.Event(Event.SHOWN, { relatedTarget: relatedTarget }); var transitionComplete = function transitionComplete() { if (_this12._config.focus) { _this12._element.focus(); } _this12._isTransitioning = false; $(_this12._element).trigger(shownEvent); }; if (transition) { $(this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION); } else { transitionComplete(); } }; Modal.prototype._enforceFocus = function _enforceFocus() { var _this13 = this; $(document).off(Event.FOCUSIN) // guard against infinite focus loop .on(Event.FOCUSIN, function (event) { if (document !== event.target && _this13._element !== event.target && !$(_this13._element).has(event.target).length) { _this13._element.focus(); } }); }; Modal.prototype._setEscapeEvent = function _setEscapeEvent() { var _this14 = this; if (this._isShown && this._config.keyboard) { $(this._element).on(Event.KEYDOWN_DISMISS, function (event) { if (event.which === ESCAPE_KEYCODE) { event.preventDefault(); _this14.hide(); } }); } else if (!this._isShown) { $(this._element).off(Event.KEYDOWN_DISMISS); } }; Modal.prototype._setResizeEvent = function _setResizeEvent() { var _this15 = this; if (this._isShown) { $(window).on(Event.RESIZE, function (event) { return _this15.handleUpdate(event); }); } else { $(window).off(Event.RESIZE); } }; Modal.prototype._hideModal = function _hideModal() { var _this16 = this; this._element.style.display = 'none'; this._element.setAttribute('aria-hidden', true); this._isTransitioning = false; this._showBackdrop(function () { $(document.body).removeClass(ClassName.OPEN); _this16._resetAdjustments(); _this16._resetScrollbar(); $(_this16._element).trigger(Event.HIDDEN); }); }; Modal.prototype._removeBackdrop = function _removeBackdrop() { if (this._backdrop) { $(this._backdrop).remove(); this._backdrop = null; } }; Modal.prototype._showBackdrop = function _showBackdrop(callback) { var _this17 = this; var animate = $(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : ''; if (this._isShown && this._config.backdrop) { var doAnimate = Util.supportsTransitionEnd() && animate; this._backdrop = document.createElement('div'); this._backdrop.className = ClassName.BACKDROP; if (animate) { $(this._backdrop).addClass(animate); } $(this._backdrop).appendTo(document.body); $(this._element).on(Event.CLICK_DISMISS, function (event) { if (_this17._ignoreBackdropClick) { _this17._ignoreBackdropClick = false; return; } if (event.target !== event.currentTarget) { return; } if (_this17._config.backdrop === 'static') { _this17._element.focus(); } else { _this17.hide(); } }); if (doAnimate) { Util.reflow(this._backdrop); } $(this._backdrop).addClass(ClassName.SHOW); if (!callback) { return; } if (!doAnimate) { callback(); return; } $(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION); } else if (!this._isShown && this._backdrop) { $(this._backdrop).removeClass(ClassName.SHOW); var callbackRemove = function callbackRemove() { _this17._removeBackdrop(); if (callback) { callback(); } }; if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) { $(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION); } else { callbackRemove(); } } else if (callback) { callback(); } }; // ---------------------------------------------------------------------- // the following methods are used to handle overflowing modals // todo (fat): these should probably be refactored out of modal.js // ---------------------------------------------------------------------- Modal.prototype._adjustDialog = function _adjustDialog() { var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; if (!this._isBodyOverflowing && isModalOverflowing) { this._element.style.paddingLeft = this._scrollbarWidth + 'px'; } if (this._isBodyOverflowing && !isModalOverflowing) { this._element.style.paddingRight = this._scrollbarWidth + 'px'; } }; Modal.prototype._resetAdjustments = function _resetAdjustments() { this._element.style.paddingLeft = ''; this._element.style.paddingRight = ''; }; Modal.prototype._checkScrollbar = function _checkScrollbar() { this._isBodyOverflowing = document.body.clientWidth < window.innerWidth; this._scrollbarWidth = this._getScrollbarWidth(); }; Modal.prototype._setScrollbar = function _setScrollbar() { var _this18 = this; if (this._isBodyOverflowing) { // Note: DOMNode.style.paddingRight returns the actual value or '' if not set // while $(DOMNode).css('padding-right') returns the calculated value or 0 if not set // Adjust fixed content padding $(Selector.FIXED_CONTENT).each(function (index, element) { var actualPadding = $(element)[0].style.paddingRight; var calculatedPadding = $(element).css('padding-right'); $(element).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + _this18._scrollbarWidth + 'px'); }); // Adjust navbar-toggler margin $(Selector.NAVBAR_TOGGLER).each(function (index, element) { var actualMargin = $(element)[0].style.marginRight; var calculatedMargin = $(element).css('margin-right'); $(element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) + _this18._scrollbarWidth + 'px'); }); // Adjust body padding var actualPadding = document.body.style.paddingRight; var calculatedPadding = $('body').css('padding-right'); $('body').data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + this._scrollbarWidth + 'px'); } }; Modal.prototype._resetScrollbar = function _resetScrollbar() { // Restore fixed content padding $(Selector.FIXED_CONTENT).each(function (index, element) { var padding = $(element).data('padding-right'); if (typeof padding !== 'undefined') { $(element).css('padding-right', padding).removeData('padding-right'); } }); // Restore navbar-toggler margin $(Selector.NAVBAR_TOGGLER).each(function (index, element) { var margin = $(element).data('margin-right'); if (typeof margin !== 'undefined') { $(element).css('margin-right', margin).removeData('margin-right'); } }); // Restore body padding var padding = $('body').data('padding-right'); if (typeof padding !== 'undefined') { $('body').css('padding-right', padding).removeData('padding-right'); } }; Modal.prototype._getScrollbarWidth = function _getScrollbarWidth() { // thx d.walsh var scrollDiv = document.createElement('div'); scrollDiv.className = ClassName.SCROLLBAR_MEASURER; document.body.appendChild(scrollDiv); var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); return scrollbarWidth; }; // static Modal._jQueryInterface = function _jQueryInterface(config, relatedTarget) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = $.extend({}, Modal.Default, $(this).data(), (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config); if (!data) { data = new Modal(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](relatedTarget); } else if (_config.show) { data.show(relatedTarget); } }); }; _createClass(Modal, null, [{ key: 'VERSION', get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }]); return Modal; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) { var _this19 = this; var target = void 0; var selector = Util.getSelectorFromElement(this); if (selector) { target = $(selector)[0]; } var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data()); if (this.tagName === 'A' || this.tagName === 'AREA') { event.preventDefault(); } var $target = $(target).one(Event.SHOW, function (showEvent) { if (showEvent.isDefaultPrevented()) { // only register focus restorer if modal will actually get shown return; } $target.one(Event.HIDDEN, function () { if ($(_this19).is(':visible')) { _this19.focus(); } }); }); Modal._jQueryInterface.call($(target), config, this); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Modal._jQueryInterface; $.fn[NAME].Constructor = Modal; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Modal._jQueryInterface; }; return Modal; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): scrollspy.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var ScrollSpy = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'scrollspy'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.scrollspy'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var Default = { offset: 10, method: 'auto', target: '' }; var DefaultType = { offset: 'number', method: 'string', target: '(string|element)' }; var Event = { ACTIVATE: 'activate' + EVENT_KEY, SCROLL: 'scroll' + EVENT_KEY, LOAD_DATA_API: 'load' + EVENT_KEY + DATA_API_KEY }; var ClassName = { DROPDOWN_ITEM: 'dropdown-item', DROPDOWN_MENU: 'dropdown-menu', ACTIVE: 'active' }; var Selector = { DATA_SPY: '[data-spy="scroll"]', ACTIVE: '.active', NAV_LIST_GROUP: '.nav, .list-group', NAV_LINKS: '.nav-link', LIST_ITEMS: '.list-group-item', DROPDOWN: '.dropdown', DROPDOWN_ITEMS: '.dropdown-item', DROPDOWN_TOGGLE: '.dropdown-toggle' }; var OffsetMethod = { OFFSET: 'offset', POSITION: 'position' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var ScrollSpy = function () { function ScrollSpy(element, config) { var _this20 = this; _classCallCheck(this, ScrollSpy); this._element = element; this._scrollElement = element.tagName === 'BODY' ? window : element; this._config = this._getConfig(config); this._selector = this._config.target + ' ' + Selector.NAV_LINKS + ',' + (this._config.target + ' ' + Selector.LIST_ITEMS + ',') + (this._config.target + ' ' + Selector.DROPDOWN_ITEMS); this._offsets = []; this._targets = []; this._activeTarget = null; this._scrollHeight = 0; $(this._scrollElement).on(Event.SCROLL, function (event) { return _this20._process(event); }); this.refresh(); this._process(); } // getters // public ScrollSpy.prototype.refresh = function refresh() { var _this21 = this; var autoMethod = this._scrollElement !== this._scrollElement.window ? OffsetMethod.POSITION : OffsetMethod.OFFSET; var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method; var offsetBase = offsetMethod === OffsetMethod.POSITION ? this._getScrollTop() : 0; this._offsets = []; this._targets = []; this._scrollHeight = this._getScrollHeight(); var targets = $.makeArray($(this._selector)); targets.map(function (element) { var target = void 0; var targetSelector = Util.getSelectorFromElement(element); if (targetSelector) { target = $(targetSelector)[0]; } if (target) { var targetBCR = target.getBoundingClientRect(); if (targetBCR.width || targetBCR.height) { // todo (fat): remove sketch reliance on jQuery position/offset return [$(target)[offsetMethod]().top + offsetBase, targetSelector]; } } return null; }).filter(function (item) { return item; }).sort(function (a, b) { return a[0] - b[0]; }).forEach(function (item) { _this21._offsets.push(item[0]); _this21._targets.push(item[1]); }); }; ScrollSpy.prototype.dispose = function dispose() { $.removeData(this._element, DATA_KEY); $(this._scrollElement).off(EVENT_KEY); this._element = null; this._scrollElement = null; this._config = null; this._selector = null; this._offsets = null; this._targets = null; this._activeTarget = null; this._scrollHeight = null; }; // private ScrollSpy.prototype._getConfig = function _getConfig(config) { config = $.extend({}, Default, config); if (typeof config.target !== 'string') { var id = $(config.target).attr('id'); if (!id) { id = Util.getUID(NAME); $(config.target).attr('id', id); } config.target = '#' + id; } Util.typeCheckConfig(NAME, config, DefaultType); return config; }; ScrollSpy.prototype._getScrollTop = function _getScrollTop() { return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop; }; ScrollSpy.prototype._getScrollHeight = function _getScrollHeight() { return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); }; ScrollSpy.prototype._getOffsetHeight = function _getOffsetHeight() { return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height; }; ScrollSpy.prototype._process = function _process() { var scrollTop = this._getScrollTop() + this._config.offset; var scrollHeight = this._getScrollHeight(); var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight(); if (this._scrollHeight !== scrollHeight) { this.refresh(); } if (scrollTop >= maxScroll) { var target = this._targets[this._targets.length - 1]; if (this._activeTarget !== target) { this._activate(target); } return; } if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) { this._activeTarget = null; this._clear(); return; } for (var i = this._offsets.length; i--;) { var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (this._offsets[i + 1] === undefined || scrollTop < this._offsets[i + 1]); if (isActiveTarget) { this._activate(this._targets[i]); } } }; ScrollSpy.prototype._activate = function _activate(target) { this._activeTarget = target; this._clear(); var queries = this._selector.split(','); queries = queries.map(function (selector) { return selector + '[data-target="' + target + '"],' + (selector + '[href="' + target + '"]'); }); var $link = $(queries.join(',')); if ($link.hasClass(ClassName.DROPDOWN_ITEM)) { $link.closest(Selector.DROPDOWN).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE); $link.addClass(ClassName.ACTIVE); } else { // Set triggered link as active $link.addClass(ClassName.ACTIVE); // Set triggered links.js parents as active // With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor $link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_LINKS + ', ' + Selector.LIST_ITEMS).addClass(ClassName.ACTIVE); } $(this._scrollElement).trigger(Event.ACTIVATE, { relatedTarget: target }); }; ScrollSpy.prototype._clear = function _clear() { $(this._selector).filter(Selector.ACTIVE).removeClass(ClassName.ACTIVE); }; // static ScrollSpy._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config; if (!data) { data = new ScrollSpy(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](); } }); }; _createClass(ScrollSpy, null, [{ key: 'VERSION', get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }]); return ScrollSpy; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(window).on(Event.LOAD_DATA_API, function () { var scrollSpys = $.makeArray($(Selector.DATA_SPY)); for (var i = scrollSpys.length; i--;) { var $spy = $(scrollSpys[i]); ScrollSpy._jQueryInterface.call($spy, $spy.data()); } }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = ScrollSpy._jQueryInterface; $.fn[NAME].Constructor = ScrollSpy; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return ScrollSpy._jQueryInterface; }; return ScrollSpy; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): tab.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Tab = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'tab'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.tab'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 150; var Event = { HIDE: 'hide' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY }; var ClassName = { DROPDOWN_MENU: 'dropdown-menu', ACTIVE: 'active', DISABLED: 'disabled', FADE: 'fade', SHOW: 'show' }; var Selector = { DROPDOWN: '.dropdown', NAV_LIST_GROUP: '.nav, .list-group', ACTIVE: '.active', DATA_TOGGLE: '[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]', DROPDOWN_TOGGLE: '.dropdown-toggle', DROPDOWN_ACTIVE_CHILD: '> .dropdown-menu .active' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Tab = function () { function Tab(element) { _classCallCheck(this, Tab); this._element = element; } // getters // public Tab.prototype.show = function show() { var _this22 = this; if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.ACTIVE) || $(this._element).hasClass(ClassName.DISABLED)) { return; } var target = void 0; var previous = void 0; var listElement = $(this._element).closest(Selector.NAV_LIST_GROUP)[0]; var selector = Util.getSelectorFromElement(this._element); if (listElement) { previous = $.makeArray($(listElement).find(Selector.ACTIVE)); previous = previous[previous.length - 1]; } var hideEvent = $.Event(Event.HIDE, { relatedTarget: this._element }); var showEvent = $.Event(Event.SHOW, { relatedTarget: previous }); if (previous) { $(previous).trigger(hideEvent); } $(this._element).trigger(showEvent); if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) { return; } if (selector) { target = $(selector)[0]; } this._activate(this._element, listElement); var complete = function complete() { var hiddenEvent = $.Event(Event.HIDDEN, { relatedTarget: _this22._element }); var shownEvent = $.Event(Event.SHOWN, { relatedTarget: previous }); $(previous).trigger(hiddenEvent); $(_this22._element).trigger(shownEvent); }; if (target) { this._activate(target, target.parentNode, complete); } else { complete(); } }; Tab.prototype.dispose = function dispose() { $.removeData(this._element, DATA_KEY); this._element = null; }; // private Tab.prototype._activate = function _activate(element, container, callback) { var _this23 = this; var active = $(container).find(Selector.ACTIVE)[0]; var isTransitioning = callback && Util.supportsTransitionEnd() && active && $(active).hasClass(ClassName.FADE); var complete = function complete() { return _this23._transitionComplete(element, active, isTransitioning, callback); }; if (active && isTransitioning) { $(active).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION); } else { complete(); } if (active) { $(active).removeClass(ClassName.SHOW); } }; Tab.prototype._transitionComplete = function _transitionComplete(element, active, isTransitioning, callback) { if (active) { $(active).removeClass(ClassName.ACTIVE); var dropdownChild = $(active.parentNode).find(Selector.DROPDOWN_ACTIVE_CHILD)[0]; if (dropdownChild) { $(dropdownChild).removeClass(ClassName.ACTIVE); } active.setAttribute('aria-expanded', false); } $(element).addClass(ClassName.ACTIVE); element.setAttribute('aria-expanded', true); if (isTransitioning) { Util.reflow(element); $(element).addClass(ClassName.SHOW); } else { $(element).removeClass(ClassName.FADE); } if (element.parentNode && $(element.parentNode).hasClass(ClassName.DROPDOWN_MENU)) { var dropdownElement = $(element).closest(Selector.DROPDOWN)[0]; if (dropdownElement) { $(dropdownElement).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE); } element.setAttribute('aria-expanded', true); } if (callback) { callback(); } }; // static Tab._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var $this = $(this); var data = $this.data(DATA_KEY); if (!data) { data = new Tab(this); $this.data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](); } }); }; _createClass(Tab, null, [{ key: 'VERSION', get: function get() { return VERSION; } }]); return Tab; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) { event.preventDefault(); Tab._jQueryInterface.call($(this), 'show'); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Tab._jQueryInterface; $.fn[NAME].Constructor = Tab; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Tab._jQueryInterface; }; return Tab; }(jQuery); /* global Popper */ /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): tooltip.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Tooltip = function ($) { /** * Check for Popper dependency * Popper - https://popper.js.org */ if (typeof Popper === 'undefined') { throw new Error('Bootstrap tooltips require Popper.js (https://popper.js.org)'); } /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'tooltip'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.tooltip'; var EVENT_KEY = '.' + DATA_KEY; var JQUERY_NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 150; var CLASS_PREFIX = 'bs-tooltip'; var BSCLS_PREFIX_REGEX = new RegExp('(^|\\s)' + CLASS_PREFIX + '\\S+', 'g'); var DefaultType = { animation: 'boolean', template: 'string', title: '(string|element|function)', trigger: 'string', delay: '(number|object)', html: 'boolean', selector: '(string|boolean)', placement: '(string|function)', offset: '(number|string)', container: '(string|element|boolean)', fallbackPlacement: '(string|array)' }; var AttachmentMap = { AUTO: 'auto', TOP: 'top', RIGHT: 'right', BOTTOM: 'bottom', LEFT: 'left' }; var Default = { animation: true, template: '<div class="tooltip" role="tooltip">' + '<div class="arrow"></div>' + '<div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, selector: false, placement: 'top', offset: 0, container: false, fallbackPlacement: 'flip' }; var HoverState = { SHOW: 'show', OUT: 'out' }; var Event = { HIDE: 'hide' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY, INSERTED: 'inserted' + EVENT_KEY, CLICK: 'click' + EVENT_KEY, FOCUSIN: 'focusin' + EVENT_KEY, FOCUSOUT: 'focusout' + EVENT_KEY, MOUSEENTER: 'mouseenter' + EVENT_KEY, MOUSELEAVE: 'mouseleave' + EVENT_KEY }; var ClassName = { FADE: 'fade', SHOW: 'show' }; var Selector = { TOOLTIP: '.tooltip', TOOLTIP_INNER: '.tooltip-inner', ARROW: '.arrow' }; var Trigger = { HOVER: 'hover', FOCUS: 'focus', CLICK: 'click', MANUAL: 'manual' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Tooltip = function () { function Tooltip(element, config) { _classCallCheck(this, Tooltip); // private this._isEnabled = true; this._timeout = 0; this._hoverState = ''; this._activeTrigger = {}; this._popper = null; // protected this.element = element; this.config = this._getConfig(config); this.tip = null; this._setListeners(); } // getters // public Tooltip.prototype.enable = function enable() { this._isEnabled = true; }; Tooltip.prototype.disable = function disable() { this._isEnabled = false; }; Tooltip.prototype.toggleEnabled = function toggleEnabled() { this._isEnabled = !this._isEnabled; }; Tooltip.prototype.toggle = function toggle(event) { if (event) { var dataKey = this.constructor.DATA_KEY; var context = $(event.currentTarget).data(dataKey); if (!context) { context = new this.constructor(event.currentTarget, this._getDelegateConfig()); $(event.currentTarget).data(dataKey, context); } context._activeTrigger.click = !context._activeTrigger.click; if (context._isWithActiveTrigger()) { context._enter(null, context); } else { context._leave(null, context); } } else { if ($(this.getTipElement()).hasClass(ClassName.SHOW)) { this._leave(null, this); return; } this._enter(null, this); } }; Tooltip.prototype.dispose = function dispose() { clearTimeout(this._timeout); $.removeData(this.element, this.constructor.DATA_KEY); $(this.element).off(this.constructor.EVENT_KEY); $(this.element).closest('.modal').off('hide.bs.modal'); if (this.tip) { $(this.tip).remove(); } this._isEnabled = null; this._timeout = null; this._hoverState = null; this._activeTrigger = null; if (this._popper !== null) { this._popper.destroy(); } this._popper = null; this.element = null; this.config = null; this.tip = null; }; Tooltip.prototype.show = function show() { var _this24 = this; if ($(this.element).css('display') === 'none') { throw new Error('Please use show on visible elements'); } var showEvent = $.Event(this.constructor.Event.SHOW); if (this.isWithContent() && this._isEnabled) { $(this.element).trigger(showEvent); var isInTheDom = $.contains(this.element.ownerDocument.documentElement, this.element); if (showEvent.isDefaultPrevented() || !isInTheDom) { return; } var tip = this.getTipElement(); var tipId = Util.getUID(this.constructor.NAME); tip.setAttribute('id', tipId); this.element.setAttribute('aria-describedby', tipId); this.setContent(); if (this.config.animation) { $(tip).addClass(ClassName.FADE); } var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement; var attachment = this._getAttachment(placement); this.addAttachmentClass(attachment); var container = this.config.container === false ? document.body : $(this.config.container); $(tip).data(this.constructor.DATA_KEY, this); if (!$.contains(this.element.ownerDocument.documentElement, this.tip)) { $(tip).appendTo(container); } $(this.element).trigger(this.constructor.Event.INSERTED); this._popper = new Popper(this.element, tip, { placement: attachment, modifiers: { offset: { offset: this.config.offset }, flip: { behavior: this.config.fallbackPlacement }, arrow: { element: Selector.ARROW } }, onCreate: function onCreate(data) { if (data.originalPlacement !== data.placement) { _this24._handlePopperPlacementChange(data); } }, onUpdate: function onUpdate(data) { _this24._handlePopperPlacementChange(data); } }); $(tip).addClass(ClassName.SHOW); // if this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html if ('ontouchstart' in document.documentElement) { $('body').children().on('mouseover', null, $.noop); } var complete = function complete() { if (_this24.config.animation) { _this24._fixTransition(); } var prevHoverState = _this24._hoverState; _this24._hoverState = null; $(_this24.element).trigger(_this24.constructor.Event.SHOWN); if (prevHoverState === HoverState.OUT) { _this24._leave(null, _this24); } }; if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) { $(this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(Tooltip._TRANSITION_DURATION); } else { complete(); } } }; Tooltip.prototype.hide = function hide(callback) { var _this25 = this; var tip = this.getTipElement(); var hideEvent = $.Event(this.constructor.Event.HIDE); var complete = function complete() { if (_this25._hoverState !== HoverState.SHOW && tip.parentNode) { tip.parentNode.removeChild(tip); } _this25._cleanTipClass(); _this25.element.removeAttribute('aria-describedby'); $(_this25.element).trigger(_this25.constructor.Event.HIDDEN); if (_this25._popper !== null) { _this25._popper.destroy(); } if (callback) { callback(); } }; $(this.element).trigger(hideEvent); if (hideEvent.isDefaultPrevented()) { return; } $(tip).removeClass(ClassName.SHOW); // if this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support if ('ontouchstart' in document.documentElement) { $('body').children().off('mouseover', null, $.noop); } this._activeTrigger[Trigger.CLICK] = false; this._activeTrigger[Trigger.FOCUS] = false; this._activeTrigger[Trigger.HOVER] = false; if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) { $(tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION); } else { complete(); } this._hoverState = ''; }; Tooltip.prototype.update = function update() { if (this._popper !== null) { this._popper.scheduleUpdate(); } }; // protected Tooltip.prototype.isWithContent = function isWithContent() { return Boolean(this.getTitle()); }; Tooltip.prototype.addAttachmentClass = function addAttachmentClass(attachment) { $(this.getTipElement()).addClass(CLASS_PREFIX + '-' + attachment); }; Tooltip.prototype.getTipElement = function getTipElement() { return this.tip = this.tip || $(this.config.template)[0]; }; Tooltip.prototype.setContent = function setContent() { var $tip = $(this.getTipElement()); this.setElementContent($tip.find(Selector.TOOLTIP_INNER), this.getTitle()); $tip.removeClass(ClassName.FADE + ' ' + ClassName.SHOW); }; Tooltip.prototype.setElementContent = function setElementContent($element, content) { var html = this.config.html; if ((typeof content === 'undefined' ? 'undefined' : _typeof(content)) === 'object' && (content.nodeType || content.jquery)) { // content is a DOM node or a jQuery if (html) { if (!$(content).parent().is($element)) { $element.empty().append(content); } } else { $element.text($(content).text()); } } else { $element[html ? 'html' : 'text'](content); } }; Tooltip.prototype.getTitle = function getTitle() { var title = this.element.getAttribute('data-original-title'); if (!title) { title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title; } return title; }; // private Tooltip.prototype._getAttachment = function _getAttachment(placement) { return AttachmentMap[placement.toUpperCase()]; }; Tooltip.prototype._setListeners = function _setListeners() { var _this26 = this; var triggers = this.config.trigger.split(' '); triggers.forEach(function (trigger) { if (trigger === 'click') { $(_this26.element).on(_this26.constructor.Event.CLICK, _this26.config.selector, function (event) { return _this26.toggle(event); }); } else if (trigger !== Trigger.MANUAL) { var eventIn = trigger === Trigger.HOVER ? _this26.constructor.Event.MOUSEENTER : _this26.constructor.Event.FOCUSIN; var eventOut = trigger === Trigger.HOVER ? _this26.constructor.Event.MOUSELEAVE : _this26.constructor.Event.FOCUSOUT; $(_this26.element).on(eventIn, _this26.config.selector, function (event) { return _this26._enter(event); }).on(eventOut, _this26.config.selector, function (event) { return _this26._leave(event); }); } $(_this26.element).closest('.modal').on('hide.bs.modal', function () { return _this26.hide(); }); }); if (this.config.selector) { this.config = $.extend({}, this.config, { trigger: 'manual', selector: '' }); } else { this._fixTitle(); } }; Tooltip.prototype._fixTitle = function _fixTitle() { var titleType = _typeof(this.element.getAttribute('data-original-title')); if (this.element.getAttribute('title') || titleType !== 'string') { this.element.setAttribute('data-original-title', this.element.getAttribute('title') || ''); this.element.setAttribute('title', ''); } }; Tooltip.prototype._enter = function _enter(event, context) { var dataKey = this.constructor.DATA_KEY; context = context || $(event.currentTarget).data(dataKey); if (!context) { context = new this.constructor(event.currentTarget, this._getDelegateConfig()); $(event.currentTarget).data(dataKey, context); } if (event) { context._activeTrigger[event.type === 'focusin' ? Trigger.FOCUS : Trigger.HOVER] = true; } if ($(context.getTipElement()).hasClass(ClassName.SHOW) || context._hoverState === HoverState.SHOW) { context._hoverState = HoverState.SHOW; return; } clearTimeout(context._timeout); context._hoverState = HoverState.SHOW; if (!context.config.delay || !context.config.delay.show) { context.show(); return; } context._timeout = setTimeout(function () { if (context._hoverState === HoverState.SHOW) { context.show(); } }, context.config.delay.show); }; Tooltip.prototype._leave = function _leave(event, context) { var dataKey = this.constructor.DATA_KEY; context = context || $(event.currentTarget).data(dataKey); if (!context) { context = new this.constructor(event.currentTarget, this._getDelegateConfig()); $(event.currentTarget).data(dataKey, context); } if (event) { context._activeTrigger[event.type === 'focusout' ? Trigger.FOCUS : Trigger.HOVER] = false; } if (context._isWithActiveTrigger()) { return; } clearTimeout(context._timeout); context._hoverState = HoverState.OUT; if (!context.config.delay || !context.config.delay.hide) { context.hide(); return; } context._timeout = setTimeout(function () { if (context._hoverState === HoverState.OUT) { context.hide(); } }, context.config.delay.hide); }; Tooltip.prototype._isWithActiveTrigger = function _isWithActiveTrigger() { for (var trigger in this._activeTrigger) { if (this._activeTrigger[trigger]) { return true; } } return false; }; Tooltip.prototype._getConfig = function _getConfig(config) { config = $.extend({}, this.constructor.Default, $(this.element).data(), config); if (config.delay && typeof config.delay === 'number') { config.delay = { show: config.delay, hide: config.delay }; } if (config.title && typeof config.title === 'number') { config.title = config.title.toString(); } if (config.content && typeof config.content === 'number') { config.content = config.content.toString(); } Util.typeCheckConfig(NAME, config, this.constructor.DefaultType); return config; }; Tooltip.prototype._getDelegateConfig = function _getDelegateConfig() { var config = {}; if (this.config) { for (var key in this.config) { if (this.constructor.Default[key] !== this.config[key]) { config[key] = this.config[key]; } } } return config; }; Tooltip.prototype._cleanTipClass = function _cleanTipClass() { var $tip = $(this.getTipElement()); var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX); if (tabClass !== null && tabClass.length > 0) { $tip.removeClass(tabClass.join('')); } }; Tooltip.prototype._handlePopperPlacementChange = function _handlePopperPlacementChange(data) { this._cleanTipClass(); this.addAttachmentClass(this._getAttachment(data.placement)); }; Tooltip.prototype._fixTransition = function _fixTransition() { var tip = this.getTipElement(); var initConfigAnimation = this.config.animation; if (tip.getAttribute('x-placement') !== null) { return; } $(tip).removeClass(ClassName.FADE); this.config.animation = false; this.hide(); this.show(); this.config.animation = initConfigAnimation; }; // static Tooltip._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config; if (!data && /dispose|hide/.test(config)) { return; } if (!data) { data = new Tooltip(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](); } }); }; _createClass(Tooltip, null, [{ key: 'VERSION', get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }, { key: 'NAME', get: function get() { return NAME; } }, { key: 'DATA_KEY', get: function get() { return DATA_KEY; } }, { key: 'Event', get: function get() { return Event; } }, { key: 'EVENT_KEY', get: function get() { return EVENT_KEY; } }, { key: 'DefaultType', get: function get() { return DefaultType; } }]); return Tooltip; }(); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Tooltip._jQueryInterface; $.fn[NAME].Constructor = Tooltip; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Tooltip._jQueryInterface; }; return Tooltip; }(jQuery); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0-beta): popover.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Popover = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'popover'; var VERSION = '4.0.0-beta'; var DATA_KEY = 'bs.popover'; var EVENT_KEY = '.' + DATA_KEY; var JQUERY_NO_CONFLICT = $.fn[NAME]; var CLASS_PREFIX = 'bs-popover'; var BSCLS_PREFIX_REGEX = new RegExp('(^|\\s)' + CLASS_PREFIX + '\\S+', 'g'); var Default = $.extend({}, Tooltip.Default, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip">' + '<div class="arrow"></div>' + '<h3 class="popover-header"></h3>' + '<div class="popover-body"></div></div>' }); var DefaultType = $.extend({}, Tooltip.DefaultType, { content: '(string|element|function)' }); var ClassName = { FADE: 'fade', SHOW: 'show' }; var Selector = { TITLE: '.popover-header', CONTENT: '.popover-body' }; var Event = { HIDE: 'hide' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY, INSERTED: 'inserted' + EVENT_KEY, CLICK: 'click' + EVENT_KEY, FOCUSIN: 'focusin' + EVENT_KEY, FOCUSOUT: 'focusout' + EVENT_KEY, MOUSEENTER: 'mouseenter' + EVENT_KEY, MOUSELEAVE: 'mouseleave' + EVENT_KEY /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var Popover = function (_Tooltip) { _inherits(Popover, _Tooltip); function Popover() { _classCallCheck(this, Popover); return _possibleConstructorReturn(this, _Tooltip.apply(this, arguments)); } // overrides Popover.prototype.isWithContent = function isWithContent() { return this.getTitle() || this._getContent(); }; Popover.prototype.addAttachmentClass = function addAttachmentClass(attachment) { $(this.getTipElement()).addClass(CLASS_PREFIX + '-' + attachment); }; Popover.prototype.getTipElement = function getTipElement() { return this.tip = this.tip || $(this.config.template)[0]; }; Popover.prototype.setContent = function setContent() { var $tip = $(this.getTipElement()); // we use append for html objects to maintain js events this.setElementContent($tip.find(Selector.TITLE), this.getTitle()); this.setElementContent($tip.find(Selector.CONTENT), this._getContent()); $tip.removeClass(ClassName.FADE + ' ' + ClassName.SHOW); }; // private Popover.prototype._getContent = function _getContent() { return this.element.getAttribute('data-content') || (typeof this.config.content === 'function' ? this.config.content.call(this.element) : this.config.content); }; Popover.prototype._cleanTipClass = function _cleanTipClass() { var $tip = $(this.getTipElement()); var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX); if (tabClass !== null && tabClass.length > 0) { $tip.removeClass(tabClass.join('')); } }; // static Popover._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' ? config : null; if (!data && /destroy|hide/.test(config)) { return; } if (!data) { data = new Popover(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](); } }); }; _createClass(Popover, null, [{ key: 'VERSION', // getters get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }, { key: 'NAME', get: function get() { return NAME; } }, { key: 'DATA_KEY', get: function get() { return DATA_KEY; } }, { key: 'Event', get: function get() { return Event; } }, { key: 'EVENT_KEY', get: function get() { return EVENT_KEY; } }, { key: 'DefaultType', get: function get() { return DefaultType; } }]); return Popover; }(Tooltip); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Popover._jQueryInterface; $.fn[NAME].Constructor = Popover; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Popover._jQueryInterface; }; return Popover; }(jQuery); })();
fr3nchN/proactive
docs/js/bootstrap.js
JavaScript
agpl-3.0
111,393
DELETE FROM `weenie` WHERE `class_Id` = 33844; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (33844, 'ace33844-blackflame', 10, '2019-02-10 00:00:00') /* Creature */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (33844, 1, 16) /* ItemType - Creature */ , (33844, 2, 22) /* CreatureType - Shadow */ , (33844, 6, -1) /* ItemsCapacity */ , (33844, 7, -1) /* ContainersCapacity */ , (33844, 16, 1) /* ItemUseable - No */ , (33844, 25, 160) /* Level */ , (33844, 93, 1032) /* PhysicsState - ReportCollisions, Gravity */ , (33844, 133, 4) /* ShowableOnRadar - ShowAlways */ , (33844, 8007, 0) /* PCAPRecordedAutonomousMovement */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (33844, 1, True ) /* Stuck */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (33844, 39, 1.2) /* DefaultScale */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (33844, 1, 'Black Flame') /* Name */ , (33844, 8006, 'AAE8AMEAAAA8AGdm5r9jABAAAAAAQAAAq94CUA==') /* PCAPRecordedCurrentMotionState */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (33844, 1, 0x0200089A) /* Setup */ , (33844, 2, 0x0900008F) /* MotionTable */ , (33844, 3, 0x20000049) /* SoundTable */ , (33844, 8, 0x0600141A) /* Icon */ , (33844, 22, 0x34000063) /* PhysicsEffectTable */ , (33844, 8001, 8388630) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, RadarBehavior */ , (33844, 8003, 20) /* PCAPRecordedObjectDesc - Stuck, Attackable */ , (33844, 8005, 104579) /* PCAPRecordedPhysicsDesc - CSetup, MTable, ObjScale, STable, PeTable, Position, Movement */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (33844, 8040, 0x00E60420, 188.5566, -26.64967, 0.000001, -0.976773, 0, 0, -0.214278) /* PCAPRecordedLocation */ /* @teleloc 0x00E60420 [188.556600 -26.649670 0.000001] -0.976773 0.000000 0.000000 -0.214278 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (33844, 8000, 0xC828E040) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_attribute` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`) VALUES (33844, 1, 290, 0, 0) /* Strength */ , (33844, 2, 330, 0, 0) /* Endurance */ , (33844, 3, 300, 0, 0) /* Quickness */ , (33844, 4, 290, 0, 0) /* Coordination */ , (33844, 5, 360, 0, 0) /* Focus */ , (33844, 6, 380, 0, 0) /* Self */; INSERT INTO `weenie_properties_attribute_2nd` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`) VALUES (33844, 1, 2000, 0, 0, 2165) /* MaxHealth */ , (33844, 3, 600, 0, 0, 930) /* MaxStamina */ , (33844, 5, 440, 0, 0, 820) /* MaxMana */;
ACEmulator/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Creature/Shadow/33844 Black Flame.sql
SQL
agpl-3.0
3,108
DELETE FROM `weenie` WHERE `class_Id` = 52221; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (52221, 'ace52221-frozenrecess', 7, '2019-02-10 00:00:00') /* Portal */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (52221, 1, 65536) /* ItemType - Portal */ , (52221, 16, 32) /* ItemUseable - Remote */ , (52221, 86, 180) /* MinLevel */ , (52221, 93, 3084) /* PhysicsState - Ethereal, ReportCollisions, Gravity, LightingOn */ , (52221, 111, 49) /* PortalBitmask - Unrestricted, NoSummon, NoRecall */ , (52221, 133, 4) /* ShowableOnRadar - ShowAlways */ , (52221, 8007, 0) /* PCAPRecordedAutonomousMovement */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (52221, 1, True ) /* Stuck */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (52221, 54, -0.1) /* UseRadius */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (52221, 1, 'Frozen Recess') /* Name */ , (52221, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (52221, 1, 0x020005D4) /* Setup */ , (52221, 2, 0x09000003) /* MotionTable */ , (52221, 8, 0x0600106B) /* Icon */ , (52221, 8001, 8388656) /* PCAPRecordedWeenieHeader - Usable, UseRadius, RadarBehavior */ , (52221, 8003, 262164) /* PCAPRecordedObjectDesc - Stuck, Attackable, Portal */ , (52221, 8005, 98307) /* PCAPRecordedPhysicsDesc - CSetup, MTable, Position, Movement */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (52221, 8040, 0x4EF60022, 114.598, 44.9705, 34.18946, 0.703035, 0, 0, -0.711155) /* PCAPRecordedLocation */ /* @teleloc 0x4EF60022 [114.598000 44.970500 34.189460] 0.703035 0.000000 0.000000 -0.711155 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (52221, 8000, 0x74EF6000) /* PCAPRecordedObjectIID */;
ACEmulator/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Portal/Portal/52221 Frozen Recess.sql
SQL
agpl-3.0
2,189
# frozen_string_literal: true require "spec_helper" module Decidim module ParticipatoryProcesses module Admin describe ParticipatoryProcessUserRoleForm do let(:email) { "my_email@example.org" } let(:name) { "John Wayne" } let(:role) { "admin" } let(:attributes) do { "participatory_process_user_role" => { "email" => email, "name" => name, "role" => role } } end subject { described_class.from_params(attributes) } context "when everything is OK" do it { is_expected.to be_valid } end context "when email is missing" do let(:email) {} it { is_expected.to be_invalid } end end end end end
Hilfe/decidim
decidim-participatory_processes/spec/forms/participatory_process_user_role_form_spec.rb
Ruby
agpl-3.0
814
package cn.edu.seu.kse.lpmln.exception.antlrexception; import org.antlr.v4.runtime.InputMismatchException; /** * Created by admin on 2017/8/30. */ public class AntlrInputMismatchException extends AntlrRecognitionException { public AntlrInputMismatchException(InputMismatchException e){ super(e); } }
wangbiu/lpmlnmodels
src/main/java/cn/edu/seu/kse/lpmln/exception/antlrexception/AntlrInputMismatchException.java
Java
agpl-3.0
321
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2015 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import org.w3c.dom.Element; import com.kaltura.client.KalturaParams; import com.kaltura.client.KalturaApiException; import java.util.ArrayList; import java.util.HashMap; import com.kaltura.client.utils.ParseUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaEntryContextDataResult extends KalturaContextDataResult { public boolean isSiteRestricted; public boolean isCountryRestricted; public boolean isSessionRestricted; public boolean isIpAddressRestricted; public boolean isUserAgentRestricted; public int previewLength = Integer.MIN_VALUE; public boolean isScheduledNow; public boolean isAdmin; /** http/rtmp/hdnetwork */ public String streamerType; /** http/https, rtmp/rtmpe */ public String mediaProtocol; public String storageProfilesXML; /** Array of messages as received from the access control rules that invalidated */ public ArrayList<KalturaString> accessControlMessages; /** Array of actions as received from the access control rules that invalidated */ public ArrayList<KalturaRuleAction> accessControlActions; /** Array of allowed flavor assets according to access control limitations and requested tags */ public ArrayList<KalturaFlavorAsset> flavorAssets; /** Array of allowed flavor assets according to access control limitations and requested tags */ public HashMap<String, KalturaPluginData> pluginData; public KalturaEntryContextDataResult() { } public KalturaEntryContextDataResult(Element node) throws KalturaApiException { super(node); NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node aNode = childNodes.item(i); String nodeName = aNode.getNodeName(); String txt = aNode.getTextContent(); if (nodeName.equals("isSiteRestricted")) { this.isSiteRestricted = ParseUtils.parseBool(txt); continue; } else if (nodeName.equals("isCountryRestricted")) { this.isCountryRestricted = ParseUtils.parseBool(txt); continue; } else if (nodeName.equals("isSessionRestricted")) { this.isSessionRestricted = ParseUtils.parseBool(txt); continue; } else if (nodeName.equals("isIpAddressRestricted")) { this.isIpAddressRestricted = ParseUtils.parseBool(txt); continue; } else if (nodeName.equals("isUserAgentRestricted")) { this.isUserAgentRestricted = ParseUtils.parseBool(txt); continue; } else if (nodeName.equals("previewLength")) { this.previewLength = ParseUtils.parseInt(txt); continue; } else if (nodeName.equals("isScheduledNow")) { this.isScheduledNow = ParseUtils.parseBool(txt); continue; } else if (nodeName.equals("isAdmin")) { this.isAdmin = ParseUtils.parseBool(txt); continue; } else if (nodeName.equals("streamerType")) { this.streamerType = ParseUtils.parseString(txt); continue; } else if (nodeName.equals("mediaProtocol")) { this.mediaProtocol = ParseUtils.parseString(txt); continue; } else if (nodeName.equals("storageProfilesXML")) { this.storageProfilesXML = ParseUtils.parseString(txt); continue; } else if (nodeName.equals("accessControlMessages")) { this.accessControlMessages = ParseUtils.parseArray(KalturaString.class, aNode); continue; } else if (nodeName.equals("accessControlActions")) { this.accessControlActions = ParseUtils.parseArray(KalturaRuleAction.class, aNode); continue; } else if (nodeName.equals("flavorAssets")) { this.flavorAssets = ParseUtils.parseArray(KalturaFlavorAsset.class, aNode); continue; } else if (nodeName.equals("pluginData")) { this.pluginData = ParseUtils.parseMap(KalturaPluginData.class, aNode); continue; } } } public KalturaParams toParams() throws KalturaApiException { KalturaParams kparams = super.toParams(); kparams.add("objectType", "KalturaEntryContextDataResult"); kparams.add("isSiteRestricted", this.isSiteRestricted); kparams.add("isCountryRestricted", this.isCountryRestricted); kparams.add("isSessionRestricted", this.isSessionRestricted); kparams.add("isIpAddressRestricted", this.isIpAddressRestricted); kparams.add("isUserAgentRestricted", this.isUserAgentRestricted); kparams.add("previewLength", this.previewLength); kparams.add("isScheduledNow", this.isScheduledNow); kparams.add("isAdmin", this.isAdmin); kparams.add("streamerType", this.streamerType); kparams.add("mediaProtocol", this.mediaProtocol); kparams.add("storageProfilesXML", this.storageProfilesXML); kparams.add("accessControlMessages", this.accessControlMessages); kparams.add("accessControlActions", this.accessControlActions); kparams.add("flavorAssets", this.flavorAssets); kparams.add("pluginData", this.pluginData); return kparams; } }
moskiteau/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/types/KalturaEntryContextDataResult.java
Java
agpl-3.0
7,054
We the People of the Free People's Republic of Loungistan, in Order to form a more perfect hackerspace, establish Justice, insure domestic Tranquility, provide for the common defense, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the Free People's Republic of Loungistan. // insert your Loungistan-Constitution paragraph here ## No property clause Nothing in the Free People's Republic of Loungistan shall be seen as someones property. ## Potato Wedges All potato wedges in the Free People's Republic of Loungistan belong to the people. ## Going for a walk The People of the Free People's Republic of Loungistan have the undeniable right to go for walks. ## Changes to this Constitution Changes to this Constitution shall be made by the people of the Free People's Republic of Loungistan by pushing their commits to the official repository on Github.
Loungistan/constitution
constitution.md
Markdown
agpl-3.0
953
{% extends theme('layouts/1-column.html') %} {% import 'macros/forms.html' as forms with context %} {% set section_class = 'form' %} {% block main_content %} <div class="container auth-container"> <form class="form-horizontal validate col-md-offset-2 col-md-8" action="{{ url_for('security.send_confirmation') }}" method="POST" name="send_confirmation_form"> <fieldset> <legend>{{ _('Resend confirmation instructions') }}</legend> {{ send_confirmation_form.hidden_tag() }} {{ forms.field(send_confirmation_form.email) }} <div class="form-group"> <div class="col-md-12"> <button type="submit" class="btn btn-primary btn-block">{{ _('Submit') }}</button> </div> </div> </fieldset> </form> </div> {% endblock %}
etalab/udata
udata/templates/security/send_confirmation.html
HTML
agpl-3.0
863
# Modelo asociativo (no tiene datos propios) para los valores (clase y # subclase) de Erosión en la ficha de Perfiles class Erosion < ApplicationRecord belongs_to :perfil, inverse_of: :erosion belongs_to :clase, inverse_of: :erosiones, class_name: 'ClaseDeErosion' belongs_to :subclase, inverse_of: :erosiones, class_name: 'SubclaseDeErosion' validates :perfil, presence: true validate :acumulacion_sin_clase delegate :publico, :usuario, :usuario_id, to: :perfil # TODO A un decorator # FIXME Se usa? En ese caso, pasar a join def to_s "#{clase.try(:to_str)} #{subclase}" end def self.ransackable_attributes(auth_object = nil) super(auth_object) - ['created_at', 'updated_at', 'perfil_id', 'id'] end private # Si se selecciona 'acumulación' como Subclase no debe haber Clase def acumulacion_sin_clase if subclase.try(:acumulacion?) && clase.present? errors.add :clase, :debe_estar_en_blanco end end end
INTA-Suelos/SiSinta
app/models/erosion.rb
Ruby
agpl-3.0
978
#pragma once #include <string> #include <vector> #include <memory> #include <map> #include "BanList.h" #include "entity/SMPlayer.h" #include "plugin/PluginLoadOrder.h" #include "minecraftpe/gamemode/GameType.h" #include "minecraftpe/entity/EntityUniqueID.h" class SMLevel; class SMOptions; class BanList; class SMList; class SMPlayer; class CommandMap; class Level; class PluginManager; class Minecraft; class LocalPlayer; class SMEntity; class SMLocalPlayer; class Plugin; class PluginCommand; class Player; class Entity; class Server { private: bool started; std::string serverDir; std::string pluginDir; SMLevel *level; Minecraft *server; SMOptions *options; BanList *banByName; BanList *banByIP; SMList *operators; SMList *whitelist; CommandMap *commandMap; PluginManager *pluginManager; SMLocalPlayer *localPlayer; std::string newVersion; int newVersionCode; std::vector<std::string> newChangelog; std::map<EntityUniqueID, SMEntity *> entityList; std::vector<SMPlayer *> players; public: Server(); ~Server(); void init(Minecraft *server, const std::string &path); void load(const std::string &path); void start(LocalPlayer *localPlayer, Level *level); void stop(); SMOptions *getOptions() const; void saveOptions(); void registerPlugin(Plugin *plugin); void loadPlugins(); void enablePlugins(PluginLoadOrder type); void disablePlugins(); const std::vector<SMPlayer *> &getOnlinePlayers() const; SMPlayer *getPlayer(const std::string &name) const; std::vector<SMPlayer *> matchPlayer(const std::string &partialName) const; SMPlayer *getPlayerExact(const std::string &name) const; SMLocalPlayer *getLocalPlayer() const; void addPlayer(SMPlayer *player); void removePlayer(SMPlayer *player); SMPlayer *getPlayer(Player *player) const; void removeEntity(Entity *entity); SMEntity *getEntity(Entity *entity); void kickPlayer(SMPlayer *player, const std::string &reason); void broadcastMessage(const std::string &message); void broadcastTranslation(const std::string &message, const std::vector<std::string> &params); void broadcastTip(const std::string &message); void broadcastPopup(const std::string &message, const std::string &subtitle = ""); int getMaxPlayers() const; int getPort() const; int getViewDistance() const; std::string getServerName() const; bool hasWhitelist() const; bool getPvP() const; void setWhitelist(bool value); void setPvP(bool value); bool dispatchCommand(SMPlayer *player, const std::string &commandLine); PluginCommand *getPluginCommand(const std::string &name); SMLevel *getLevel() const; BanList *getBanList(BanList::Type type) const; SMList *getWhitelistList() const; SMList *getOPList() const; void banIP(const std::string &address); void unbanIP(const std::string &address); void addWhitelist(const std::string &name); void removeWhitelist(const std::string &name); void reloadWhitelist(); void addOp(const std::string &name); void removeOp(const std::string &name); bool isWhitelisted(const std::string &name) const; bool isOp(const std::string &name) const; CommandMap *getCommandMap() const; PluginManager *getPluginManager() const; static std::string getGamemodeString(GameType type); static GameType getGamemodeFromString(const std::string &value); Minecraft *getServer() const; private: bool updateCheck(); void setVanillaCommands(); void loadPlugin(Plugin *plugin); };
Tom643/Servermanager
ServerManager/ServerManager.NativeActivity/servermanager/Server.h
C
agpl-3.0
3,424
# Copyright 2021 Alfredo de la Fuente - Avanzosc S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common from odoo.tests import tagged @tagged("post_install", "-at_install") class TestNameCodeYearId(common.SavepointCase): @classmethod def setUpClass(cls): super(TestNameCodeYearId, cls).setUpClass() cls.event_obj = cls.env['event.event'] cls.skill_type_lang = cls.env.ref('hr_skills.hr_skill_type_lang') cls.skill_spanish = cls.env.ref('hr_skills.hr_skill_spanish') cls.skill_filipino = cls.env.ref('hr_skills.hr_skill_filipino') cls.skill_type_lang.skill_language = True cls.skill_spanish.code = 'SP' cls.skill_filipino.code = 'FI' def test_event_name_code_year_id(self): vals = {'name': 'User for event lang level', 'date_begin': '2025-01-06 08:00:00', 'date_end': '2025-01-15 10:00:00', 'lang_id': self.skill_spanish.id} event = self.event_obj.create(vals) name = 'SP-{}-2025'.format(event.id) self.assertEqual(event.name, name) vals = {'date_begin': '2024-01-06 08:00:00', 'lang_id': self.skill_filipino.id} event.write(vals) name = 'FI-{}-2024'.format(event.id) self.assertEqual(event.name, name)
avanzosc/odoo-addons
event_name_code_year_id/tests/test_event_name_code_year_id.py
Python
agpl-3.0
1,353
DELETE FROM `weenie` WHERE `class_Id` = 23268; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (23268, 'guppyred', 18, '2019-02-10 00:00:00') /* Food */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (23268, 1, 4194304) /* ItemType - CraftCookingBase */ , (23268, 5, 10) /* EncumbranceVal */ , (23268, 11, 100) /* MaxStackSize */ , (23268, 12, 1) /* StackSize */ , (23268, 13, 10) /* StackUnitEncumbrance */ , (23268, 15, 0) /* StackUnitValue */ , (23268, 16, 8) /* ItemUseable - Contained */ , (23268, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */ , (23268, 151, 2) /* HookType - Wall */ , (23268, 8041, 101) /* PCAPRecordedPlacement - Resting */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (23268, 39, 0.6) /* DefaultScale */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (23268, 1, 'Red Guppy') /* Name */ , (23268, 20, 'Red Guppies') /* PluralName */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (23268, 1, 33558282) /* Setup */ , (23268, 3, 536870932) /* SoundTable */ , (23268, 6, 67114203) /* PaletteBase */ , (23268, 8, 100674194) /* Icon */ , (23268, 22, 872415275) /* PhysicsEffectTable */ , (23268, 8001, 270561297) /* PCAPRecordedWeenieHeader - PluralName, Usable, StackSize, MaxStackSize, Container, Burden, HookType */ , (23268, 8003, 32784) /* PCAPRecordedObjectDesc - Attackable, Food */ , (23268, 8005, 137345) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, STable, PeTable, AnimationFrame */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (23268, 8000, 3708843076) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`) VALUES (23268, 67114210, 0, 0); INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`) VALUES (23268, 0, 83894506, 83894506); INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`) VALUES (23268, 0, 16788968);
LtRipley36706/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Food/CraftCookingBase/23268 Red Guppy.sql
SQL
agpl-3.0
2,293
package lila.coach import org.joda.time.{DateTime,Days} import lila.user.User case class Coach( _id: Coach.Id, // user ID listed: Coach.Listed, available: Coach.Available, approved: Coach.Approved, profile: CoachProfile, picturePath: Option[Coach.PicturePath], nbReviews: Int, createdAt: DateTime, updatedAt: DateTime) { def id = _id def is(user: User) = id.value == user.id def hasPicture = picturePath.isDefined def isListed = listed.value && approved.value def daysOld = Days.daysBetween(createdAt, DateTime.now).getDays } object Coach { def make(user: User) = Coach( _id = Id(user.id), listed = Listed(false), available = Available(true), approved = Approved(true), profile = CoachProfile(), picturePath = None, nbReviews = 0, createdAt = DateTime.now, updatedAt = DateTime.now) case class WithUser(coach: Coach, user: User) case class Id(value: String) extends AnyVal with StringValue case class Listed(value: Boolean) extends AnyVal case class Available(value: Boolean) extends AnyVal case class Approved(value: Boolean) extends AnyVal case class PicturePath(value: String) extends AnyVal with StringValue }
clarkerubber/lila
modules/coach/src/main/Coach.scala
Scala
agpl-3.0
1,222
<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Logical OR. * * @package PHPUnit * @subpackage Framework_Constraint * @author Sebastian Bergmann <sebastian@phpunit.de> * @author Bernhard Schussek <bschussek@2bepublished.at> * @copyright Sebastian Bergmann <sebastian@phpunit.de> * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://www.phpunit.de/ * @since Class available since Release 3.0.0 */ class PHPUnit_Framework_Constraint_Or extends PHPUnit_Framework_Constraint { /** * @var PHPUnit_Framework_Constraint[] */ protected $constraints = array(); /** * @param PHPUnit_Framework_Constraint[] $constraints */ public function setConstraints( array $constraints ) { $this->constraints = array(); foreach ($constraints as $constraint) { if (!( $constraint instanceof PHPUnit_Framework_Constraint )) { $constraint = new PHPUnit_Framework_Constraint_IsEqual( $constraint ); } $this->constraints[] = $constraint; } } /** * Evaluates the constraint for parameter $other * * If $returnResult is set to false (the default), an exception is thrown * in case of a failure. null is returned otherwise. * * If $returnResult is true, the result of the evaluation is returned as * a boolean value instead: true in case of success, false in case of a * failure. * * @param mixed $other Value or object to evaluate. * @param string $description Additional information about the test * @param bool $returnResult Whether to return a result or throw an exception * * @return mixed * @throws PHPUnit_Framework_ExpectationFailedException */ public function evaluate( $other, $description = '', $returnResult = false ) { $success = false; $constraint = null; foreach ($this->constraints as $constraint) { if ($constraint->evaluate( $other, $description, true )) { $success = true; break; } } if ($returnResult) { return $success; } if (!$success) { $this->fail( $other, $description ); } } /** * Returns a string representation of the constraint. * * @return string */ public function toString() { $text = ''; foreach ($this->constraints as $key => $constraint) { if ($key > 0) { $text .= ' or '; } $text .= $constraint->toString(); } return $text; } /** * Counts the number of constraint elements. * * @return integer * @since Method available since Release 3.4.0 */ public function count() { $count = 0; foreach ($this->constraints as $constraint) { $count += count( $constraint ); } return $count; } }
KWZwickau/KREDA-Sphere
Library/MOC-V/Component/Database/Vendor/Doctrine2ORM/2.5-Master/vendor/phpunit/phpunit/src/Framework/Constraint/Or.php
PHP
agpl-3.0
3,291
var l_cache = SR.State.get('cache'); // language setting var l_lang = require('./language')('english'); SR.Callback.onStart(function () { }); var l_form = SR.State.get('FlexFormMap'); var l_accounts; SR.Callback.onStart(function () { l_form = SR.State.get('FlexFormMap'); l_accounts = SR.State.get('_accountMap'); // check if our form exists or create one if not LOG.warn('l_form size: ' + Object.keys(l_form).length); }); // get session value based on request object's cookie // TODO: make this SR function? var l_getSession = function (req) { var cookie = SR.REST.getCookie(req.headers.cookie); var session = SR.EventManager.getSession(cookie); return session; }; // pass in request object, returns session data if logined, otherwise returns null var l_checkLogin = function (req) { var session = l_getSession(req); if (session.hasOwnProperty('_user')) { var login = session._user; login.admin = (session._user.account === 'admin'); return login; } LOG.warn('user not yet logined...'); return {control: {groups: [], permissions: []}}; }; module.exports = function (app) { // CORS header app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.get('/api/menu', (req, res) => { const menu = [ { "path": "/", "redirect": "/dashboard", "name": "Home", "hidden": true, "children": [ { "path": "dashboard" } ] }, { "path": "/device", "redirect": "/device", "name": "Device Manege", "meta": { "title": "device", "icon": "device" }, "children": [ { "path": "create", "name": "create device", "type": "create", "meta": { "title": "create device", "icon": "device" } }, { "path": "list", "name": "list device", "type": "list", "meta": { "title": "list", "icon": "edit" } } ] }, { "path": "external-link", "children": [ { "path": "https://www.google.com/", "meta": { "title": "External Link", "icon": "link" } } ] } ]; res.send(menu); }); };
imonology/scalra
demo/lobby/router.js
JavaScript
agpl-3.0
2,280
// rhino.js // 2009-09-11 /* Copyright (c) 2002 Douglas Crockford (www.JSLint.com) Rhino Edition */ // This is the Rhino companion to fulljslint.js. /*global JSLINT */ /*jslint rhino: true, strict: false */ (function (a) { var e, i, input; if (!a[0]) { print("Usage: jslint.js file.js"); quit(1); } input = readFile(a[0]); if (!input) { print("jslint: Couldn't open file '" + a[0] + "'."); quit(1); } if (!JSLINT(input, {bitwise: true, eqeqeq: true, immed: true, newcap: true, nomen: true, onevar: false, plusplus: false, regexp: true, rhino: true, undef: false, white: false, 'continue': true})) { for (i = 0; i < JSLINT.errors.length; i += 1) { e = JSLINT.errors[i]; if (e) { print('Lint at line ' + e.line + ' character ' + e.character + ': ' + e.reason); print((e.evidence || ''). replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1")); print(''); } } quit(2); } else { print("jslint: No problems found in " + a[0]); quit(); } }(arguments));
niavok/syj
scripts/rhino.js
JavaScript
agpl-3.0
1,212
jQuery(document).ready(function() { jQuery('ul:checkboxList("reservation, reservation_has_user_list")').addFilter(); jQuery.fn.inval = function(options) { var defaults = { attribute: 'id', expr: '' }; var opts = jQuery.extend(defaults, options); var result = $(this).attr(opts.attribute); result = result.replace(opts.expr, '$1'); return parseInt(result); } jQuery.fn.selectionTable = function(options) { var defaults = { itemClass: 'tselectable', selectionClass: 'tselection', selectedClass: 'tselected', dayExpr: /book-(.*)-.*/, indexExpr: /book-.*-(.*)/ }; var opts = jQuery.extend(defaults, options); jQuery(this).each(function () { var table = jQuery(this); var items = table.find('td.' + opts.itemClass); var startItem = null; var downItem = null; var downDay = null; var downIndex = null; var duration = 0; var selectIndexItems = function(min, max, day) { items.each(function() { var item = jQuery(this); var itemDay = item.inval({ expr: opts.dayExpr }); var ok = false; if (itemDay == day) { var itemIndex = item.inval({ expr: opts.indexExpr }); if ((itemIndex >= min) && (itemIndex <= max)) { ok = true; } } if (ok) { item.addClass(opts.selectionClass); } else { item.removeClass(opts.selectionClass); } }); duration = (max - min + 1); }; var mouseDownHandler = function (e) { var buttonLeft = 0; if (jQuery.browser.msie) { buttonLeft = 1; } if (e.button == buttonLeft) { downItem = jQuery(this); startItem = downItem; downItem.addClass(opts.selectionClass); startItem.addClass(opts.selectedClass); downDay = downItem.inval({ expr: opts.dayExpr }); downIndex = downItem.inval({ expr: opts.indexExpr }); duration = 1; jQuery(document).mouseup(mouseUpHandler); jQuery(document).keypress(keyPressHandler); e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } return false; } }; var keyPressHandler = function(e) { if (e.keyCode = 27) { jQuery(document).unbind('mouseup', mouseUpHandler); jQuery(document).unbind('keypress', keyPressHandler); items.removeClass(opts.selectionClass); items.removeClass(opts.selectedClass); downItem = null; downDay = null; downIndex = null; duration = 0; } } var mouseEnterHandler = function (e) { if (downItem) { var target = jQuery(this); var targetIndex = target.inval({ expr: opts.indexExpr }); startItem.removeClass(opts.selectedClass); if (targetIndex < downIndex) { startItem = target; selectIndexItems(targetIndex, downIndex, downDay); } else { startItem = downItem; selectIndexItems(downIndex, targetIndex, downDay); } startItem.addClass(opts.selectedClass); } }; var mouseUpHandler = function () { jQuery(document).unbind('mouseup', mouseUpHandler); jQuery(document).unbind('keypress', keyPressHandler); items.removeClass(opts.selectionClass); downItem.removeClass(opts.selectedClass); if (duration < 1) { duration = 1; } window.location = startItem.find('a').attr('href') + '/duration/' + Math.floor(duration * 30); downItem = null; downDay = null; downIndex = null; duration = 0; return false; }; items.each(function () { // Hides the links inside jQuery(this).find('a').hide(); jQuery(this).append('<span class="autohide">' + jQuery(this).find('a').text() + '</span>'); if ('undefined' !== typeof this.onselectstart) { this.onselectstart = function() { return false; }; } jQuery(this).mousedown(mouseDownHandler); jQuery(this).mouseenter(mouseEnterHandler); jQuery(this).css('cursor', 'pointer'); }); }); }; jQuery('table.planning').selectionTable(); });
islog/tempos
web/js/reservation-helper.js
JavaScript
agpl-3.0
4,042
/* CrappyDBMS, a simple relational DBMS written in Java. Copyright (C) 2008 Facundo Manuel Quiroga <facundoq@gmail.com> This file is part of CrappyDBMS. CrappyDBMS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CrappyDBMS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CrappyDBMS. If not, see <http://www.gnu.org/licenses/>. */ package org.crappydbms.queries.predicates; import org.crappydbms.exceptions.InvalidAttributeNameException; import org.crappydbms.relations.tuples.Tuple; /** * @author Facundo Manuel Quiroga * Dec 12, 2008 * */ public class TruePredicate extends BasePredicate { @Override public boolean isTrueFor(Tuple tuple) throws InvalidAttributeNameException { return true; } public String toString(){ return "True"; } }
facundoq/toys
crappydbms/CrappyDBMS/src/org/crappydbms/queries/predicates/TruePredicate.java
Java
agpl-3.0
1,240
DELETE FROM `weenie` WHERE `class_Id` = 1705; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (1705, 'scrollitemenchantmentmasteryself', 34, '2019-02-10 00:00:00') /* Scroll */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (1705, 1, 8192) /* ItemType - Writable */ , (1705, 5, 30) /* EncumbranceVal */ , (1705, 16, 8) /* ItemUseable - Contained */ , (1705, 19, 1) /* Value */ , (1705, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */ , (1705, 8041, 101) /* PCAPRecordedPlacement - Resting */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (1705, 22, True ) /* Inscribable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (1705, 39, 1.5) /* DefaultScale */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (1705, 1, 'Scroll of Item Enchantment Mastery Self') /* Name */ , (1705, 14, 'Use this item to attempt to learn its spell.') /* Use */ , (1705, 16, 'Inscribed spell: Item Enchantment Mastery Self I Increases the caster''s Item Enchantment skill by 10 points.') /* LongDesc */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (1705, 1, 0x0200018A) /* Setup */ , (1705, 8, 0x0600336C) /* Icon */ , (1705, 22, 0x3400002B) /* PhysicsEffectTable */ , (1705, 28, 581) /* Spell - ItemEnchantmentMasterySelf1 */ , (1705, 8001, 6307864) /* PCAPRecordedWeenieHeader - Value, Usable, Container, Burden, Spell */ , (1705, 8003, 18) /* PCAPRecordedObjectDesc - Inscribable, Attackable */ , (1705, 8005, 135297) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, PeTable, AnimationFrame */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (1705, 8000, 0xD872E28F) /* PCAPRecordedObjectIID */;
ACEmulator/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Scroll/Writable/01705 Scroll of Item Enchantment Mastery Self.sql
SQL
agpl-3.0
1,966
/* * WEmu Scripts for WEmu MMORPG Server * Copyright (C) 2008 WEmu Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "StdAfx.h" #include "../../Base/EAS/EasyFunctions.h" class ProtectingtheShipment : public QuestScript { public: void OnQuestStart( Player * mTarget, QuestLogEntry * qLogEntry) { if( mTarget == NULL || mTarget->GetMapMgr() == NULL || mTarget->GetMapMgr()->GetInterface() == NULL ) return; float SSX = mTarget->GetPositionX(); float SSY = mTarget->GetPositionY(); float SSZ = mTarget->GetPositionZ(); Creature* creat = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 1379); if(creat == NULL) return; creat->m_escorter = mTarget; creat->GetAIInterface()->setMoveType(11); creat->GetAIInterface()->StopMovement(3000); creat->GetAIInterface()->SetAllowedToEnterCombat(false); creat->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Okay let's do!"); creat->SetUInt32Value(UNIT_NPC_FLAGS, 0); EAS::CreateCustomWaypointMap(creat); EAS::WaypointCreate(creat,-5753.780762f, -3433.290039f, 301.628387f, 4.834769f, 0, 256, 1417); EAS::WaypointCreate(creat,-5744.062500f, -3476.653564f, 302.269287f, 5.580896f, 0, 256, 1417); EAS::WaypointCreate(creat,-5674.703125f, -3543.583984f, 303.273682f, 4.775867f, 0, 256, 1417); EAS::WaypointCreate(creat,-5670.187500f, -3595.618164f, 311.888153f, 4.791576f, 0, 256, 1417); EAS::WaypointCreate(creat,-5664.515625f, -3687.601563f, 317.954590f, 4.131842f, 0, 256, 1417); EAS::WaypointCreate(creat,-5705.745117f, -3755.254150f, 321.452118f, 4.457779f, 0, 256, 1417); EAS::WaypointCreate(creat,-5711.766113f, -3778.145752f, 322.827942f, 4.473486f, 0, 256, 1417); } }; class Miran : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(Miran); Miran(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnReachWP(uint32 iWaypointId, bool bForwards) { if(iWaypointId == 7) { _unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Thanks, I'm outta here!"); _unit->Despawn(5000,1000); EAS::DeleteWaypoints(_unit); if(_unit->m_escorter == NULL) return; Player* plr = _unit->m_escorter; _unit->m_escorter = NULL; plr->GetQuestLogForEntry(309)->SendQuestComplete(); } } }; void SetupLochModan(ScriptMgr * mgr) { mgr->register_creature_script(1379, &Miran::Create); mgr->register_quest_script(309, CREATE_QUESTSCRIPT(ProtectingtheShipment)); }
Tulba/wowtbc
src/scripts/src/QuestScripts/Zone/Loch_Modan.cpp
C++
agpl-3.0
3,123
#!/usr/bin/env bash # # Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors # # This file is part of Alignak. # # Alignak is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Alignak is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Alignak. If not, see <http://www.gnu.org/licenses/>. echo 'pycodestyle ...' pycodestyle --max-line-length=100 --exclude='*.pyc, *.ini' --ignore='E402' alignak_backend/* if [ $? -ne 0 ]; then echo "pycodestyle not compliant" exit fi echo 'pylint ...' pylint --rcfile=.pylintrc alignak_backend/ if [ $? -ne 0 ]; then echo "pylint not compliant" exit fi echo 'pep157 ...' pep257 --select=D300 alignak_backend if [ $? -ne 0 ]; then echo "pep257 not compliant" exit fi echo 'tests ...' cd test pycodestyle --max-line-length=100 --exclude='*.pyc, *.cfg, *.log' --ignore='E402' test_*.py if [ $? -ne 0 ]; then echo "pycodestyle not compliant" exit fi pylint --rcfile=../.pylintrc test_*.py if [ $? -ne 0 ]; then echo "pylint not compliant" exit fi nosetests -xv --process-restartworker --processes=1 --process-timeout=300 test*.py cd ..
Alignak-monitoring-contrib/alignak-backend
code_test.sh
Shell
agpl-3.0
1,596
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage UnitTests * @copyright Copyright (c) 2006-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ require_once 'Zend/Gdata/Books.php'; require_once 'Zend/Http/Client.php'; /** * @package Zend_Gdata * @subpackage UnitTests */ class Zend_Gdata_BooksTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->gdata = new Zend_Gdata_Books(new Zend_Http_Client()); } public function testBooks() { $this->assertTrue(true); } }
ftrotter/btg
trunk/ZendGdata-1.7.1+Health/tests/Zend/Gdata/BooksTest.php
PHP
agpl-3.0
1,090
{% load standing %} {% load i18n %} {% comment %} The following variables are expected in the context: election election_data post_data.id post_data.label post_label_shorter candidacies candidacies_might_stand_again candidacies_not_standing_again candidates_locked show_confirm_result show_retract_result candidates_list_edits_allowed lock_form add_candidate_form Permission variables from the context processor: user_can_upload_documents user_can_lock user_can_record_results user Those required by included partials: candidates/_person_in_list.html c (a candidacy from candidacies, candidacies_might_stand_again, etc.) candidates/_source_confirmation.html c standing (either 'standing' or 'not-standing') post_data.id official_documents/_post.html official_documents post_data.label post_data.id {% endcomment %} {% if election_data.show_official_documents %} {% include 'official_documents/_post.html' %} {% endif %} <div id="candidates-for-post-{{ post_data.id }}" class="candidates-for-post"> {% if user_can_lock %} <form method="post" action="{% url 'constituency-lock' election=election %}"> {% csrf_token %} {% for field in lock_form %}{{ field }}{% endfor %} <input type="submit" class="button small" value="{% if candidates_locked %}{% trans "Unlock candidate list" %}{% else %}{% trans "Lock candidate list" %}{% endif %}"> {% if candidates_locked %} {% trans "(This list of candidates is currently <strong>locked</strong>.)" %} {% else %} {% trans "(This list of candidates is currently <strong>unlocked</strong>.)" %} {% endif %} </form> {% else %} {% if candidates_locked %} <p>{% blocktrans trimmed %}This list of candidates is now <strong>locked</strong>; you can still update contact details of candidates, but can't change the people standing in this constituency.{% endblocktrans %}</p> {% endif %} {% endif %} {% if user_can_record_results and show_retract_result %} <form action="{% url 'retract-winner' election=election post_id=post_id %}" method="post"> {% csrf_token %} <input type="submit" class="button alert" value="{% trans "Unset the current winners, if incorrect" %}"> </form> {% endif %} <div class="candidates__known"> {# Use the post label here, since multiple posts may be used on a page #} {% url 'constituency' election=election post_id=post_data.id ignored_slug=post_data.label|slugify as post_url %} {% url 'constituencies' election=election_data.slug as election_posts_url %} <h3>{% blocktrans trimmed with post_label=post_data.label election_name=election_data.name %} Known candidates for <a href="{{ post_url }}">{{ post_label }}</a> in the <a href="{{ election_posts_url }}"> {{ election_name }}</a>{% endblocktrans %} </h3> {% with party_lists_in_use=candidacies.party_lists_in_use parties_and_people=candidacies.parties_and_people %} {% if parties_and_people and candidate_list_edits_allowed %} <p><a class="show-new-candidate-form button">{% trans "Add a new candidate" %}</a></p> {% endif %} {% for party, people in parties_and_people %} <div class="party-group {% if party_lists_in_use %}party-list{% else %}no-party-list{% endif %}"> {% if party_lists_in_use %} <h4 class="party-list-header">{{ party.name }}</h4> <p class="party-list-description"> {% if party.truncated %} {% trans "Showing the top candidates." %} <a href="{% url 'party-for-post' election=election post_id=post_data.id organization_id=party.id %}">{% blocktrans with count=party.total_count %}See all {{ count }} members on the party list{% endblocktrans %} &rarr;</a> {% else %} <a href="{% url 'party-for-post' election=election post_id=post_data.id organization_id=party.id %}">{% blocktrans with count=party.total_count %}See just this party list{% endblocktrans %} &rarr;</a> {% endif %} {% endif %} {% for position_in_list, c, candidate_elected in people %} {% if forloop.first %} <ul class="candidate-list"> {% endif %} <li class="candidates-list__person{% if user_can_record_results %} hover-highlighting{% endif %}{% if candidate_elected %} candidates-list__person__winner{% endif %}"> {% if candidate_elected %} <h4 class="candidates-list__person__elected-text">{% trans "Winner" %}</h4> {% endif %} {% include 'candidates/_person_in_list.html' with election=election %} {% if user.is_authenticated %} <p> {% if candidate_list_edits_allowed %} <a class="button tiny js-toggle-source-confirmation not-standing">{% trans "Not actually standing?" %}</a> {% endif %} <a href="{% url 'person-update' person_id=c.id %}" class="button tiny secondary">{% trans "Edit" %}</a> </p> {% if candidate_list_edits_allowed %} {% include 'candidates/_source_confirmation.html' with standing='not-standing' action='candidacy-delete' %} {% endif %} {% endif %} {% if DATE_TODAY >= election_data.election_date %} {% if user_can_record_results and show_confirm_result and not candidate_elected %} <form class="winner-confirm" action="{% url 'record-winner' election=election post_id=post_data.id %}" method="post"> {% csrf_token %} <input type="hidden" name="person_id" value="{{ c.id }}"> <input type="hidden" name="source" value="{% trans "[Quick update from the constituency page]" %}"> <input type="submit" class="button" value="{% trans "This candidate was elected!" %}"> </form> {% endif %} {% endif %} </li> {% if forloop.last %} </ul> {% endif %} {% endfor %} {# end of 'for position_in_list, c, candidate_elected in people' #} </div> {% empty %} <div class="no-candidates row"> <p class="medium-8 columns">{% blocktrans trimmed with post_label=post_data.label election_name=election_data.name %} <strong>Oh no!</strong> We don’t know of any candidates in {{ post_label }} for the {{ election_name }} yet.{% endblocktrans %}</p> {% if candidate_list_edits_allowed %} <p class="medium-4 columns"><a class="show-new-candidate-form button">{% trans "Add a new candidate" %}</a></p> {% else %} <p class="medium-4 columns"><a href="{% url 'account_login' %}{% if redirect_after_login %}?next={{ redirect_after_login }}{% endif %}" class="show-new-candidate-form button">{% trans "Sign in to add a new candidate" %}</a></p> {% endif %} </div> {% endfor %} {# end of 'for party, people in parties_and_people' #} {% if parties_and_people and candidate_list_edits_allowed %} <p><a class="show-new-candidate-form button">{% trans "Add a new candidate" %}</a></p> {% endif %} {% endwith %} </div> {% if candidate_list_edits_allowed %} <div class="candidates__new" {% if add_candidate_form.errors %}style="display: block"{% endif %}> <h4>{% trans "Add a new candidate" %}</h4> <form id="new-candidate-form" name="new-candidate-form" action="{% url 'person-create' election=election %}" method="post"> {% with form=add_candidate_form %} {% include 'candidates/_person_form.html' %} {% endwith %} </form> </div> {% endif %} {% if not candidates_locked %} {% if candidacies_might_stand_again.parties_and_people %} <div class="candidates__previous"> {% if user.is_authenticated %} <h3>{% trans "Is a candidate from an earlier election standing again?" %}</h3> {% else %} <h3>{% trans "We don't know if these candidates from earlier elections are standing again" %}</h3> {% endif %} {% with party_lists_in_use=candidacies_might_stand_again.party_lists_in_use parties_and_people=candidacies_might_stand_again.parties_and_people %} {% for party, people in parties_and_people %} <div class="party-group {% if party_lists_in_use %}party-list{% else %}no-party-list{% endif %}"> {% if party_lists_in_use %} <h4>{{ party.name }}</h4> {% endif %} <ul class="candidate-list"> {% for position_in_list, c, candidate_elected in people %} <li class="candidates-list__person"> {% include 'candidates/_person_in_list.html' %} {% if user.is_authenticated %} <p> {% if candidate_list_edits_allowed %} <a class="button tiny js-toggle-source-confirmation standing">{% trans "Standing again" %}</a> <a class="button tiny js-toggle-source-confirmation not-standing">{% trans "Not standing again" %}</a> {% endif %} <a href="{% url 'person-update' person_id=c.id %}" class="button tiny secondary">{% trans "Edit" %}</a> </p> {% if candidate_list_edits_allowed %} {% include 'candidates/_source_confirmation.html' with standing='standing' action='candidacy-create' %} {% include 'candidates/_source_confirmation.html' with standing='not-standing' action='candidacy-delete' %} {% endif %} {% endif %} </li> {% endfor %} {# end of 'for position_in_list, c, candidate_elected in people' #} </ul> </div> {% endfor %} {# end of 'party, people in parties_and_people' #} {% endwith %} </div> {% endif %} {% if candidacies_not_standing_again.parties_and_people %} <div class="candidates__not-standing"> <h3>{% trans "These candidates from earlier elections are known not to be standing again" %}</h3> {% with party_lists_in_use=candidacies_not_standing_again.party_lists_in_use parties_and_people=candidacies_not_standing_again.parties_and_people %} {% for party, people in parties_and_people %} <div class="party-group {% if party_lists_in_use %}party-list{% else %}no-party-list{% endif %}"> {% if party_lists_in_use %} <h4>{{ party.name }}</h4> {% endif %} <ul class="candidate-list"> {% for position_in_list, c, candidate_elected in people %} <li class="candidates-list__person"> {% include 'candidates/_person_in_list.html' %} {% if user.is_authenticated %} <p> {% if candidate_list_edits_allowed %} <a class="button tiny js-toggle-source-confirmation standing">{% trans "Actually, they are standing!" %}</a> {% endif %} <a href="{% url 'person-update' person_id=c.id %}" class="button tiny secondary">{% trans "Edit" %}</a> </p> {% if candidate_list_edits_allowed %} {% include 'candidates/_source_confirmation.html' with standing='standing' action='candidacy-create' %} {% endif %} {% endif %} </li> {% endfor %} {# end of 'for position_in_list, c, candidate_elected in people' #} </ul> </div> {% endfor %} {# end of 'for party, people in parties_and_people' #} {% endwith %} </div> {% endif %} {% endif %} {# end of 'if not candidates_locked' #} </div>
neavouli/yournextrepresentative
candidates/templates/candidates/_candidates_for_post.html
HTML
agpl-3.0
12,259
if (typeof Mapmaker === 'undefined') Mapmaker = {}; Mapmaker.TopicMappingView = (function($, famous) { var Engine = famous.core.Engine; var Surface = famous.core.Surface; var ImageSurface = famous.surfaces.ImageSurface; var Modifier = famous.core.Modifier; var StateModifier = famous.modifiers.StateModifier; var Transform = famous.core.Transform; var Particle = famous.physics.bodies.Particle; var Repulsion = famous.physics.forces.Repulsion; var Handlers = { mousedown: function(event) { this.mouseIsDown = true; this.hasMoved = false; this.topicParticle.sleep(); $(document).trigger(Mapmaker.TopicMappingView.events.mousedown); }, mouseup: function(event) { this.topicParticle.wake(); Private.cancelClick.call(this); $(document).trigger(Mapmaker.TopicMappingView.events.mouseup, [this]); var storedTime = this.lastClick; var now = Date.now(); this.lastClick = now; if (now - storedTime < this.view.config.DOUBLE_CLICK_TOLERANCE) { $(document).trigger(Mapmaker.TopicMappingView.events.doubleClick, [this]); } }, mousemove: function(event) { var m = this.mapping; var newX, newY; if (this.mouseIsDown) { if (!this.hasMoved) this.hasMoved = true; newX = this.topicParticle.getTransform()[12] + event.movementX; newY = this.topicParticle.getTransform()[13] + event.movementY; // modify the mapping, the saved state m.set("xloc", newX); m.set("yloc", newY); //this.anchorParticle.setPosition([newX, newY, 0]); this.topicParticle.setPosition([newX, newY, 0]); //this.anchorParticle.setVelocity([0, 0, 0]); this.topicParticle.setVelocity([0, 0, 0]); // when changing this topics location, trigger event with location data // so that mapView can move synapses attached to it } } }; var Private = { cancelClick: function() { this.mouseIsDown = false; if (this.hasMoved) { // save the mapping } $(document).trigger(Mapmaker.TopicMappingView.events.dragEnd); }, createImageSurface: function() { var self = this; var topic = this.mapping.getTopic(); var updateMetacodeImage = function() { var metacode = self.view.metacodes.get(topic.get("metacode_id")); var metacodeUrl = metacode.get("icon"); self.imageSurface.setContent(metacodeUrl); }; // add listener topic.on("change:metacode_id", updateMetacodeImage); this.imageSurface = new ImageSurface({ classes: ["noselect"], size: [50, 50] }); updateMetacodeImage(); this.modNode.add(this.imageSurface); // attach events var mousedownHandler = function(event) { event.preventDefault(); Handlers.mousedown.call(self, event); }; this.imageSurface.on("mousedown", mousedownHandler); var mouseupHandler = function(event) { Handlers.mouseup.call(self, event); }; this.imageSurface.on("mouseup", mouseupHandler); var mousemoveHandler = function(event) { Handlers.mousemove.call(self, event); }; //this.imageSurface.on("mousemove", mousemoveHandler); }, createNameSurface: function() { var self = this; var topic = this.mapping.getTopic(); var updateName = function() { self.nameSurface.setContent(topic.get("name")); }; // add listener topic.on("change:name", updateName); this.nameSurface = new Surface({ content: topic.get("name"), classes: ["noselect"], size: [true, true], properties: { marginTop: "35px", borderRadius: "5px", backgroundColor: "#FFF" } }); this.modNode.add(this.nameSurface); // attach events var mousedownHandler = function(event) { Handlers.mousedown.call(self, event); }; this.nameSurface.on("mousedown", mousedownHandler); var mouseupHandler = function(event) { Handlers.mouseup.call(self, event); }; this.nameSurface.on("mouseup", mouseupHandler); var mousemoveHandler = function(event) { Handlers.mousemove.call(self, event); }; //this.nameSurface.on("mousemove", mousemoveHandler); }, attachPhysics: function () { var self = this; var m = this.mapping; var pos = [m.get("xloc"), m.get("yloc"), 0]; // this one is going to stay rooted at the mapping this.anchorParticle = new Particle({ position: pos }); this.view.pe.addBody(this.anchorParticle); // this one is going to dance and move around this.topicParticle = new Particle({ position: pos }); this.view.pe.addBody(this.topicParticle); //var gravity = new Repulsion({ // strength: -3 //}); //this.view.pe.attach(gravity, this.topicParticle, this.anchorParticle); // create a new force and add it to the physics engine //var repel = new Repulsion({ strength: 0.5, radii: {max: 1, min: 0}}); // for 'attach' variables to pass are (Force, Targets, Source) //this.view.pe.attach(repel, undefined, this.topicParticle); this.mod = new Modifier({ transform: function () { return self.topicParticle.getTransform(); } }); this.modNode = this.view.originModNode.add(this.mod); } }; var topicView = function(view, mapping) { var self = this; Mapmaker.MappingView.call(this, view, mapping); this.topic = mapping.getTopic(); Private.attachPhysics.call(this); Private.createImageSurface.call(this); Private.createNameSurface.call(this); var cancelHandler = function(event) { Private.cancelClick.call(self, event); }; Engine.on("mouseup", cancelHandler); var mousemoveHandler = function(event) { Handlers.mousemove.call(self, event); }; Engine.on("mousemove", mousemoveHandler); this.mouseIsDown = false; this.lastClick = null; this.hasMoved = false; }; topicView.prototype = new Mapmaker.MappingView(); topicView.prototype.constructor = topicView; return topicView; }(jQuery, famous)); /** * @class * @static */ Mapmaker.TopicMappingView.events = { mousedown: "Mapmaker:TopicMappingView:mousedown", mouseup: "Mapmaker:TopicMappingView:mouseup", doubleClick: "Mapmaker:TopicMappingView:doubleClick", dragEnd: "Mapmaker:TopicMappingView:dragEnd", };
metamaps/mapmaker
lib/views/topicMappingView.js
JavaScript
agpl-3.0
6,105
require 'digest/sha2' class User < ActiveRecord::Base has_many :club_members has_many :clubs, :through => :club_members has_many :competitors has_many :teams has_many :bills belongs_to :country validates_presence_of :country, :message => I18n.t('activerecord.errors.messages.mustbeselected'), :unless => "country_id.blank?" belongs_to :nation, :class_name => "Country" validates_presence_of :nation, :message => I18n.t('activerecord.errors.messages.mustbeselected') validates :username, :presence => true, :uniqueness => true validates :email, :presence => true, :uniqueness => true validates_format_of :email, :with => /(\S+)@(\S+)/ validates :password, :confirmation => true validates_length_of :password, :minimum => 4 validates :sex, :presence => true, :inclusion => {:in => %w( M F ), :message => I18n.t('activerecord.errors.messages.invalid'), :allow_nil => true} validates :first_name, :presence => true validates :last_name, :presence => true validates :birthdate_y, :presence => true, :numericality => {:only_integer => true, :allow_nil => true}, :inclusion => {:in => 1900..Date.today.year, :message => I18n.t('activerecord.errors.messages.between', :from => 1900, :to => Date.today.year.to_s), :allow_nil => true} validates :sicard_number, :numericality => {:only_integer => true, :allow_nil => true}, :inclusion => {:in => 1..16777216, :message => I18n.t('activerecord.errors.messages.between', :from => 1, :to => 16777216), :allow_nil => true} attr_accessor :password_confirmation attr_accessor :old_password attr_reader :password validate :password_must_be_present validate :check_old_password validate :password_change_only_if_old_password_provided # 'password' is a virtual attribute def password=(password) @password = password if password.present? generate_salt self.hashed_password = self.class.encrypt_password(password, salt) end end # Provides a reader for the full name # Pass true to it to get an alphabetically sortable name def full_name(alpha = false) if alpha then last_name+', '+first_name else first_name+' '+last_name end end def has_full_address (first_name and !first_name.empty?) and (last_name and !last_name.empty?) and (address_line_1 and !address_line_1.empty?) and (city and !city.empty?) and (zipcode and !zipcode.empty?) and country end def User.authenticate(identifier, password) user = nil if not user = find_by_username(identifier) user = find_by_email(identifier) end if user and user.hashed_password == encrypt_password(password, user.salt) user else nil end end def User.get_logged_in session if session[:user_id] User.find_by_id(session[:user_id]) end end private def password_must_be_present errors.add(:password, I18n.t('activerecord.errors.messages.blank') ) unless hashed_password.present? end def password_change_only_if_old_password_provided if !new_record? and hashed_password.present? and !old_password errors.add(:old_password, I18n.t('activerecord.errors.messages.blank') ) end end def check_old_password if old_password and !User.authenticate(username, old_password) errors.add(:old_password, I18n.t('activerecord.errors.messages.invalid') ) end end def generate_salt self.salt = self.object_id.to_s + rand.to_s end def User.encrypt_password(password, salt) Digest::SHA2.hexdigest(password + "wibble" + salt) end end
snellen/o-events.net
app/models/user.rb
Ruby
agpl-3.0
3,621
try: import serial # Python2 except ImportError: from serial3 import * # Python3 from nupic.frameworks.opf.modelfactory import ModelFactory import os,sys ser = serial.Serial('/dev/ttyACM0', 9600) def get_online(number_of_records=20):# 0 means forever model = ModelFactory.loadFromCheckpoint(os.getcwd() + "/model_save") count=0 ser.flushInput() while (count < number_of_records) or (number_of_records == 0): count = count + 1 text = ser.readline() if (len(text.split(",")) == 4): result = model.run({ "s1": float(text.split(",")[0]), "s2": float(text.split(",")[1]), "s3": float(text.split(",")[2]), "s4": float(text.split(",")[3]) }) prediction = int(result.inferences['multiStepBestPredictions'][4]) sys.stdout.write("\r"+ str(prediction)) sys.stdout.write("\t"+ text) ser.write(str(prediction)+ '\n')
lmaag182/nupic_physical
online.py
Python
agpl-3.0
994
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package provider_test import ( "github.com/juju/errors" "github.com/juju/names" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "github.com/juju/juju/storage" "github.com/juju/juju/storage/provider" "github.com/juju/juju/testing" ) var _ = gc.Suite(&tmpfsSuite{}) type tmpfsSuite struct { testing.BaseSuite storageDir string commands *mockRunCommand } func (s *tmpfsSuite) SetUpTest(c *gc.C) { s.BaseSuite.SetUpTest(c) s.storageDir = c.MkDir() } func (s *tmpfsSuite) TearDownTest(c *gc.C) { s.commands.assertDrained() s.BaseSuite.TearDownTest(c) } func (s *tmpfsSuite) tmpfsProvider(c *gc.C) storage.Provider { s.commands = &mockRunCommand{c: c} return provider.TmpfsProvider(s.commands.run) } func (s *tmpfsSuite) TestFilesystemSource(c *gc.C) { p := s.tmpfsProvider(c) cfg, err := storage.NewConfig("name", provider.TmpfsProviderType, map[string]interface{}{}) c.Assert(err, jc.ErrorIsNil) _, err = p.FilesystemSource(nil, cfg) c.Assert(err, gc.ErrorMatches, "storage directory not specified") cfg, err = storage.NewConfig("name", provider.TmpfsProviderType, map[string]interface{}{ "storage-dir": c.MkDir(), }) c.Assert(err, jc.ErrorIsNil) _, err = p.FilesystemSource(nil, cfg) c.Assert(err, jc.ErrorIsNil) } func (s *tmpfsSuite) TestValidateConfig(c *gc.C) { p := s.tmpfsProvider(c) cfg, err := storage.NewConfig("name", provider.TmpfsProviderType, map[string]interface{}{}) c.Assert(err, jc.ErrorIsNil) err = p.ValidateConfig(cfg) // The tmpfs provider does not have any user // configuration, so an empty map will pass. c.Assert(err, jc.ErrorIsNil) } func (s *tmpfsSuite) TestSupports(c *gc.C) { p := s.tmpfsProvider(c) c.Assert(p.Supports(storage.StorageKindBlock), jc.IsFalse) c.Assert(p.Supports(storage.StorageKindFilesystem), jc.IsTrue) } func (s *tmpfsSuite) tmpfsFilesystemSource(c *gc.C) storage.FilesystemSource { s.commands = &mockRunCommand{c: c} return provider.TmpfsFilesystemSource( s.storageDir, s.commands.run, ) } func (s *tmpfsSuite) TestCreateFilesystems(c *gc.C) { source := s.tmpfsFilesystemSource(c) cmd := s.commands.expect("mount", "-t", "tmpfs", "none", "/mnt/bar", "-o", "size=2097152") cmd.respond("", nil) cmd = s.commands.expect("df", "--output=size", "/mnt/bar") cmd.respond("1K-blocks\n2048", nil) filesystems, filesystemAttachments, err := source.CreateFilesystems([]storage.FilesystemParams{{ Tag: names.NewFilesystemTag("6"), Size: 2, Attachment: &storage.FilesystemAttachmentParams{ AttachmentParams: storage.AttachmentParams{ Machine: names.NewMachineTag("1"), InstanceId: "instance-id", }, Path: "/mnt/bar", }, }}) c.Assert(err, jc.ErrorIsNil) mountedDirs := provider.MountedDirs(source) c.Assert(mountedDirs.Size(), gc.Equals, 1) c.Assert(mountedDirs.Contains("/mnt/bar"), jc.IsTrue) c.Assert(filesystems, gc.HasLen, 1) c.Assert(filesystemAttachments, gc.HasLen, 1) c.Assert(filesystems[0], gc.Equals, storage.Filesystem{ Tag: names.NewFilesystemTag("6"), Size: 2, }) c.Assert(filesystemAttachments[0], gc.Equals, storage.FilesystemAttachment{ Path: "/mnt/bar", Filesystem: names.NewFilesystemTag("6"), Machine: names.NewMachineTag("1"), }) } func (s *tmpfsSuite) TestCreateFilesystemsIsUse(c *gc.C) { source := s.tmpfsFilesystemSource(c) _, _, err := source.CreateFilesystems([]storage.FilesystemParams{ { Tag: names.NewFilesystemTag("6"), Size: 1, Attachment: &storage.FilesystemAttachmentParams{ AttachmentParams: storage.AttachmentParams{ Machine: names.NewMachineTag("1"), InstanceId: "instance-id1", }, Path: "/mnt/notempty", }, }, { Tag: names.NewFilesystemTag("6"), Size: 2, Attachment: &storage.FilesystemAttachmentParams{ AttachmentParams: storage.AttachmentParams{ Machine: names.NewMachineTag("2"), InstanceId: "instance-id2", }, Path: "/mnt/notempty", }, }}) c.Assert(err, gc.ErrorMatches, ".* path must be empty") } func (s *tmpfsSuite) TestCreateFilesystemsPathNotDir(c *gc.C) { source := s.tmpfsFilesystemSource(c) _, _, err := source.CreateFilesystems([]storage.FilesystemParams{{ Tag: names.NewFilesystemTag("6"), Size: 2, Attachment: &storage.FilesystemAttachmentParams{ AttachmentParams: storage.AttachmentParams{ Machine: names.NewMachineTag("1"), InstanceId: "instance-id", }, Path: "file", }, }}) c.Assert(err, gc.ErrorMatches, `.* path "file" must be a directory`) } func (s *tmpfsSuite) TestCreateFilesystemsNotEnoughSpace(c *gc.C) { source := s.tmpfsFilesystemSource(c) cmd := s.commands.expect("mount", "-t", "tmpfs", "none", "/var/lib/juju/storage/fs/foo", "-o", "size=4194304") cmd.respond("", nil) cmd = s.commands.expect("df", "--output=size", "/var/lib/juju/storage/fs/foo") cmd.respond("1K-blocks\n2048", nil) _, _, err := source.CreateFilesystems([]storage.FilesystemParams{{ Tag: names.NewFilesystemTag("6"), Size: 4, Attachment: &storage.FilesystemAttachmentParams{ AttachmentParams: storage.AttachmentParams{ Machine: names.NewMachineTag("1"), InstanceId: "instance-id", }, Path: "/var/lib/juju/storage/fs/foo", }, }}) c.Assert(err, gc.ErrorMatches, ".* filesystem is not big enough \\(2M < 4M\\)") } func (s *tmpfsSuite) TestCreateFilesystemsInvalidPath(c *gc.C) { source := s.tmpfsFilesystemSource(c) cmd := s.commands.expect("mount", "-t", "tmpfs", "none", "/mnt/bad-dir", "-o", "size=2097152") cmd.respond("", nil) cmd = s.commands.expect("df", "--output=size", "/mnt/bad-dir") cmd.respond("", errors.New("error creating directory")) _, _, err := source.CreateFilesystems([]storage.FilesystemParams{{ Tag: names.NewFilesystemTag("6"), Size: 2, Attachment: &storage.FilesystemAttachmentParams{ AttachmentParams: storage.AttachmentParams{ Machine: names.NewMachineTag("1"), InstanceId: "instance-id", }, Path: "/mnt/bad-dir", }, }}) c.Assert(err, gc.ErrorMatches, ".* error creating directory") } func (s *tmpfsSuite) TestCreateFilesystemsNoAttachment(c *gc.C) { source := s.tmpfsFilesystemSource(c) _, _, err := source.CreateFilesystems([]storage.FilesystemParams{{ Tag: names.NewFilesystemTag("6"), Size: 2, }}) c.Assert(err, gc.ErrorMatches, ".* creating filesystem without machine attachment not supported") } func (s *tmpfsSuite) TestCreateFilesystemsNoPathSpecified(c *gc.C) { source := s.tmpfsFilesystemSource(c) _, _, err := source.CreateFilesystems([]storage.FilesystemParams{{ Tag: names.NewFilesystemTag("6"), Size: 2, Attachment: &storage.FilesystemAttachmentParams{ AttachmentParams: storage.AttachmentParams{ Machine: names.NewMachineTag("1"), InstanceId: "instance-id", }, }, }}) c.Assert(err, gc.ErrorMatches, ".* cannot create a filesystem mount without specifying a path") }
cmars/juju
storage/provider/tmpfs_test.go
GO
agpl-3.0
6,948
<?php /** * TActiveRecordManager class file. * * @author Wei Zhuo <weizhuo[at]gmail[dot]com> * @link http://www.pradosoft.com/ * @copyright Copyright &copy; 2005-2013 PradoSoft * @license http://www.pradosoft.com/license/ * @version $Id: TActiveRecordManager.php 3245 2013-01-07 20:23:32Z ctrlaltca $ * @package System.Data.ActiveRecord */ Prado::using('System.Data.TDbConnection'); Prado::using('System.Data.ActiveRecord.TActiveRecord'); Prado::using('System.Data.ActiveRecord.Exceptions.TActiveRecordException'); Prado::using('System.Data.ActiveRecord.TActiveRecordGateway'); /** * TActiveRecordManager provides the default DB connection, * default active record gateway, and table meta data inspector. * * The default connection can be set as follows: * <code> * TActiveRecordManager::getInstance()->setDbConnection($conn); * </code> * All new active record created after setting the * {@link DbConnection setDbConnection()} will use that connection unless * the custom ActiveRecord class overrides the ActiveRecord::getDbConnection(). * * Set the {@link setCache Cache} property to an ICache object to allow * the active record gateway to cache the table meta data information. * * @author Wei Zhuo <weizho[at]gmail[dot]com> * @version $Id: TActiveRecordManager.php 3245 2013-01-07 20:23:32Z ctrlaltca $ * @package System.Data.ActiveRecord * @since 3.1 */ class TActiveRecordManager extends TComponent { const DEFAULT_GATEWAY_CLASS = 'System.Data.ActiveRecord.TActiveRecordGateway'; /** * Defaults to {@link TActiveRecordManager::DEFAULT_GATEWAY_CLASS DEFAULT_GATEWAY_CLASS} * @var string */ private $_gatewayClass = self::DEFAULT_GATEWAY_CLASS; private $_gateway; private $_meta=array(); private $_connection; private $_cache; /** * Defaults to '{@link TActiveRecordInvalidFinderResult::Null Null}' * * @var TActiveRecordInvalidFinderResult * @since 3.1.5 */ private $_invalidFinderResult = TActiveRecordInvalidFinderResult::Null; /** * @return ICache application cache. */ public function getCache() { return $this->_cache; } /** * @param ICache application cache */ public function setCache($value) { $this->_cache=$value; } /** * @param TDbConnection default database connection */ public function setDbConnection($conn) { $this->_connection=$conn; } /** * @return TDbConnection default database connection */ public function getDbConnection() { return $this->_connection; } /** * @return TActiveRecordManager static instance of record manager. */ public static function getInstance($self=null) { static $instance; if($self!==null) $instance=$self; else if($instance===null) $instance = new self; return $instance; } /** * @return TActiveRecordGateway record gateway. */ public function getRecordGateway() { if($this->_gateway === null) { $this->_gateway = $this->createRecordGateway(); } return $this->_gateway; } /** * @return TActiveRecordGateway default record gateway. */ protected function createRecordGateway() { return Prado::createComponent($this->getGatewayClass(), $this); } /** * Set implementation class of ActiveRecordGateway * @param string $value */ public function setGatewayClass($value) { $this->_gateway = null; $this->_gatewayClass = (string)$value; } /** * @return string the implementation class of ActiveRecordGateway. Defaults to {@link TActiveRecordManager::DEFAULT_GATEWAY_CLASS DEFAULT_GATEWAY_CLASS} */ public function getGatewayClass() { return $this->_gatewayClass; } /** * @return TActiveRecordInvalidFinderResult Defaults to '{@link TActiveRecordInvalidFinderResult::Null Null}'. * @since 3.1.5 * @see setInvalidFinderResult */ public function getInvalidFinderResult() { return $this->_invalidFinderResult; } /** * Define the way an active record finder react if an invalid magic-finder invoked * @param TActiveRecordInvalidFinderResult * @since 3.1.5 * @see getInvalidFinderResult */ public function setInvalidFinderResult($value) { $this->_invalidFinderResult = TPropertyValue::ensureEnum($value, 'TActiveRecordInvalidFinderResult'); } }
rkorzeniewski/bacula
gui/baculum/framework/Data/ActiveRecord/TActiveRecordManager.php
PHP
agpl-3.0
4,194
/* Generated by Snowball 2.0.0 - https://snowballstem.org/ */ #include <xapian-internal.h> #pragma hdrstop #include "kraaij_pohlmann.sbl.h" static const symbol s_pool[] = { #define s_0_0 0 'n', 'd', 'e', #define s_0_1 3 'e', 'n', #define s_0_2 (s_0_3 + 1) #define s_0_3 5 '\'', 's', #define s_0_4 (s_0_5 + 1) #define s_0_5 7 'i', 'e', 's', #define s_0_6 10 'a', 'u', 's', #define s_1_0 13 'd', 'e', #define s_1_1 15 'g', 'e', #define s_1_2 17 'i', 's', 'c', 'h', 'e', #define s_1_3 22 'j', 'e', #define s_1_4 24 'l', 'i', 'j', 'k', 'e', #define s_1_5 29 'l', 'e', #define s_1_6 31 'e', 'n', 'e', #define s_1_7 34 'r', 'e', #define s_1_8 36 's', 'e', #define s_1_9 38 't', 'e', #define s_1_10 40 'i', 'e', 'v', 'e', #define s_2_0 44 'h', 'e', 'i', 'd', #define s_2_1 48 'f', 'i', 'e', #define s_2_2 51 'g', 'i', 'e', #define s_2_3 54 'a', 't', 'i', 'e', #define s_2_4 58 'i', 's', 'm', 'e', #define s_2_5 62 'i', 'n', 'g', #define s_2_6 65 'a', 'r', 'i', 'j', #define s_2_7 69 'e', 'r', 'i', 'j', #define s_2_8 73 's', 'e', 'l', #define s_2_9 76 'r', 'd', 'e', 'r', #define s_2_10 80 's', 't', 'e', 'r', #define s_2_11 84 'i', 't', 'e', 'i', 't', #define s_2_12 89 'd', 's', 't', #define s_2_13 92 't', 's', 't', #define s_3_0 95 'e', 'n', 'd', #define s_3_1 98 'a', 't', 'i', 'e', 'f', #define s_3_2 s_3_9 #define s_3_3 s_3_10 #define s_3_4 103 'i', 'o', 'n', 'e', 'e', 'l', #define s_3_5 109 'b', 'a', 'a', 'r', #define s_3_6 113 'l', 'a', 'a', 'r', #define s_3_7 117 'n', 'a', 'a', 'r', #define s_3_8 121 'r', 'a', 'a', 'r', #define s_3_9 125 'e', 'r', 'i', 'g', 'e', 'r', #define s_3_10 131 'a', 'c', 'h', 't', 'i', 'g', 'e', 'r', #define s_3_11 139 'l', 'i', 'j', 'k', 'e', 'r', #define s_3_12 145 't', 'a', 'n', 't', #define s_3_13 149 'e', 'r', 'i', 'g', 's', 't', #define s_3_14 155 'a', 'c', 'h', 't', 'i', 'g', 's', 't', #define s_3_15 163 'l', 'i', 'j', 'k', 's', 't', #define s_4_0 s_4_1 #define s_4_1 169 'i', 'g', 'e', 'r', #define s_4_2 173 'i', 'g', 's', 't', #define s_5_0 177 'f', 't', #define s_5_1 179 'k', 't', #define s_5_2 181 'p', 't', #define s_6_0 183 'b', 'b', #define s_6_1 185 'c', 'c', #define s_6_2 187 'd', 'd', #define s_6_3 189 'f', 'f', #define s_6_4 191 'g', 'g', #define s_6_5 193 'h', 'h', #define s_6_6 195 'j', 'j', #define s_6_7 197 'k', 'k', #define s_6_8 199 'l', 'l', #define s_6_9 201 'm', 'm', #define s_6_10 203 'n', 'n', #define s_6_11 205 'p', 'p', #define s_6_12 207 'q', 'q', #define s_6_13 209 'r', 'r', #define s_6_14 211 's', 's', #define s_6_15 213 't', 't', #define s_6_16 (s_6_17 + 1) #define s_6_17 215 'v', 'v', #define s_6_18 217 'w', 'w', #define s_6_19 219 'x', 'x', #define s_6_20 (s_6_21 + 1) #define s_6_21 221 'z', 'z', #define s_7_0 223 'd', #define s_7_1 224 't', }; static const Among a_0[7] = { /* 0 */ { 3, s_0_0, -1, 7}, /* 1 */ { 2, s_0_1, -1, 6}, /* 2 */ { 1, s_0_2, -1, 2}, /* 3 */ { 2, s_0_3, 2, 1}, /* 4 */ { 2, s_0_4, 2, 4}, /* 5 */ { 3, s_0_5, 4, 3}, /* 6 */ { 3, s_0_6, 2, 5} }; static const Among a_1[11] = { /* 0 */ { 2, s_1_0, -1, 5}, /* 1 */ { 2, s_1_1, -1, 2}, /* 2 */ { 5, s_1_2, -1, 4}, /* 3 */ { 2, s_1_3, -1, 1}, /* 4 */ { 5, s_1_4, -1, 3}, /* 5 */ { 2, s_1_5, -1, 9}, /* 6 */ { 3, s_1_6, -1, 10}, /* 7 */ { 2, s_1_7, -1, 8}, /* 8 */ { 2, s_1_8, -1, 7}, /* 9 */ { 2, s_1_9, -1, 6}, /* 10 */ { 4, s_1_10, -1, 11} }; static const Among a_2[14] = { /* 0 */ { 4, s_2_0, -1, 3}, /* 1 */ { 3, s_2_1, -1, 6}, /* 2 */ { 3, s_2_2, -1, 7}, /* 3 */ { 4, s_2_3, -1, 1}, /* 4 */ { 4, s_2_4, -1, 2}, /* 5 */ { 3, s_2_5, -1, 2}, /* 6 */ { 4, s_2_6, -1, 5}, /* 7 */ { 4, s_2_7, -1, 2}, /* 8 */ { 3, s_2_8, -1, 3}, /* 9 */ { 4, s_2_9, -1, 4}, /* 10 */ { 4, s_2_10, -1, 3}, /* 11 */ { 5, s_2_11, -1, 2}, /* 12 */ { 3, s_2_12, -1, 9}, /* 13 */ { 3, s_2_13, -1, 8} }; static const Among a_3[16] = { /* 0 */ { 3, s_3_0, -1, 9}, /* 1 */ { 5, s_3_1, -1, 2}, /* 2 */ { 4, s_3_2, -1, 9}, /* 3 */ { 6, s_3_3, -1, 3}, /* 4 */ { 6, s_3_4, -1, 1}, /* 5 */ { 4, s_3_5, -1, 3}, /* 6 */ { 4, s_3_6, -1, 5}, /* 7 */ { 4, s_3_7, -1, 4}, /* 8 */ { 4, s_3_8, -1, 6}, /* 9 */ { 6, s_3_9, -1, 9}, /* 10 */ { 8, s_3_10, -1, 3}, /* 11 */ { 6, s_3_11, -1, 8}, /* 12 */ { 4, s_3_12, -1, 7}, /* 13 */ { 6, s_3_13, -1, 9}, /* 14 */ { 8, s_3_14, -1, 3}, /* 15 */ { 6, s_3_15, -1, 8} }; static const Among a_4[3] = { /* 0 */ { 2, s_4_0, -1, 1}, /* 1 */ { 4, s_4_1, -1, 1}, /* 2 */ { 4, s_4_2, -1, 1} }; static const Among a_5[3] = { /* 0 */ { 2, s_5_0, -1, 2}, /* 1 */ { 2, s_5_1, -1, 1}, /* 2 */ { 2, s_5_2, -1, 3} }; static const Among a_6[22] = { /* 0 */ { 2, s_6_0, -1, 1}, /* 1 */ { 2, s_6_1, -1, 2}, /* 2 */ { 2, s_6_2, -1, 3}, /* 3 */ { 2, s_6_3, -1, 4}, /* 4 */ { 2, s_6_4, -1, 5}, /* 5 */ { 2, s_6_5, -1, 6}, /* 6 */ { 2, s_6_6, -1, 7}, /* 7 */ { 2, s_6_7, -1, 8}, /* 8 */ { 2, s_6_8, -1, 9}, /* 9 */ { 2, s_6_9, -1, 10}, /* 10 */ { 2, s_6_10, -1, 11}, /* 11 */ { 2, s_6_11, -1, 12}, /* 12 */ { 2, s_6_12, -1, 13}, /* 13 */ { 2, s_6_13, -1, 14}, /* 14 */ { 2, s_6_14, -1, 15}, /* 15 */ { 2, s_6_15, -1, 16}, /* 16 */ { 1, s_6_16, -1, 4}, /* 17 */ { 2, s_6_17, 16, 17}, /* 18 */ { 2, s_6_18, -1, 18}, /* 19 */ { 2, s_6_19, -1, 19}, /* 20 */ { 1, s_6_20, -1, 15}, /* 21 */ { 2, s_6_21, 20, 20} }; static const Among a_7[2] = { /* 0 */ { 1, s_7_0, -1, 1}, /* 1 */ { 1, s_7_1, -1, 2} }; static const uchar g_v[] = { 17, 65, 16, 1 }; static const uchar g_v_WX[] = { 17, 65, 208, 1 }; static const uchar g_AOU[] = { 1, 64, 16 }; static const uchar g_AIOU[] = { 1, 65, 16 }; static const symbol s_0[] = { 'i', 'j' }; static const symbol s_1[] = { 'i', 'j' }; static const symbol s_2[] = { 'i', 'j' }; static const symbol s_3[] = { 'i', 'e' }; static const symbol s_4[] = { 'a', 'r' }; static const symbol s_5[] = { 'e', 'r' }; static const symbol s_6[] = { 'e' }; static const symbol s_7[] = { 'a', 'u' }; static const symbol s_8[] = { 'h', 'e', 'd' }; static const symbol s_9[] = { 'h', 'e', 'i', 'd' }; static const symbol s_10[] = { 'n', 'd' }; static const symbol s_11[] = { 'n', 'd' }; static const symbol s_12[] = { '\'', 't' }; static const symbol s_13[] = { 'e', 't' }; static const symbol s_14[] = { 'r', 'n', 't' }; static const symbol s_15[] = { 'r', 'n' }; static const symbol s_16[] = { 'i', 'n', 'k' }; static const symbol s_17[] = { 'i', 'n', 'g' }; static const symbol s_18[] = { 'm', 'p' }; static const symbol s_19[] = { 'm' }; static const symbol s_20[] = { 'g' }; static const symbol s_21[] = { 'l', 'i', 'j', 'k' }; static const symbol s_22[] = { 'i', 's', 'c', 'h' }; static const symbol s_23[] = { 't' }; static const symbol s_24[] = { 's' }; static const symbol s_25[] = { 'r' }; static const symbol s_26[] = { 'l' }; static const symbol s_27[] = { 'e', 'n' }; static const symbol s_28[] = { 'i', 'e', 'f' }; static const symbol s_29[] = { 'e', 'e', 'r' }; static const symbol s_30[] = { 'r' }; static const symbol s_31[] = { 'a', 'a', 'r' }; static const symbol s_32[] = { 'f' }; static const symbol s_33[] = { 'g' }; static const symbol s_34[] = { 't' }; static const symbol s_35[] = { 'd' }; static const symbol s_36[] = { 'i', 'e' }; static const symbol s_37[] = { 'e', 'e', 'r' }; static const symbol s_38[] = { 'n' }; static const symbol s_39[] = { 'l' }; static const symbol s_40[] = { 'r' }; static const symbol s_41[] = { 't', 'e', 'e', 'r' }; static const symbol s_42[] = { 'l', 'i', 'j', 'k' }; static const symbol s_43[] = { 'k' }; static const symbol s_44[] = { 'f' }; static const symbol s_45[] = { 'p' }; static const symbol s_46[] = { 'b' }; static const symbol s_47[] = { 'c' }; static const symbol s_48[] = { 'd' }; static const symbol s_49[] = { 'f' }; static const symbol s_50[] = { 'g' }; static const symbol s_51[] = { 'h' }; static const symbol s_52[] = { 'j' }; static const symbol s_53[] = { 'k' }; static const symbol s_54[] = { 'l' }; static const symbol s_55[] = { 'm' }; static const symbol s_56[] = { 'n' }; static const symbol s_57[] = { 'p' }; static const symbol s_58[] = { 'q' }; static const symbol s_59[] = { 'r' }; static const symbol s_60[] = { 's' }; static const symbol s_61[] = { 't' }; static const symbol s_62[] = { 'v' }; static const symbol s_63[] = { 'w' }; static const symbol s_64[] = { 'x' }; static const symbol s_65[] = { 'z' }; static const symbol s_66[] = { 'g', 'e' }; static const symbol s_67[] = { 'g', 'e' }; static const symbol s_68[] = { 'i', 'j' }; static const symbol s_69[] = { 'i', 'j' }; static const symbol s_70[] = { 'Y' }; static const symbol s_71[] = { 'Y' }; static const symbol s_72[] = { 'y' }; int Xapian::InternalStemKraaij_pohlmann::r_R1() { if(!(I_p1 <= c)) return 0; return 1; } int Xapian::InternalStemKraaij_pohlmann::r_R2() { if(!(I_p2 <= c)) return 0; return 1; } int Xapian::InternalStemKraaij_pohlmann::r_V() { { int m_test1 = l - c; { int m2 = l - c; (void)m2; if(in_grouping_b_U(g_v, 97, 121, 0)) goto lab1; goto lab0; lab1: c = l - m2; if(!(eq_s_b(2, s_0))) return 0; } lab0: c = l - m_test1; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_VX() { { int m_test1 = l - c; { int ret = skip_utf8(p, c, lb, 0, -1); if(ret < 0) return 0; c = ret; } { int m2 = l - c; (void)m2; if(in_grouping_b_U(g_v, 97, 121, 0)) goto lab1; goto lab0; lab1: c = l - m2; if(!(eq_s_b(2, s_1))) return 0; } lab0: c = l - m_test1; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_C() { { int m_test1 = l - c; { int m2 = l - c; (void)m2; if(!(eq_s_b(2, s_2))) goto lab0; return 0; lab0: c = l - m2; } if(out_grouping_b_U(g_v, 97, 121, 0)) return 0; c = l - m_test1; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_lengthen_V() { { int m1 = l - c; (void)m1; if(out_grouping_b_U(g_v_WX, 97, 121, 0)) goto lab0; ket = c; { int m2 = l - c; (void)m2; if(in_grouping_b_U(g_AOU, 97, 117, 0)) goto lab2; bra = c; { int m_test3 = l - c; { int m4 = l - c; (void)m4; if(out_grouping_b_U(g_v, 97, 121, 0)) goto lab4; goto lab3; lab4: c = l - m4; if(c > lb) goto lab2; } lab3: c = l - m_test3; } goto lab1; lab2: c = l - m2; if(c <= lb || p[c - 1] != 'e') goto lab0; c--; bra = c; { int m_test5 = l - c; { int m6 = l - c; (void)m6; if(out_grouping_b_U(g_v, 97, 121, 0)) goto lab6; goto lab5; lab6: c = l - m6; if(c > lb) goto lab0; } lab5: { int m7 = l - c; (void)m7; if(in_grouping_b_U(g_AIOU, 97, 117, 0)) goto lab7; goto lab0; lab7: c = l - m7; } { int m8 = l - c; (void)m8; { int ret = skip_utf8(p, c, lb, 0, -1); if(ret < 0) goto lab8; c = ret; } if(in_grouping_b_U(g_AIOU, 97, 117, 0)) goto lab8; if(out_grouping_b_U(g_v, 97, 121, 0)) goto lab8; goto lab0; lab8: c = l - m8; } c = l - m_test5; } } lab1: { symbol * ret = slice_to(S_ch); if(ret == 0) return -1; S_ch = ret; } { int saved_c = c; insert_v(c, c, S_ch); c = saved_c; } lab0: c = l - m1; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Step_1() { int among_var; ket = c; if(c <= lb || p[c-1] >> 5 != 3 || !((540704 >> (p[c-1] & 0x1f)) & 1)) return 0; among_var = find_among_b(s_pool, a_0, 7, 0, 0); if(!(among_var)) return 0; bra = c; switch(among_var) { case 1: { int ret = slice_del(); if(ret < 0) return ret; } break; case 2: { int ret = r_R1(); if(ret <= 0) return ret; } { int m1 = l - c; (void)m1; if(c <= lb || p[c - 1] != 't') goto lab0; c--; { int ret = r_R1(); if(ret == 0) goto lab0; if(ret < 0) return ret; } return 0; lab0: c = l - m1; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } break; case 3: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(2, s_3); if(ret < 0) return ret; } break; case 4: { int m2 = l - c; (void)m2; if(!(eq_s_b(2, s_4))) goto lab2; { int ret = r_R1(); if(ret == 0) goto lab2; if(ret < 0) return ret; } { int ret = r_C(); if(ret == 0) goto lab2; if(ret < 0) return ret; } bra = c; { int ret = slice_del(); if(ret < 0) return ret; } { int ret = r_lengthen_V(); if(ret == 0) goto lab2; if(ret < 0) return ret; } goto lab1; lab2: c = l - m2; if(!(eq_s_b(2, s_5))) goto lab3; { int ret = r_R1(); if(ret == 0) goto lab3; if(ret < 0) return ret; } { int ret = r_C(); if(ret == 0) goto lab3; if(ret < 0) return ret; } bra = c; { int ret = slice_del(); if(ret < 0) return ret; } goto lab1; lab3: c = l - m2; { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_from_s(1, s_6); if(ret < 0) return ret; } } lab1: break; case 5: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_V(); if(ret <= 0) return ret; } { int ret = slice_from_s(2, s_7); if(ret < 0) return ret; } break; case 6: { int m3 = l - c; (void)m3; if(!(eq_s_b(3, s_8))) goto lab5; { int ret = r_R1(); if(ret == 0) goto lab5; if(ret < 0) return ret; } bra = c; { int ret = slice_from_s(4, s_9); if(ret < 0) return ret; } goto lab4; lab5: c = l - m3; if(!(eq_s_b(2, s_10))) goto lab6; { int ret = slice_del(); if(ret < 0) return ret; } goto lab4; lab6: c = l - m3; if(c <= lb || p[c - 1] != 'd') goto lab7; c--; { int ret = r_R1(); if(ret == 0) goto lab7; if(ret < 0) return ret; } { int ret = r_C(); if(ret == 0) goto lab7; if(ret < 0) return ret; } bra = c; { int ret = slice_del(); if(ret < 0) return ret; } goto lab4; lab7: c = l - m3; { int m4 = l - c; (void)m4; if(c <= lb || p[c - 1] != 'i') goto lab10; c--; goto lab9; lab10: c = l - m4; if(c <= lb || p[c - 1] != 'j') goto lab8; c--; } lab9: { int ret = r_V(); if(ret == 0) goto lab8; if(ret < 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } goto lab4; lab8: c = l - m3; { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } { int ret = r_lengthen_V(); if(ret <= 0) return ret; } } lab4: break; case 7: { int ret = slice_from_s(2, s_11); if(ret < 0) return ret; } break; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Step_2() { int among_var; ket = c; if(c - 1 <= lb || p[c-1] != 101) return 0; among_var = find_among_b(s_pool, a_1, 11, 0, 0); if(!(among_var)) return 0; bra = c; switch(among_var) { case 1: { int m1 = l - c; (void)m1; if(!(eq_s_b(2, s_12))) goto lab1; bra = c; { int ret = slice_del(); if(ret < 0) return ret; } goto lab0; lab1: c = l - m1; if(!(eq_s_b(2, s_13))) goto lab2; bra = c; { int ret = r_R1(); if(ret == 0) goto lab2; if(ret < 0) return ret; } { int ret = r_C(); if(ret == 0) goto lab2; if(ret < 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } goto lab0; lab2: c = l - m1; if(!(eq_s_b(3, s_14))) goto lab3; bra = c; { int ret = slice_from_s(2, s_15); if(ret < 0) return ret; } goto lab0; lab3: c = l - m1; if(c <= lb || p[c - 1] != 't') goto lab4; c--; bra = c; { int ret = r_R1(); if(ret == 0) goto lab4; if(ret < 0) return ret; } { int ret = r_VX(); if(ret == 0) goto lab4; if(ret < 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } goto lab0; lab4: c = l - m1; if(!(eq_s_b(3, s_16))) goto lab5; bra = c; { int ret = slice_from_s(3, s_17); if(ret < 0) return ret; } goto lab0; lab5: c = l - m1; if(!(eq_s_b(2, s_18))) goto lab6; bra = c; { int ret = slice_from_s(1, s_19); if(ret < 0) return ret; } goto lab0; lab6: c = l - m1; if(c <= lb || p[c - 1] != '\'') goto lab7; c--; bra = c; { int ret = r_R1(); if(ret == 0) goto lab7; if(ret < 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } goto lab0; lab7: c = l - m1; bra = c; { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } } lab0: break; case 2: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(1, s_20); if(ret < 0) return ret; } break; case 3: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(4, s_21); if(ret < 0) return ret; } break; case 4: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(4, s_22); if(ret < 0) return ret; } break; case 5: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } break; case 6: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(1, s_23); if(ret < 0) return ret; } break; case 7: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(1, s_24); if(ret < 0) return ret; } break; case 8: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(1, s_25); if(ret < 0) return ret; } break; case 9: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } insert_s(c, c, 1, s_26); { int ret = r_lengthen_V(); if(ret <= 0) return ret; } break; case 10: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } insert_s(c, c, 2, s_27); { int ret = r_lengthen_V(); if(ret <= 0) return ret; } break; case 11: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_from_s(3, s_28); if(ret < 0) return ret; } break; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Step_3() { int among_var; ket = c; if(c - 2 <= lb || p[c-1] >> 5 != 3 || !((1316016 >> (p[c-1] & 0x1f)) & 1)) return 0; among_var = find_among_b(s_pool, a_2, 14, 0, 0); if(!(among_var)) return 0; bra = c; switch(among_var) { case 1: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_from_s(3, s_29); if(ret < 0) return ret; } break; case 2: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } { int ret = r_lengthen_V(); if(ret <= 0) return ret; } break; case 3: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } break; case 4: { int ret = slice_from_s(1, s_30); if(ret < 0) return ret; } break; case 5: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_from_s(3, s_31); if(ret < 0) return ret; } break; case 6: { int ret = r_R2(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } insert_s(c, c, 1, s_32); { int ret = r_lengthen_V(); if(ret <= 0) return ret; } break; case 7: { int ret = r_R2(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } insert_s(c, c, 1, s_33); { int ret = r_lengthen_V(); if(ret <= 0) return ret; } break; case 8: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_from_s(1, s_34); if(ret < 0) return ret; } break; case 9: { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_from_s(1, s_35); if(ret < 0) return ret; } break; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Step_4() { int among_var; { int m1 = l - c; (void)m1; ket = c; if(c - 2 <= lb || p[c-1] >> 5 != 3 || !((1315024 >> (p[c-1] & 0x1f)) & 1)) goto lab1; among_var = find_among_b(s_pool, a_3, 16, 0, 0); if(!(among_var)) goto lab1; bra = c; switch(among_var) { case 1: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_from_s(2, s_36); if(ret < 0) return ret; } break; case 2: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_from_s(3, s_37); if(ret < 0) return ret; } break; case 3: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } break; case 4: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = r_V(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_from_s(1, s_38); if(ret < 0) return ret; } break; case 5: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = r_V(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_from_s(1, s_39); if(ret < 0) return ret; } break; case 6: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = r_V(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_from_s(1, s_40); if(ret < 0) return ret; } break; case 7: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_from_s(4, s_41); if(ret < 0) return ret; } break; case 8: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_from_s(4, s_42); if(ret < 0) return ret; } break; case 9: { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = r_C(); if(ret == 0) goto lab1; if(ret < 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } { int ret = r_lengthen_V(); if(ret == 0) goto lab1; if(ret < 0) return ret; } break; } goto lab0; lab1: c = l - m1; ket = c; if(c - 1 <= lb || p[c-1] >> 5 != 3 || !((1310848 >> (p[c-1] & 0x1f)) & 1)) return 0; if(!(find_among_b(s_pool, a_4, 3, 0, 0))) return 0; bra = c; { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } { int ret = slice_del(); if(ret < 0) return ret; } { int ret = r_lengthen_V(); if(ret <= 0) return ret; } } lab0: return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Step_7() { int among_var; ket = c; if(c - 1 <= lb || p[c-1] != 116) return 0; among_var = find_among_b(s_pool, a_5, 3, 0, 0); if(!(among_var)) return 0; bra = c; switch(among_var) { case 1: { int ret = slice_from_s(1, s_43); if(ret < 0) return ret; } break; case 2: { int ret = slice_from_s(1, s_44); if(ret < 0) return ret; } break; case 3: { int ret = slice_from_s(1, s_45); if(ret < 0) return ret; } break; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Step_6() { int among_var; ket = c; if(c <= lb || p[c-1] >> 5 != 3 || !((98532828 >> (p[c-1] & 0x1f)) & 1)) return 0; among_var = find_among_b(s_pool, a_6, 22, 0, 0); if(!(among_var)) return 0; bra = c; switch(among_var) { case 1: { int ret = slice_from_s(1, s_46); if(ret < 0) return ret; } break; case 2: { int ret = slice_from_s(1, s_47); if(ret < 0) return ret; } break; case 3: { int ret = slice_from_s(1, s_48); if(ret < 0) return ret; } break; case 4: { int ret = slice_from_s(1, s_49); if(ret < 0) return ret; } break; case 5: { int ret = slice_from_s(1, s_50); if(ret < 0) return ret; } break; case 6: { int ret = slice_from_s(1, s_51); if(ret < 0) return ret; } break; case 7: { int ret = slice_from_s(1, s_52); if(ret < 0) return ret; } break; case 8: { int ret = slice_from_s(1, s_53); if(ret < 0) return ret; } break; case 9: { int ret = slice_from_s(1, s_54); if(ret < 0) return ret; } break; case 10: { int ret = slice_from_s(1, s_55); if(ret < 0) return ret; } break; case 11: { int ret = slice_from_s(1, s_56); if(ret < 0) return ret; } break; case 12: { int ret = slice_from_s(1, s_57); if(ret < 0) return ret; } break; case 13: { int ret = slice_from_s(1, s_58); if(ret < 0) return ret; } break; case 14: { int ret = slice_from_s(1, s_59); if(ret < 0) return ret; } break; case 15: { int ret = slice_from_s(1, s_60); if(ret < 0) return ret; } break; case 16: { int ret = slice_from_s(1, s_61); if(ret < 0) return ret; } break; case 17: { int ret = slice_from_s(1, s_62); if(ret < 0) return ret; } break; case 18: { int ret = slice_from_s(1, s_63); if(ret < 0) return ret; } break; case 19: { int ret = slice_from_s(1, s_64); if(ret < 0) return ret; } break; case 20: { int ret = slice_from_s(1, s_65); if(ret < 0) return ret; } break; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Step_1c() { int among_var; ket = c; if(c <= lb || (p[c-1] != 100 && p[c-1] != 116)) return 0; among_var = find_among_b(s_pool, a_7, 2, 0, 0); if(!(among_var)) return 0; bra = c; { int ret = r_R1(); if(ret <= 0) return ret; } { int ret = r_C(); if(ret <= 0) return ret; } switch(among_var) { case 1: { int m1 = l - c; (void)m1; if(c <= lb || p[c - 1] != 'n') goto lab0; c--; { int ret = r_R1(); if(ret == 0) goto lab0; if(ret < 0) return ret; } return 0; lab0: c = l - m1; } { int ret = slice_del(); if(ret < 0) return ret; } break; case 2: { int m2 = l - c; (void)m2; if(c <= lb || p[c - 1] != 'h') goto lab1; c--; { int ret = r_R1(); if(ret == 0) goto lab1; if(ret < 0) return ret; } return 0; lab1: c = l - m2; } { int ret = slice_del(); if(ret < 0) return ret; } break; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Lose_prefix() { bra = c; if(!(eq_s(2, s_66))) return 0; ket = c; { int c_test1 = c; { int ret = skip_utf8(p, c, 0, l, + 3); if(ret < 0) return 0; c = ret; } c = c_test1; } if(out_grouping_U(g_v, 97, 121, 1) < 0) return 0; if(in_grouping_U(g_v, 97, 121, 1) < 0) return 0; I_GE_removed = 1; { int ret = slice_del(); if(ret < 0) return ret; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_Lose_infix() { { int ret = skip_utf8(p, c, 0, l, 1); if(ret < 0) return 0; c = ret; } while(1) { bra = c; if(!(eq_s(2, s_67))) goto lab0; ket = c; break; lab0: { int ret = skip_utf8(p, c, 0, l, 1); if(ret < 0) return 0; c = ret; } } { int c_test1 = c; { int ret = skip_utf8(p, c, 0, l, + 3); if(ret < 0) return 0; c = ret; } c = c_test1; } if(out_grouping_U(g_v, 97, 121, 1) < 0) return 0; if(in_grouping_U(g_v, 97, 121, 1) < 0) return 0; I_GE_removed = 1; { int ret = slice_del(); if(ret < 0) return ret; } return 1; } int Xapian::InternalStemKraaij_pohlmann::r_measure() { I_p1 = l; I_p2 = l; { int c1 = c; while(1) { if(out_grouping_U(g_v, 97, 121, 0)) goto lab1; continue; lab1: break; } { int i = 1; while(1) { int c2 = c; { int c3 = c; if(!(eq_s(2, s_68))) goto lab4; goto lab3; lab4: c = c3; if(in_grouping_U(g_v, 97, 121, 0)) goto lab2; } lab3: i--; continue; lab2: c = c2; break; } if(i > 0) goto lab0; } if(out_grouping_U(g_v, 97, 121, 0)) goto lab0; I_p1 = c; while(1) { if(out_grouping_U(g_v, 97, 121, 0)) goto lab5; continue; lab5: break; } { int i = 1; while(1) { int c4 = c; { int c5 = c; if(!(eq_s(2, s_69))) goto lab8; goto lab7; lab8: c = c5; if(in_grouping_U(g_v, 97, 121, 0)) goto lab6; } lab7: i--; continue; lab6: c = c4; break; } if(i > 0) goto lab0; } if(out_grouping_U(g_v, 97, 121, 0)) goto lab0; I_p2 = c; lab0: c = c1; } return 1; } int Xapian::InternalStemKraaij_pohlmann::stem() { I_Y_found = 0; I_stemmed = 0; { int c1 = c; bra = c; if(c == l || p[c] != 'y') goto lab0; c++; ket = c; { int ret = slice_from_s(1, s_70); if(ret < 0) return ret; } I_Y_found = 1; lab0: c = c1; } { int c2 = c; while(1) { int c3 = c; while(1) { int c4 = c; if(in_grouping_U(g_v, 97, 121, 0)) goto lab3; bra = c; if(c == l || p[c] != 'y') goto lab3; c++; ket = c; c = c4; break; lab3: c = c4; { int ret = skip_utf8(p, c, 0, l, 1); if(ret < 0) goto lab2; c = ret; } } { int ret = slice_from_s(1, s_71); if(ret < 0) return ret; } I_Y_found = 1; continue; lab2: c = c3; break; } c = c2; } { int ret = r_measure(); if(ret <= 0) return ret; } lb = c; c = l; { int m5 = l - c; (void)m5; { int ret = r_Step_1(); if(ret == 0) goto lab4; if(ret < 0) return ret; } I_stemmed = 1; lab4: c = l - m5; } { int m6 = l - c; (void)m6; { int ret = r_Step_2(); if(ret == 0) goto lab5; if(ret < 0) return ret; } I_stemmed = 1; lab5: c = l - m6; } { int m7 = l - c; (void)m7; { int ret = r_Step_3(); if(ret == 0) goto lab6; if(ret < 0) return ret; } I_stemmed = 1; lab6: c = l - m7; } { int m8 = l - c; (void)m8; { int ret = r_Step_4(); if(ret == 0) goto lab7; if(ret < 0) return ret; } I_stemmed = 1; lab7: c = l - m8; } c = lb; I_GE_removed = 0; { int c9 = c; { int c10 = c; { int ret = r_Lose_prefix(); if(ret == 0) goto lab8; if(ret < 0) return ret; } c = c10; { int ret = r_measure(); if(ret == 0) goto lab8; if(ret < 0) return ret; } } lab8: c = c9; } lb = c; c = l; { int m11 = l - c; (void)m11; if(!(I_GE_removed)) goto lab9; { int ret = r_Step_1c(); if(ret == 0) goto lab9; if(ret < 0) return ret; } lab9: c = l - m11; } c = lb; I_GE_removed = 0; { int c12 = c; { int c13 = c; { int ret = r_Lose_infix(); if(ret == 0) goto lab10; if(ret < 0) return ret; } c = c13; { int ret = r_measure(); if(ret == 0) goto lab10; if(ret < 0) return ret; } } lab10: c = c12; } lb = c; c = l; { int m14 = l - c; (void)m14; if(!(I_GE_removed)) goto lab11; { int ret = r_Step_1c(); if(ret == 0) goto lab11; if(ret < 0) return ret; } lab11: c = l - m14; } c = lb; lb = c; c = l; { int m15 = l - c; (void)m15; { int ret = r_Step_7(); if(ret == 0) goto lab12; if(ret < 0) return ret; } I_stemmed = 1; lab12: c = l - m15; } { int m16 = l - c; (void)m16; if(!(I_stemmed)) goto lab15; goto lab14; lab15: if(!(I_GE_removed)) goto lab13; lab14: { int ret = r_Step_6(); if(ret == 0) goto lab13; if(ret < 0) return ret; } lab13: c = l - m16; } c = lb; { int c17 = c; if(!(I_Y_found)) goto lab16; while(1) { int c18 = c; while(1) { int c19 = c; bra = c; if(c == l || p[c] != 'Y') goto lab18; c++; ket = c; c = c19; break; lab18: c = c19; { int ret = skip_utf8(p, c, 0, l, 1); if(ret < 0) goto lab17; c = ret; } } { int ret = slice_from_s(1, s_72); if(ret < 0) return ret; } continue; lab17: c = c18; break; } lab16: c = c17; } return 1; } Xapian::InternalStemKraaij_pohlmann::InternalStemKraaij_pohlmann() : I_GE_removed(0), I_stemmed(0), I_Y_found(0), I_p2(0), I_p1(0), S_ch(0) { S_ch = create_s(); } Xapian::InternalStemKraaij_pohlmann::~InternalStemKraaij_pohlmann() { lose_s(S_ch); } std::string Xapian::InternalStemKraaij_pohlmann::get_description() const { return "kraaij_pohlmann.sbl"; }
papyrussolution/OpenPapyrus
Src/OSF/xapian/xapian-core/languages/kraaij_pohlmann.sbl.cc
C++
agpl-3.0
33,359
DELETE FROM `weenie` WHERE `class_Id` = 25894; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (25894, 'orbnefaneblack', 35, '2019-02-10 00:00:00') /* Caster */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (25894, 1, 32768) /* ItemType - Caster */ , (25894, 5, 75) /* EncumbranceVal */ , (25894, 9, 16777216) /* ValidLocations - Held */ , (25894, 16, 1) /* ItemUseable - No */ , (25894, 18, 1) /* UiEffects - Magical */ , (25894, 19, 7500) /* Value */ , (25894, 93, 3092) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity, LightingOn */ , (25894, 94, 16) /* TargetType - Creature */ , (25894, 106, 400) /* ItemSpellcraft */ , (25894, 107, 1400) /* ItemCurMana */ , (25894, 108, 1400) /* ItemMaxMana */ , (25894, 109, 100) /* ItemDifficulty */ , (25894, 151, 2) /* HookType - Wall */ , (25894, 158, 1) /* WieldRequirements - Skill */ , (25894, 159, 16) /* WieldSkillType - ManaConversion */ , (25894, 160, 240) /* WieldDifficulty */ , (25894, 8041, 101) /* PCAPRecordedPlacement - Resting */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (25894, 22, True ) /* Inscribable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (25894, 5, -0.05) /* ManaRate */ , (25894, 29, 1) /* WeaponDefense */ , (25894, 76, 0.2) /* Translucency */ , (25894, 144, 0.11) /* ManaConversionMod */ , (25894, 147, 1) /* CriticalFrequency */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (25894, 1, 'Nefane Pearl') /* Name */ , (25894, 16, 'A pearl carefully removed from the corpse of a nefane.') /* LongDesc */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (25894, 1, 33558259) /* Setup */ , (25894, 3, 536870932) /* SoundTable */ , (25894, 6, 67111919) /* PaletteBase */ , (25894, 8, 100675628) /* Icon */ , (25894, 22, 872415275) /* PhysicsEffectTable */ , (25894, 8001, 271138968) /* PCAPRecordedWeenieHeader - Value, Usable, UiEffects, Container, ValidLocations, TargetType, Burden, HookType */ , (25894, 8003, 18) /* PCAPRecordedObjectDesc - Inscribable, Attackable */ , (25894, 8005, 399361) /* PCAPRecordedPhysicsDesc - CSetup, STable, PeTable, AnimationFrame, Translucency */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (25894, 8000, 3679800301) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_spell_book` (`object_Id`, `spell`, `probability`) VALUES (25894, 1478, 2) /* HermeticLinkSelf4 */ , (25894, 2624, 2) /* CANTRIPMANAGAIN2 */; INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`) VALUES (25894, 67111925, 0, 0); INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`) VALUES (25894, 0, 83894476, 83894476); INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`) VALUES (25894, 0, 16788882);
LtRipley36706/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Caster/Caster/25894 Nefane Pearl.sql
SQL
agpl-3.0
3,271
#pragma once #include <QString> #include <QByteArray> class MotorFaultsMessage { public: MotorFaultsMessage(QByteArray& messageData); unsigned char M0ErrorFlags() const; unsigned char M1ErrorFlags() const; unsigned char M0LimitFlags() const; unsigned char M1LimitFlags() const; unsigned char M0CanRxErrorCount() const; unsigned char M0CanTxErrorCount() const; unsigned char M1CanRxErrorCount() const; unsigned char M1CanTxErrorCount() const; QString toString() const; private: const QByteArray messageData_; };
UCSolarCarTeam/Epsilon-Hermes
src/CommunicationLayer/MessagingFramework/MotorFaultsMessage.h
C
agpl-3.0
560
<?php // Album titles $locale['400'] = "Add Photo"; $locale['401'] = "Edit Photo"; $locale['402'] = "Current Photos"; $locale['403'] = "Serious Photoalbum Error"; // Album messages $locale['410'] = "Photo(s) added"; $locale['411'] = "Photo updated"; $locale['412'] = "Photo thumbnail deleted"; $locale['413'] = "Photo deleted"; $locale['414'] = "The following error has occured:"; $locale['415'] = "Invalid image filename."; $locale['416'] = "Image must be less than %s."; $locale['417'] = "Image must be a GIF, JPEG or PNG file."; $locale['418'] = "Image must be no bigger than %uw x %uh pixels."; $locale['419'] = "Photo(s) moved."; $locale['420'] = "No GD library detected. Photoalbums will not work without GD library. Contact your hosting provider for further information."; $locale['421'] = "Image can not be empty."; $locale['422'] = "Selected folder is not writable. Change it to CHMOD 777."; // Photos form $locale['430'] = "Move photo into album"; $locale['431'] = "Move"; $locale['432'] = "Title: "; $locale['433'] = "Description: "; $locale['434'] = "Order: "; $locale['435'] = "Thumb: "; $locale['436'] = "Image: "; $locale['437'] = "Enable Comments"; $locale['438'] = "Enable Ratings"; $locale['439'] = "Save Photo"; $locale['440'] = "Cancel"; $locale['441'] = "Keywords (separate each keyword with a ,):"; // Current Photos $locale['450'] = "No image"; $locale['451'] = "Click to view"; $locale['452'] = "Move up"; $locale['453'] = "Move down"; $locale['454'] = "Edit"; $locale['455'] = "Delete"; $locale['456'] = "Date: "; $locale['457'] = "Added by: "; $locale['458'] = "Views: "; $locale['459'] = "Comments: "; $locale['460'] = "No Thumbnail"; // Current Photos options $locale['470'] = "Select all"; $locale['471'] = "Unselect all"; $locale['472'] = "Move into album"; $locale['473'] = "Select album"; $locale['474'] = "Move selected"; $locale['475'] = "Move all"; $locale['476'] = "Close Album"; // Additional notices $locale['480'] = "No Photos defined."; $locale['481'] = "Move selected photos?"; $locale['482'] = "Move all photos?"; //Mass Upload $locale['490'] = "Add Folder"; $locale['491'] = "Add folder to album"; $locale['492'] = "Add photos to album"; $locale['493'] = "Upload single photos"; $locale['494'] = "Upload folder with photos"; $locale['495'] = "Upload multiple photos"; $locale['496'] = "<strong>Warning:</strong><br />Photo title and description of each uploaded photo will be empty,<br />you can enter them later by editing each photo!"; $locale['497'] = "1. Upload your folder with photos to directory <em>%s</em>."; $locale['498'] = "2. Select the folder you want to add to album <strong>%s</strong>."; $locale['499'] = "Select folder:"; $locale['500'] = "Add selected folder to album"; $locale['501'] = "No folders found"; $locale['502'] = "%s is not writable!"; $locale['503'] = "Please change the directory permissions to 0777 and click on the button to reload this page."; $locale['504'] = "Refresh"; $locale['505'] = "1. Upload your photos to folder <em>%s</em>."; $locale['506'] = "2. Select the photos you want to add to album <strong>%s</strong>."; $locale['507'] = "3. You can select more than one photo by holding the key [SHIFT] or [CTRL] while clicking."; $locale['508'] = "Select photo(s):"; $locale['509'] = "Add selected photo(s) to album"; $locale['510'] = "No photos found"; $locale['511'] = "Photo Options"; // Messages $locale['520'] = "%s are disabled for all items.<br />This setting will only take effect when they are enabled again."; $locale['521'] = "Comments"; $locale['522'] = "Ratings"; $locale['523'] = $locale['521']." and ".$locale['522'];
Talocha/PHP-Fusion
locale/Malay/admin/photos.php
PHP
agpl-3.0
3,703
package tigase.xmpp.impl; import com.quickblox.chat.utils.QBChatUtils; import tigase.db.NonAuthUserRepository; import tigase.db.TigaseDBException; import tigase.disteventbus.EventBus; import tigase.disteventbus.EventBusFactory; import tigase.server.Message; import tigase.server.Packet; import tigase.server.Presence; import tigase.stats.qb.processors.ProcessPacket; import tigase.stats.qb.processors.containers.MessageProcessorsContainer; import tigase.stats.qb.processors.containers.PresenceProcessorsContainer; import tigase.stats.qb.processors.containers.ProcessorsContainer; import tigase.xmpp.JID; import tigase.xmpp.XMPPException; import tigase.xmpp.XMPPProcessorIfc; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.impl.annotation.AnnotatedXMPPProcessor; import tigase.xmpp.impl.annotation.Handle; import tigase.xmpp.impl.annotation.Handles; import tigase.xmpp.impl.annotation.Id; import java.util.HashMap; import java.util.Map; import java.util.Queue; import java.util.logging.Logger; @Id(QBStatsCollector.ID) @Handles({ @Handle( path = {Message.ELEM_NAME}, xmlns = QBStatsCollector.XMLNS ), @Handle( path = {Presence.ELEM_NAME}, xmlns = QBStatsCollector.XMLNS ) }) /** * Created by QuickBlox team on 1/1/15. */ public class QBStatsCollector extends AnnotatedXMPPProcessor implements XMPPProcessorIfc { public static final String ID = "stats_collector"; public static final String XMLNS = "jabber:client"; private static final Logger log = Logger.getLogger(QBStatsCollector.class.getName()); protected EventBus eventBus; /** * Processors for messages and presence. */ protected Map<String, ProcessorsContainer> processorsContainers; @Override public void init(Map<String, Object> settings) throws TigaseDBException { //init processors processorsContainers = new HashMap<>(); processorsContainers.put(Presence.ELEM_NAME, new PresenceProcessorsContainer()); processorsContainers.put(Message.ELEM_NAME, new MessageProcessorsContainer()); //init event bus eventBus = EventBusFactory.getInstance(); } @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { Integer appId = getAppIdFromJID(packet.getStanzaFrom()); if (appId == null || !packet.getPacketFrom().getLocalpart().equals("c2s")) { return; } ProcessPacket[] processors; try { //retrieve corresponding processors for incoming element processors = processorsContainers.get(packet.getElemName()).getProcessors(); } catch (Exception e) { log.warning("An error occured : " + e.getMessage()); log.warning("Setting processors to an empty array."); processors = new ProcessPacket[0]; } for (ProcessPacket processor : processors) { processor.execute(packet, String.valueOf(appId), eventBus); } } protected Integer getAppIdFromJID(JID jid) { if (jid == null) { log.warning("Can't save stats for Presence or Message because packet.getStanzaFrom() is null"); return null; } Integer appId = null; Integer[] userParams = QBChatUtils.getApplicationIDAndUserIDFromUserJIDLocalPart(jid.getLocalpart()); if (userParams != null) { appId = userParams[0]; } return appId; } }
QuickBlox/QuickBlox-Tigase-CustomFeatures
tigase-server/plugins/QBStatsCollector.java
Java
agpl-3.0
3,594
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.purap.document.authorization; import org.apache.commons.collections.CollectionUtils; import org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument; import org.kuali.kfs.sys.KFSPropertyConstants; import org.kuali.kfs.sys.businessobject.AccountingLine; import org.kuali.kfs.sys.document.AccountingDocument; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kim.api.identity.Person; import java.util.Set; /** * Accounting line authorizer for Requisition document which allows adding accounting lines at specified nodes */ public class RequisitionAccountingLineAuthorizer extends PurapAccountingLineAuthorizer { protected static final String INITIATOR_NODE = "Initiator"; protected static final String CONTENT_REVIEW_NODE = "Organization"; /** * Allow new lines to be rendered at Initiator node * * @see org.kuali.kfs.sys.document.authorization.AccountingLineAuthorizerBase#renderNewLine(org.kuali.kfs.sys.document.AccountingDocument, java.lang.String) */ @Override public boolean renderNewLine(AccountingDocument accountingDocument, String accountingGroupProperty) { WorkflowDocument workflowDocument = ((PurchasingAccountsPayableDocument) accountingDocument).getFinancialSystemDocumentHeader().getWorkflowDocument(); Set<String> currentNodes = workflowDocument.getCurrentNodeNames(); if (CollectionUtils.isNotEmpty(currentNodes) && (currentNodes.contains(RequisitionAccountingLineAuthorizer.INITIATOR_NODE) || currentNodes.contains(RequisitionAccountingLineAuthorizer.CONTENT_REVIEW_NODE))) { return true; } return super.renderNewLine(accountingDocument, accountingGroupProperty); } /** * @see org.kuali.kfs.sys.document.authorization.AccountingLineAuthorizerBase#getUnviewableBlocks(org.kuali.kfs.sys.document.AccountingDocument, org.kuali.kfs.sys.businessobject.AccountingLine, boolean, org.kuali.rice.kim.api.identity.Person) */ @Override public Set<String> getUnviewableBlocks(AccountingDocument accountingDocument, AccountingLine accountingLine, boolean newLine, Person currentUser) { Set<String> unviewableBlocks = super.getUnviewableBlocks(accountingDocument, accountingLine, newLine, currentUser); unviewableBlocks.remove(KFSPropertyConstants.PERCENT); unviewableBlocks.remove(KFSPropertyConstants.AMOUNT); return unviewableBlocks; } }
quikkian-ua-devops/will-financials
kfs-purap/src/main/java/org/kuali/kfs/module/purap/document/authorization/RequisitionAccountingLineAuthorizer.java
Java
agpl-3.0
3,282
package com.tesora.dve.variables; /* * #%L * Tesora Inc. * Database Virtualization Engine * %% * Copyright (C) 2011 - 2014 Tesora Inc. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ public interface VariableStore { public <Type> ValueReference<Type> getReference(VariableHandler<Type> vh); public <Type> void setValue(VariableHandler<Type> vh, Type t); public <Type> Type getValue(VariableHandler<Type> vh); }
Tesora/tesora-dve-pub
tesora-dve-core/src/main/java/com/tesora/dve/variables/VariableStore.java
Java
agpl-3.0
1,001