answer
stringlengths 15
1.25M
|
|---|
package cern.colt.matrix.tlong.impl;
public class <API key> extends <API key> {
public <API key>(String arg0) {
super(arg0);
}
protected void createMatrices() throws Exception {
A = new <API key>(NCOLUMNS, NROWS).viewDice();
B = new <API key>(NCOLUMNS, NROWS).viewDice();
Bt = new <API key>(NROWS, NCOLUMNS).viewDice();
}
}
|
<!DOCTYPE HTML PUBLIC "-
<html><head><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="<API key>" onLoad="NDOnLoad()"><script language=JavaScript><!
if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script>
<!-- Generated by Natural Docs, version 1.4 -->
<div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_FileException><div class=IEntry><a href="../files/lib/exception-file-php.html#FileException" target=_parent class=ISymbol>FileException</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults", "HTML");
searchResults.Search();
--></script></div><script language=JavaScript><!--
if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
|
package handling.handlers;
import java.awt.Point;
import client.MapleClient;
import handling.PacketHandler;
import handling.RecvPacketOpcode;
import server.MaplePortal;
import tools.data.<API key>;
public class <API key> {
@PacketHandler(opcode = RecvPacketOpcode.USE_INNER_PORTAL)
public static void handle(MapleClient c, <API key> lea) {
lea.skip(1);
if (c.getPlayer() == null || c.getPlayer().getMap() == null) {
return;
}
String portalName = lea.<API key>();
MaplePortal portal = c.getPlayer().getMap().getPortal(portalName);
if (portal == null) {
return;
}
//That "22500" should not be hard coded in this manner
if (portal.getPosition().distanceSq(c.getPlayer().getTruePosition()) > 22500.0D && !c.getPlayer().isGM()) {
return;
}
int toX = lea.readShort();
int toY = lea.readShort();
//Are there not suppose to be checks here? Can players not just PE any x and y value they want?
c.getPlayer().getMap().movePlayer(c.getPlayer(), new Point(toX, toY));
c.getPlayer().checkFollow();
}
}
|
#ifndef __COMMON_H_
#define __COMMON_H_
#include "system.h"
#include "fsinet.h"
#define SAFE_DELETE_ARRAY(a) {if (a) {delete [] a; a = NULL;}}
#endif
|
#ifndef REPLY_H
#define REPLY_H
#include <QNetworkReply>
class Reply : public QObject
{
Q_OBJECT
public:
int _id;
QNetworkReply *res;
Reply(int id, QNetworkReply *net){
res = net;
_id = id;
connect(res,SIGNAL(uploadProgress(qint64,qint64)),this,SLOT(progress(qint64,qint64)));
}
signals:
void percentReady(int percent,int id);
public slots:
void progress(qint64 up,qint64 to){
float per = (float)100/(float)to*(float)up;
percentReady((int)per,_id);
}
};
#endif
|
#ifndef <API key>
#define <API key>
#include <cassert>
#include <vector>
#include <Eigen/Geometry>
namespace Vitelotte
{
enum BezierSegmentType
{
BEZIER_EMPTY = 0,
BEZIER_LINEAR = 2,
BEZIER_QUADRATIC = 3,
BEZIER_CUBIC = 4
};
template < typename _Vector >
class BezierSegment {
public:
typedef typename _Vector::Scalar Scalar;
typedef _Vector Vector;
typedef BezierSegment<Vector> Self;
public:
inline BezierSegment()
: m_type(BEZIER_EMPTY) {}
inline BezierSegment(BezierSegmentType type, const Vector* points)
: m_type(type) {
std::copy(points, points + type, m_points);
}
inline BezierSegmentType type() const { return m_type; }
inline void setType(BezierSegmentType type) { m_type = type; }
inline const Vector& point(unsigned i) const {
assert(i < m_type);
return m_points[i];
}
inline Vector& point(unsigned i) {
assert(i < m_type);
return m_points[i];
}
inline Self getBackward() const {
Self seg;
seg.setType(type());
for(unsigned i = 0; i < type(); ++i) {
seg.point(type() - 1 - i) = point(i);
}
return seg;
}
void split(Scalar pos, Self& head, Self& tail) {
assert(m_type != BEZIER_EMPTY);
// All the points of de Casteljau Algorithm
Vector pts[10];
Vector* levels[] = {
&pts[9],
&pts[7],
&pts[4],
pts
};
// Initialize the current level.
std::copy(m_points, m_points + type(), levels[type() - 1]);
// Compute all the points
for(int level = type()-1; level >= 0; --level) {
for(int i = 0; i < level; ++i) {
levels[level-1][i] = (Scalar(1) - pos) * levels[level][i]
+ pos * levels[level][i+1];
}
}
// Set the segments
head.setType(type());
tail.setType(type());
const unsigned last = type() - 1;
for(unsigned i = 0; i < type(); ++i) {
head.point(i) = levels[last - i][0];
tail.point(i) = levels[i][i];
}
}
template < typename InIt >
void refineUniform(InIt out, unsigned nSplit) {
Self head;
Self tail = *this;
*(out++) = std::make_pair(Scalar(0), point(0));
for(unsigned i = 0; i < nSplit; ++i) {
Scalar x = Scalar(i+1) / Scalar(nSplit + 1);
tail.split(x, head, tail);
*(out++) = std::make_pair(x, tail.point(0));
}
*(out++) = std::make_pair(Scalar(1), point(type()-1));
}
<API key>
private:
BezierSegmentType m_type;
Vector m_points[4];
};
template < typename _Vector >
class BezierPath
{
public:
typedef _Vector Vector;
public:
static unsigned size(BezierSegmentType type) { return unsigned(type); }
public:
inline BezierPath() {}
inline unsigned nPoints() const { return m_points.size(); }
inline unsigned nSegments() const { return m_segments.size(); }
inline BezierSegmentType type(unsigned si) const { return m_segments.at(si).type; }
inline unsigned nPoints(unsigned si) const { return size(type(si)); }
inline const Vector& point(unsigned pi) const { return m_points.at(pi); }
inline Vector& point(unsigned pi) { return m_points.at(pi); }
inline const Vector& point(unsigned si, unsigned pi) const
{
assert(si < nSegments() && pi < nPoints(si));
return m_points.at(m_segments[si].firstPoint + pi);
}
inline Vector& point(unsigned si, unsigned pi)
{
assert(si < nSegments() && pi < nPoints(si));
return m_points.at(m_segments[si].firstPoint + pi);
}
inline void setFirstPoint(const Vector& point)
{
assert(nPoints() == 0);
m_points.push_back(point);
}
unsigned addSegment(BezierSegmentType type, const Vector* points)
{
assert(nPoints() != 0);
unsigned si = nSegments();
Segment s;
s.type = type;
s.firstPoint = nPoints() - 1;
m_segments.push_back(s);
for(unsigned i = 0; i < nPoints(si) - 1; ++i)
{
m_points.push_back(points[i]);
}
return si;
}
BezierSegment<Vector> getSegment(unsigned si) const {
assert(si < nSegments());
return BezierSegment<Vector>(type(si), &m_points[m_segments[si].firstPoint]);
}
private:
struct Segment {
BezierSegmentType type;
unsigned firstPoint;
};
typedef std::vector<Vector> PointList;
typedef std::vector<Segment> SegmentList;
private:
PointList m_points;
SegmentList m_segments;
};
}
#endif
|
<!DOCTYPE html>
<!
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 4.7.1
Author: KeenThemes
Website: http:
Contact: support@keenthemes.com
Follow: www.twitter.com/keenthemes
Dribbble: www.dribbble.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/<API key>/4021469?ref=keenthemes
Renew Support: http://themeforest.net/item/<API key>/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en" dir="rtl">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title>Metronic Admin RTL Theme #5 | User Login 3</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="Preview page of Metronic Admin RTL Theme #5 for " name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap-switch/css/<API key>.min.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="../assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="../assets/global/css/<API key>.min.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="../assets/global/css/plugins-rtl.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link href="../assets/pages/css/login-3-rtl.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<!-- END THEME LAYOUT STYLES -->
<link rel="shortcut icon" href="favicon.ico" /> </head>
<!-- END HEAD -->
<body class=" login">
<!-- BEGIN LOGO -->
<div class="logo">
<a href="index.html">
<img src="../assets/pages/img/logo-big.png" alt="" /> </a>
</div>
<!-- END LOGO -->
<!-- BEGIN LOGIN -->
<div class="content">
<!-- BEGIN LOGIN FORM -->
<form class="login-form" action="index.html" method="post">
<h3 class="form-title">Login to your account</h3>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span> Enter any username and password. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" /> </div>
</div>
<div class="form-actions">
<label class="rememberme mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="remember" value="1" /> Remember me
<span></span>
</label>
<button type="submit" class="btn green pull-right"> Login </button>
</div>
<div class="login-options">
<h4>Or login with</h4>
<ul class="social-icons">
<li>
<a class="facebook" data-original-title="facebook" href="javascript:;"> </a>
</li>
<li>
<a class="<TwitterConsumerkey>="Twitter" href="javascript:;"> </a>
</li>
<li>
<a class="googleplus" data-original-title="Goole Plus" href="javascript:;"> </a>
</li>
<li>
<a class="linkedin" data-original-title="Linkedin" href="javascript:;"> </a>
</li>
</ul>
</div>
<div class="forget-password">
<h4>Forgot your password ?</h4>
<p> no worries, click
<a href="javascript:;" id="forget-password"> here </a> to reset your password. </p>
</div>
<div class="create-account">
<p> Don't have an account yet ?
<a href="javascript:;" id="register-btn"> Create an account </a>
</p>
</div>
</form>
<!-- END LOGIN FORM -->
<!-- BEGIN FORGOT PASSWORD FORM -->
<form class="forget-form" action="index.html" method="post">
<h3>Forget Password ?</h3>
<p> Enter your e-mail address below to reset your password. </p>
<div class="form-group">
<div class="input-icon">
<i class="fa fa-envelope"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Email" name="email" /> </div>
</div>
<div class="form-actions">
<button type="button" id="back-btn" class="btn grey-salsa btn-outline"> Back </button>
<button type="submit" class="btn green pull-right"> Submit </button>
</div>
</form>
<!-- END FORGOT PASSWORD FORM -->
<!-- BEGIN REGISTRATION FORM -->
<form class="register-form" action="index.html" method="post">
<h3>Sign Up</h3>
<p> Enter your personal details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Full Name</label>
<div class="input-icon">
<i class="fa fa-font"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="Full Name" name="fullname" /> </div>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that
<label class="control-label visible-ie8 visible-ie9">Email</label>
<div class="input-icon">
<i class="fa fa-envelope"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="Email" name="email" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Address</label>
<div class="input-icon">
<i class="fa fa-check"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="Address" name="address" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">City/Town</label>
<div class="input-icon">
<i class="fa fa-location-arrow"></i>
<input class="form-control placeholder-no-fix" type="text" placeholder="City/Town" name="city" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Country</label>
<select name="country" id="country_list" class="select2 form-control">
<option value=""></option>
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="AZ">Azerbaijan</option>
<option value="BS">Bahamas</option>
<option value="BH">Bahrain</option>
<option value="BD">Bangladesh</option>
<option value="BB">Barbados</option>
<option value="BY">Belarus</option>
<option value="BE">Belgium</option>
<option value="BZ">Belize</option>
<option value="BJ">Benin</option>
<option value="BM">Bermuda</option>
<option value="BT">Bhutan</option>
<option value="BO">Bolivia</option>
<option value="BA">Bosnia and Herzegowina</option>
<option value="BW">Botswana</option>
<option value="BV">Bouvet Island</option>
<option value="BR">Brazil</option>
<option value="IO">British Indian Ocean Territory</option>
<option value="BN">Brunei Darussalam</option>
<option value="BG">Bulgaria</option>
<option value="BF">Burkina Faso</option>
<option value="BI">Burundi</option>
<option value="KH">Cambodia</option>
<option value="CM">Cameroon</option>
<option value="CA">Canada</option>
<option value="CV">Cape Verde</option>
<option value="KY">Cayman Islands</option>
<option value="CF">Central African Republic</option>
<option value="TD">Chad</option>
<option value="CL">Chile</option>
<option value="CN">China</option>
<option value="CX">Christmas Island</option>
<option value="CC">Cocos (Keeling) Islands</option>
<option value="CO">Colombia</option>
<option value="KM">Comoros</option>
<option value="CG">Congo</option>
<option value="CD">Congo, the Democratic Republic of the</option>
<option value="CK">Cook Islands</option>
<option value="CR">Costa Rica</option>
<option value="CI">Cote d'Ivoire</option>
<option value="HR">Croatia (Hrvatska)</option>
<option value="CU">Cuba</option>
<option value="CY">Cyprus</option>
<option value="CZ">Czech Republic</option>
<option value="DK">Denmark</option>
<option value="DJ">Djibouti</option>
<option value="DM">Dominica</option>
<option value="DO">Dominican Republic</option>
<option value="EC">Ecuador</option>
<option value="EG">Egypt</option>
<option value="SV">El Salvador</option>
<option value="GQ">Equatorial Guinea</option>
<option value="ER">Eritrea</option>
<option value="EE">Estonia</option>
<option value="ET">Ethiopia</option>
<option value="FK">Falkland Islands (Malvinas)</option>
<option value="FO">Faroe Islands</option>
<option value="FJ">Fiji</option>
<option value="FI">Finland</option>
<option value="FR">France</option>
<option value="GF">French Guiana</option>
<option value="PF">French Polynesia</option>
<option value="TF">French Southern Territories</option>
<option value="GA">Gabon</option>
<option value="GM">Gambia</option>
<option value="GE">Georgia</option>
<option value="DE">Germany</option>
<option value="GH">Ghana</option>
<option value="GI">Gibraltar</option>
<option value="GR">Greece</option>
<option value="GL">Greenland</option>
<option value="GD">Grenada</option>
<option value="GP">Guadeloupe</option>
<option value="GU">Guam</option>
<option value="GT">Guatemala</option>
<option value="GN">Guinea</option>
<option value="GW">Guinea-Bissau</option>
<option value="GY">Guyana</option>
<option value="HT">Haiti</option>
<option value="HM">Heard and Mc Donald Islands</option>
<option value="VA">Holy See (Vatican City State)</option>
<option value="HN">Honduras</option>
<option value="HK">Hong Kong</option>
<option value="HU">Hungary</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran (Islamic Republic of)</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JO">Jordan</option>
<option value="KZ">Kazakhstan</option>
<option value="KE">Kenya</option>
<option value="KI">Kiribati</option>
<option value="KP">Korea, Democratic People's Republic of</option>
<option value="KR">Korea, Republic of</option>
<option value="KW">Kuwait</option>
<option value="KG">Kyrgyzstan</option>
<option value="LA">Lao People's Democratic Republic</option>
<option value="LV">Latvia</option>
<option value="LB">Lebanon</option>
<option value="LS">Lesotho</option>
<option value="LR">Liberia</option>
<option value="LY">Libyan Arab Jamahiriya</option>
<option value="LI">Liechtenstein</option>
<option value="LT">Lithuania</option>
<option value="LU">Luxembourg</option>
<option value="MO">Macau</option>
<option value="MK">Macedonia, The Former Yugoslav Republic of</option>
<option value="MG">Madagascar</option>
<option value="MW">Malawi</option>
<option value="MY">Malaysia</option>
<option value="MV">Maldives</option>
<option value="ML">Mali</option>
<option value="MT">Malta</option>
<option value="MH">Marshall Islands</option>
<option value="MQ">Martinique</option>
<option value="MR">Mauritania</option>
<option value="MU">Mauritius</option>
<option value="YT">Mayotte</option>
<option value="MX">Mexico</option>
<option value="FM">Micronesia, Federated States of</option>
<option value="MD">Moldova, Republic of</option>
<option value="MC">Monaco</option>
<option value="MN">Mongolia</option>
<option value="MS">Montserrat</option>
<option value="MA">Morocco</option>
<option value="MZ">Mozambique</option>
<option value="MM">Myanmar</option>
<option value="NA">Namibia</option>
<option value="NR">Nauru</option>
<option value="NP">Nepal</option>
<option value="NL">Netherlands</option>
<option value="AN">Netherlands Antilles</option>
<option value="NC">New Caledonia</option>
<option value="NZ">New Zealand</option>
<option value="NI">Nicaragua</option>
<option value="NE">Niger</option>
<option value="NG">Nigeria</option>
<option value="NU">Niue</option>
<option value="NF">Norfolk Island</option>
<option value="MP">Northern Mariana Islands</option>
<option value="NO">Norway</option>
<option value="OM">Oman</option>
<option value="PK">Pakistan</option>
<option value="PW">Palau</option>
<option value="PA">Panama</option>
<option value="PG">Papua New Guinea</option>
<option value="PY">Paraguay</option>
<option value="PE">Peru</option>
<option value="PH">Philippines</option>
<option value="PN">Pitcairn</option>
<option value="PL">Poland</option>
<option value="PT">Portugal</option>
<option value="PR">Puerto Rico</option>
<option value="QA">Qatar</option>
<option value="RE">Reunion</option>
<option value="RO">Romania</option>
<option value="RU">Russian Federation</option>
<option value="RW">Rwanda</option>
<option value="KN">Saint Kitts and Nevis</option>
<option value="LC">Saint LUCIA</option>
<option value="VC">Saint Vincent and the Grenadines</option>
<option value="WS">Samoa</option>
<option value="SM">San Marino</option>
<option value="ST">Sao Tome and Principe</option>
<option value="SA">Saudi Arabia</option>
<option value="SN">Senegal</option>
<option value="SC">Seychelles</option>
<option value="SL">Sierra Leone</option>
<option value="SG">Singapore</option>
<option value="SK">Slovakia (Slovak Republic)</option>
<option value="SI">Slovenia</option>
<option value="SB">Solomon Islands</option>
<option value="SO">Somalia</option>
<option value="ZA">South Africa</option>
<option value="GS">South Georgia and the South Sandwich Islands</option>
<option value="ES">Spain</option>
<option value="LK">Sri Lanka</option>
<option value="SH">St. Helena</option>
<option value="PM">St. Pierre and Miquelon</option>
<option value="SD">Sudan</option>
<option value="SR">Suriname</option>
<option value="SJ">Svalbard and Jan Mayen Islands</option>
<option value="SZ">Swaziland</option>
<option value="SE">Sweden</option>
<option value="CH">Switzerland</option>
<option value="SY">Syrian Arab Republic</option>
<option value="TW">Taiwan, Province of China</option>
<option value="TJ">Tajikistan</option>
<option value="TZ">Tanzania, United Republic of</option>
<option value="TH">Thailand</option>
<option value="TG">Togo</option>
<option value="TK">Tokelau</option>
<option value="TO">Tonga</option>
<option value="TT">Trinidad and Tobago</option>
<option value="TN">Tunisia</option>
<option value="TR">Turkey</option>
<option value="TM">Turkmenistan</option>
<option value="TC">Turks and Caicos Islands</option>
<option value="TV">Tuvalu</option>
<option value="UG">Uganda</option>
<option value="UA">Ukraine</option>
<option value="AE">United Arab Emirates</option>
<option value="GB">United Kingdom</option>
<option value="US">United States</option>
<option value="UM">United States Minor Outlying Islands</option>
<option value="UY">Uruguay</option>
<option value="UZ">Uzbekistan</option>
<option value="VU">Vanuatu</option>
<option value="VE">Venezuela</option>
<option value="VN">Viet Nam</option>
<option value="VG">Virgin Islands (British)</option>
<option value="VI">Virgin Islands (U.S.)</option>
<option value="WF">Wallis and Futuna Islands</option>
<option value="EH">Western Sahara</option>
<option value="YE">Yemen</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
</div>
<p> Enter your account details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password" /> </div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label>
<div class="controls">
<div class="input-icon">
<i class="fa fa-check"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Re-type Your Password" name="rpassword" /> </div>
</div>
</div>
<div class="form-group">
<label class="mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="tnc" /> I agree to the
<a href="javascript:;">Terms of Service </a> &
<a href="javascript:;">Privacy Policy </a>
<span></span>
</label>
<div id="register_tnc_error"> </div>
</div>
<div class="form-actions">
<button id="register-back-btn" type="button" class="btn grey-salsa btn-outline"> Back </button>
<button type="submit" id="register-submit-btn" class="btn green pull-right"> Sign Up </button>
</div>
</form>
<!-- END REGISTRATION FORM -->
</div>
<!-- END LOGIN -->
<!--[if lt IE 9]>
<script src="../assets/global/plugins/respond.min.js"></script>
<script src="../assets/global/plugins/excanvas.min.js"></script>
<script src="../assets/global/plugins/ie8.fix.min.js"></script>
<![endif]
<!-- BEGIN CORE PLUGINS -->
<script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="../assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL SCRIPTS -->
<script src="../assets/global/scripts/app.min.js" type="text/javascript"></script>
<!-- END THEME GLOBAL SCRIPTS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../assets/pages/scripts/login.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<!-- BEGIN THEME LAYOUT SCRIPTS -->
<!-- END THEME LAYOUT SCRIPTS -->
</body>
</html>
|
<html>
<head><title>download de dados</title></head>
<body>
<h3>Dados anuais por órgão</h3>
<p><a href="2008/orgaos.json">2008</a></p>
<p><a href="2009/orgaos.json">2009</a></p>
<p><a href="2010/orgaos.json">2010</a></p>
<p><a href="2011/orgaos.json">2011</a></p>
<p><a href="2012/orgaos.json">2012</a></p>
<p><a href="2013/orgaos.json">2013</a></p>
</body>
</html>
|
// This file is part of Hermes2D.
// Hermes2D is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Hermes2D is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#include "curved.h"
#include <algorithm>
#include "global.h"
#include "shapeset/shapeset_h1_all.h"
#include "shapeset/shapeset_common.h"
#include "shapeset/precalc.h"
#include "mesh.h"
#include "quad_all.h"
#include "matrix.h"
#include "algebra/<API key>.h"
using namespace Hermes::Algebra::<API key>;
namespace Hermes
{
namespace Hermes2D
{
HERMES_API Quad1DStd g_quad_1d_std;
HERMES_API Quad2DStd g_quad_2d_std;
H1ShapesetJacobi ref_map_shapeset;
<API key> ref_map_pss_static(&ref_map_shapeset);
CurvMapStatic::CurvMapStatic()
{
int order = ref_map_shapeset.get_max_order();
this-><API key> = order - 1;
// Edges.
this->edge_proj_matrix = new_matrix<double>(<API key>, <API key>);
edge_p = malloc_with_check<double>(<API key>);
// Bubbles - triangles.
this->tri_bubble_np = ref_map_shapeset.get_num_bubbles(order, <API key>);
<API key> = new_matrix<double>(tri_bubble_np, tri_bubble_np);
bubble_tri_p = malloc_with_check<double>(tri_bubble_np);
// Bubbles - quads.
order = H2D_MAKE_QUAD_ORDER(order, order);
this->quad_bubble_np = ref_map_shapeset.get_num_bubbles(order, HERMES_MODE_QUAD);
<API key> = new_matrix<double>(quad_bubble_np, quad_bubble_np);
bubble_quad_p = malloc_with_check<double>(quad_bubble_np);
this-><API key>();
this-><API key>();
}
CurvMapStatic::~CurvMapStatic()
{
free_with_check(edge_proj_matrix, true);
free_with_check(<API key>, true);
free_with_check(<API key>, true);
free_with_check(edge_p);
free_with_check(bubble_tri_p);
free_with_check(bubble_quad_p);
}
double** CurvMapStatic::<API key>(short* indices, ElementMode2D mode)
{
unsigned short nb;
double** mat;
if (mode == <API key>)
{
mat = this-><API key>;
nb = this->tri_bubble_np;
}
else
{
mat = this-><API key>;
nb = this->quad_bubble_np;
}
<API key> <API key>(&ref_map_shapeset);
<API key>.set_active_element(ref_map_pss_static.get_active_element());
for (unsigned short i = 0; i < nb; i++)
{
for (unsigned short j = i; j < nb; j++)
{
short ii = indices[i], ij = indices[j];
unsigned short o = ref_map_shapeset.get_order(ii, mode) + ref_map_shapeset.get_order(ij, mode);
o = std::max(H2D_GET_V_ORDER(o), H2D_GET_H_ORDER(o));
ref_map_pss_static.set_active_shape(ii);
ref_map_pss_static.set_quad_order(o, H2D_FN_VAL);
const double* fni = ref_map_pss_static.get_fn_values();
<API key>.set_active_shape(ij);
<API key>.set_quad_order(o, H2D_FN_VAL);
const double* fnj = <API key>.get_fn_values();
double3* pt = g_quad_2d_std.get_points(o, mode);
double val = 0.0;
for (unsigned short k = 0; k < g_quad_2d_std.get_num_points(o, mode); k++)
val += pt[k][2] * (fni[k] * fnj[k]);
mat[i][j] = mat[j][i] = val;
}
}
return mat;
}
void CurvMapStatic::<API key>()
{
// calculate projection matrix of maximum order
{
Element e;
e.nvert = 3;
e.cm = nullptr;
e.id = -1;
ref_map_pss_static.set_active_element(&e);
short* indices = ref_map_shapeset.get_bubble_indices(ref_map_shapeset.get_max_order(), <API key>);
curvMapStatic.<API key> = <API key>(indices, <API key>);
// cholesky factorization of the matrix
choldc(curvMapStatic.<API key>, this->tri_bubble_np, curvMapStatic.bubble_tri_p);
}
// calculate projection matrix of maximum order
{
Element e;
e.nvert = 4;
e.cm = nullptr;
e.id = -1;
ref_map_pss_static.set_active_element(&e);
short *indices = ref_map_shapeset.get_bubble_indices(H2D_MAKE_QUAD_ORDER(ref_map_shapeset.get_max_order(), ref_map_shapeset.get_max_order()), HERMES_MODE_QUAD);
curvMapStatic.<API key> = <API key>(indices, HERMES_MODE_QUAD);
// cholesky factorization of the matrix
choldc(curvMapStatic.<API key>, this->quad_bubble_np, curvMapStatic.bubble_quad_p);
}
}
void CurvMapStatic::<API key>()
{
// calculate projection matrix of maximum order
for (int i = 0; i < this-><API key>; i++)
{
for (int j = i; j < this-><API key>; j++)
{
int o = i + j + 4;
double2* pt = g_quad_1d_std.get_points(o);
double val = 0.0;
for (int k = 0; k < g_quad_1d_std.get_num_points(o); k++)
{
double fi = 0;
double fj = 0;
double x = pt[k][0];
switch (i + 2)
{
case 0:
fi = l0(x);
break;
case 1:
fi = l1(x);
break;
case 2:
fi = l2(x);
break;
case 3:
fi = l3(x);
break;
case 4:
fi = l4(x);
break;
case 5:
fi = l5(x);
break;
case 6:
fi = l6(x);
break;
case 7:
fi = l7(x);
break;
case 8:
fi = l8(x);
break;
case 9:
fi = l9(x);
break;
case 10:
fi = l10(x);
break;
case 11:
fi = l11(x);
break;
}
switch (j + 2)
{
case 0:
fj = l0(x);
break;
case 1:
fj = l1(x);
break;
case 2:
fj = l2(x);
break;
case 3:
fj = l3(x);
break;
case 4:
fj = l4(x);
break;
case 5:
fj = l5(x);
break;
case 6:
fj = l6(x);
break;
case 7:
fj = l7(x);
break;
case 8:
fj = l8(x);
break;
case 9:
fj = l9(x);
break;
case 10:
fj = l10(x);
break;
case 11:
fj = l11(x);
break;
}
val += pt[k][1] * (fi * fj);
}
this->edge_proj_matrix[i][j] = this->edge_proj_matrix[j][i] = val;
}
}
// Cholesky factorization of the matrix
choldc(this->edge_proj_matrix, this-><API key>, this->edge_p);
}
CurvMapStatic curvMapStatic;
Curve::Curve(CurvType type) : type(type)
{
}
Curve::~Curve()
{
}
Arc::Arc() : Curve(ArcType)
{
kv[0] = kv[1] = kv[2] = 0;
kv[3] = kv[4] = kv[5] = 1;
}
Arc::Arc(double angle) : Curve(ArcType), angle(angle)
{
kv[0] = kv[1] = kv[2] = 0;
kv[3] = kv[4] = kv[5] = 1;
}
Arc::Arc(const Arc* other) : Curve(ArcType)
{
this->angle = other->angle;
memcpy(this->kv, other->kv, 6 * sizeof(double));
memcpy(this->pt, other->pt, 3 * sizeof(double3));
}
Nurbs::Nurbs() : Curve(NurbsType)
{
pt = nullptr;
kv = nullptr;
};
Nurbs::~Nurbs()
{
free_with_check(pt);
free_with_check(kv);
};
Nurbs::Nurbs(const Nurbs* other) : Curve(NurbsType)
{
this->degree = other->degree;
this->nk = other->nk;
this->np = other->np;
this->kv = malloc_with_check<double>(nk);
this->pt = malloc_with_check<double3>(np);
}
static double lambda_0(double x, double y)
{
return -0.5 * (x + y);
}
static double lambda_1(double x, double y)
{
return 0.5 * (x + 1);
}
static double lambda_2(double x, double y)
{
return 0.5 * (y + 1);
}
CurvMap::CurvMap() : ref_map_pss(&ref_map_shapeset)
{
coeffs = nullptr;
ctm = nullptr;
memset(curves, 0, sizeof(Curve*)* <API key>);
this->parent = nullptr;
this->sub_idx = 0;
}
CurvMap::CurvMap(const CurvMap* cm) : ref_map_pss(&ref_map_shapeset)
{
this->nc = cm->nc;
this->order = cm->order;
\todo Find out if this is safe.
this->ctm = cm->ctm;
this->coeffs = malloc_with_check<double2>(nc, true);
memcpy(coeffs, cm->coeffs, sizeof(double2)* nc);
this->toplevel = cm->toplevel;
if (this->toplevel)
{
for (int i = 0; i < 4; i++)
{
if (cm->curves[i])
{
if (cm->curves[i]->type == NurbsType)
this->curves[i] = new Nurbs((Nurbs*)cm->curves[i]);
else
this->curves[i] = new Arc((Arc*)cm->curves[i]);
}
else
this->curves[i] = nullptr;
}
this->parent = nullptr;
this->sub_idx = 0;
}
else
{
memset(curves, 0, sizeof(Curve*)* <API key>);
this->parent = cm->parent;
this->sub_idx = cm->sub_idx;
}
}
CurvMap::~CurvMap()
{
this->free();
}
void CurvMap::free()
{
free_with_check(this->coeffs, true);
if (toplevel)
{
for (int i = 0; i < 4; i++)
if (curves[i])
{
delete curves[i];
curves[i] = nullptr;
}
}
}
double CurvMap::nurbs_basis_fn(unsigned short i, unsigned short k, double t, double* knot)
{
if (k == 0)
{
return (t >= knot[i] && t <= knot[i + 1] && knot[i] < knot[i + 1]) ? 1.0 : 0.0;
}
else
{
double N1 = nurbs_basis_fn(i, k - 1, t, knot);
double N2 = nurbs_basis_fn(i + 1, k - 1, t, knot);
if ((N1 > HermesEpsilon) || (N2 > HermesEpsilon))
{
double result = 0.0;
if ((N1 > HermesEpsilon) && knot[i + k] != knot[i])
result += ((t - knot[i]) / (knot[i + k] - knot[i])) * N1;
if ((N2 > HermesEpsilon) && knot[i + k + 1] != knot[i + 1])
result += ((knot[i + k + 1] - t) / (knot[i + k + 1] - knot[i + 1])) * N2;
return result;
}
else
return 0.0;
}
}
void CurvMap::nurbs_edge(Element* e, Curve* curve, int edge, double t, double& x,
double& y)
{
// Nurbs curves are parametrized from 0 to 1.
t = (t + 1.0) / 2.0;
// Start point A, end point B.
double2 A = { e->vn[edge]->x, e->vn[edge]->y };
double2 B = { e->vn[e->next_vert(edge)]->x, e->vn[e->next_vert(edge)]->y };
// Vector pointing from A to B.
double2 v = { B[0] - A[0], B[1] - A[1] };
// Straight line.
if (!curve)
{
x = A[0] + t * v[0];
y = A[1] + t * v[1];
}
else
{
double3* cp;
int degree, np;
double* kv;
if (curve->type == ArcType)
{
cp = ((Arc*)curve)->pt;
np = ((Arc*)curve)->np;
degree = ((Arc*)curve)->degree;
kv = ((Arc*)curve)->kv;
}
else
{
cp = ((Nurbs*)curve)->pt;
np = ((Nurbs*)curve)->np;
degree = ((Nurbs*)curve)->degree;
kv = ((Nurbs*)curve)->kv;
}
// sum of basis fns and weights
double sum = 0.0;
x = y = 0.0;
for (int i = 0; i < np; i++)
{
double basis = nurbs_basis_fn(i, degree, t, kv);
sum += cp[i][2] * basis;
double x_i = cp[i][0];
double y_i = cp[i][1];
double w_i = cp[i][2];
x += w_i * basis * x_i;
y += w_i * basis * y_i;
}
x /= sum;
y /= sum;
}
}
const double2 CurvMap::ref_vert[2][<API key>] =
{
{ { -1.0, -1.0 }, { 1.0, -1.0 }, { -1.0, 1.0 }, { 0.0, 0.0 } },
{ { -1.0, -1.0 }, { 1.0, -1.0 }, { 1.0, 1.0 }, { -1.0, 1.0 } }
};
void CurvMap::nurbs_edge_0(Element* e, Curve* curve, unsigned short edge, double t, double& x, double& y, double& n_x, double& n_y, double& t_x, double& t_y)
{
unsigned short va = edge;
unsigned short vb = e->next_vert(edge);
nurbs_edge(e, curve, edge, t, x, y);
x -= 0.5 * ((1 - t) * (e->vn[va]->x) + (1 + t) * (e->vn[vb]->x));
y -= 0.5 * ((1 - t) * (e->vn[va]->y) + (1 + t) * (e->vn[vb]->y));
double k = 4.0 / ((1 - t) * (1 + t));
x *= k;
y *= k;
}
void CurvMap::calc_ref_map_tri(Element* e, Curve** curve, double xi_1, double xi_2, double& x, double& y)
{
double fx, fy;
x = y = 0.0;
double l[3] = { lambda_0(xi_1, xi_2), lambda_1(xi_1, xi_2), lambda_2(xi_1, xi_2) };
for (unsigned char j = 0; j < e->get_nvert(); j++)
{
int va = j;
int vb = e->next_vert(j);
double la = l[va];
double lb = l[vb];
// vertex part
x += e->vn[j]->x * la;
y += e->vn[j]->y * la;
if (!(((ref_vert[0][va][0] == xi_1) && (ref_vert[0][va][1] == xi_2)) || ((ref_vert[0][vb][0] == xi_1) && (ref_vert[0][vb][1] == xi_2))))
{
// edge part
double t = lb - la;
double n_x, n_y, t_x, t_y;
nurbs_edge_0(e, curve[j], j, t, fx, fy, n_x, n_y, t_x, t_y);
x += fx * lb * la;
y += fy * lb * la;
}
}
}
void CurvMap::calc_ref_map_quad(Element* e, Curve** curve, double xi_1, double xi_2,
double& x, double& y)
{
double ex[<API key>], ey[<API key>];
nurbs_edge(e, curve[0], 0, xi_1, ex[0], ey[0]);
nurbs_edge(e, curve[1], 1, xi_2, ex[1], ey[1]);
nurbs_edge(e, curve[2], 2, -xi_1, ex[2], ey[2]);
nurbs_edge(e, curve[3], 3, -xi_2, ex[3], ey[3]);
x = (1 - xi_2) / 2.0 * ex[0] + (1 + xi_1) / 2.0 * ex[1] +
(1 + xi_2) / 2.0 * ex[2] + (1 - xi_1) / 2.0 * ex[3] -
(1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->x - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->x -
(1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->x - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->x;
y = (1 - xi_2) / 2.0 * ey[0] + (1 + xi_1) / 2.0 * ey[1] +
(1 + xi_2) / 2.0 * ey[2] + (1 - xi_1) / 2.0 * ey[3] -
(1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->y - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->y -
(1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->y - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->y;
}
void CurvMap::calc_ref_map(Element* e, Curve** curve, double xi_1, double xi_2, double2& f)
{
if (e->get_mode() == HERMES_MODE_QUAD)
calc_ref_map_quad(e, curve, xi_1, xi_2, f[0], f[1]);
else
calc_ref_map_tri(e, curve, xi_1, xi_2, f[0], f[1]);
}
void CurvMap::edge_coord(Element* e, unsigned short edge, double t, double2& x) const
{
unsigned short mode = e->get_mode();
double2 a, b;
a[0] = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0];
a[1] = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1];
b[0] = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0];
b[1] = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1];
for (int i = 0; i < 2; i++)
{
x[i] = a[i] + (t + 1.0) / 2.0 * (b[i] - a[i]);
}
}
void CurvMap::<API key>(Element* e, unsigned short edge, Curve** nurbs, unsigned short order, double2* proj) const
{
unsigned short i, j, k;
unsigned short mo1 = g_quad_1d_std.get_max_order();
unsigned char np = g_quad_1d_std.get_num_points(mo1);
unsigned short ne = order - 1;
unsigned short mode = e->get_mode();
assert(np <= 15 && ne <= 10);
double2 fn[15];
double rhside[2][10];
memset(rhside[0], 0, sizeof(double)* ne);
memset(rhside[1], 0, sizeof(double)* ne);
double a_1, a_2, b_1, b_2;
a_1 = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0];
a_2 = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1];
b_1 = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0];
b_2 = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1];
// values of nonpolynomial function in two vertices
double2 fa, fb;
calc_ref_map(e, nurbs, a_1, a_2, fa);
calc_ref_map(e, nurbs, b_1, b_2, fb);
double2* pt = g_quad_1d_std.get_points(mo1);
// over all integration points
for (j = 0; j < np; j++)
{
double2 x;
double t = pt[j][0];
edge_coord(e, edge, t, x);
calc_ref_map(e, nurbs, x[0], x[1], fn[j]);
for (k = 0; k < 2; k++)
fn[j][k] = fn[j][k] - (fa[k] + (t + 1) / 2.0 * (fb[k] - fa[k]));
}
double2* result = proj + e->get_nvert() + edge * (order - 1);
for (k = 0; k < 2; k++)
{
for (i = 0; i < ne; i++)
{
for (j = 0; j < np; j++)
{
double t = pt[j][0];
double fi = 0;
switch (i + 2)
{
case 0:
fi = l0(t);
break;
case 1:
fi = l1(t);
break;
case 2:
fi = l2(t);
break;
case 3:
fi = l3(t);
break;
case 4:
fi = l4(t);
break;
case 5:
fi = l5(t);
break;
case 6:
fi = l6(t);
break;
case 7:
fi = l7(t);
break;
case 8:
fi = l8(t);
break;
case 9:
fi = l9(t);
break;
case 10:
fi = l10(t);
break;
case 11:
fi = l11(t);
break;
}
rhside[k][i] += pt[j][1] * (fi * fn[j][k]);
}
}
// solve
cholsl(curvMapStatic.edge_proj_matrix, ne, curvMapStatic.edge_p, rhside[k], rhside[k]);
for (i = 0; i < ne; i++)
result[i][k] = rhside[k][i];
}
}
void CurvMap::old_projection(Element* e, unsigned short order, double2* proj, double* old[2])
{
unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode());
unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode());
unsigned short nvert = e->get_nvert();
for (unsigned int k = 0; k < nvert; k++) // loop over vertices
{
// vertex basis functions in all integration points
int index_v = ref_map_shapeset.get_vertex_index(k, e->get_mode());
ref_map_pss.set_active_shape(index_v);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double* vd = ref_map_pss.get_fn_values();
for (int m = 0; m < 2; m++) // part 0 or 1
for (int j = 0; j < np; j++)
old[m][j] += proj[k][m] * vd[j];
for (int ii = 0; ii < order - 1; ii++)
{
// edge basis functions in all integration points
int index_e = ref_map_shapeset.get_edge_index(k, 0, ii + 2, e->get_mode());
ref_map_pss.set_active_shape(index_e);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double* ed = ref_map_pss.get_fn_values();
for (int m = 0; m < 2; m++) //part 0 or 1
for (int j = 0; j < np; j++)
old[m][j] += proj[nvert + k * (order - 1) + ii][m] * ed[j];
}
}
}
void CurvMap::<API key>(Element* e, Curve** curve, unsigned short order, double2* proj)
{
ref_map_pss.set_active_element(e);
unsigned short i, j, k;
unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode());
unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode());
unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order;
unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode());
double2* fn = new double2[np];
memset(fn, 0, np * sizeof(double2));
double* rhside[2];
double* old[2];
for (i = 0; i < 2; i++)
{
rhside[i] = new double[nb];
old[i] = new double[np];
memset(rhside[i], 0, sizeof(double)* nb);
memset(old[i], 0, sizeof(double)* np);
}
// compute known part of projection (vertex and edge part)
old_projection(e, order, proj, old);
// fn values of both components of nonpolynomial function
double3* pt = g_quad_2d_std.get_points(mo2, e->get_mode());
for (j = 0; j < np; j++) // over all integration points
{
double2 a;
a[0] = ctm->m[0] * pt[j][0] + ctm->t[0];
a[1] = ctm->m[1] * pt[j][1] + ctm->t[1];
calc_ref_map(e, curve, a[0], a[1], fn[j]);
}
double2* result = proj + e->get_nvert() + e->get_nvert() * (order - 1);
for (k = 0; k < 2; k++)
{
for (i = 0; i < nb; i++) // loop over bubble basis functions
{
// bubble basis functions in all integration points
int index_i = ref_map_shapeset.get_bubble_indices(qo, e->get_mode())[i];
ref_map_pss.set_active_shape(index_i);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double *bfn = ref_map_pss.get_fn_values();
for (j = 0; j < np; j++) // over all integration points
rhside[k][i] += pt[j][2] * (bfn[j] * (fn[j][k] - old[k][j]));
}
// solve
if (e->get_mode() == <API key>)
cholsl(curvMapStatic.<API key>, nb, curvMapStatic.bubble_tri_p, rhside[k], rhside[k]);
else
cholsl(curvMapStatic.<API key>, nb, curvMapStatic.bubble_quad_p, rhside[k], rhside[k]);
for (i = 0; i < nb; i++)
result[i][k] = rhside[k][i];
}
for (i = 0; i < 2; i++)
{
delete[] rhside[i];
delete[] old[i];
}
delete[] fn;
}
void CurvMap::<API key>(Element* e)
{
ref_map_pss.set_quad_2d(&g_quad_2d_std);
ref_map_pss.set_active_element(e);
// allocate projection coefficients
unsigned char nvert = e->get_nvert();
unsigned char ne = order - 1;
unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order;
unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode());
this->nc = nvert + nvert*ne + nb;
this->coeffs = realloc_with_check<double2>(this->coeffs, nc);
// WARNING: do not change the format of the array 'coeffs'. If it changes,
// RefMap::set_active_element() has to be changed too.
Curve** curves;
if (toplevel == false)
{
ref_map_pss.set_active_element(e);
ref_map_pss.set_transform(this->sub_idx);
curves = parent->cm->curves;
}
else
{
ref_map_pss.reset_transform();
curves = e->cm->curves;
}
ctm = ref_map_pss.get_ctm();
// calculation of new_ projection coefficients
// vertex part
for (unsigned char i = 0; i < nvert; i++)
{
coeffs[i][0] = e->vn[i]->x;
coeffs[i][1] = e->vn[i]->y;
}
if (!e->cm->toplevel)
e = e->cm->parent;
// edge part
for (unsigned char edge = 0; edge < nvert; edge++)
<API key>(e, edge, curves, order, coeffs);
//bubble part
<API key>(e, curves, order, coeffs);
}
void CurvMap::get_mid_edge_points(Element* e, double2* pt, unsigned short n)
{
Curve** curves = this->curves;
Transformable tran;
tran.set_active_element(e);
if (toplevel == false)
{
tran.set_transform(this->sub_idx);
e = e->cm->parent;
curves = e->cm->curves;
}
ctm = tran.get_ctm();
double xi_1, xi_2;
for (unsigned short i = 0; i < n; i++)
{
xi_1 = ctm->m[0] * pt[i][0] + ctm->t[0];
xi_2 = ctm->m[1] * pt[i][1] + ctm->t[1];
calc_ref_map(e, curves, xi_1, xi_2, pt[i]);
}
}
CurvMap* CurvMap::create_son_curv_map(Element* e, int son)
{
// if the top three bits of part are nonzero, we would overflow
// -- make the element non-curvilinear
if (e->cm->sub_idx & <API key>)
return nullptr;
// if the parent element is already almost straight-edged,
// the son will be even more straight-edged
if (e->iro_cache == 0)
return nullptr;
CurvMap* cm = new CurvMap;
if (e->cm->toplevel == false)
{
cm->parent = e->cm->parent;
cm->sub_idx = (e->cm->sub_idx << 3) + son + 1;
}
else
{
cm->parent = e;
cm->sub_idx = (son + 1);
}
cm->toplevel = false;
cm->order = 4;
return cm;
}
}
}
|
<!
This file is a part of MediaDrop (http:
Copyright 2009-2014 MediaDrop contributors
For the exact contribution history, see the git revision log.
The source code contained in this file is licensed under the GPLv3 or
(at your option) any later version.
See LICENSE.txt in the main project directory, for more information.
<form xmlns="http:
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http:
id="${id}"
name="${name}"
action="${action}"
method="${method}"
class="${css_class}"
py:attrs="attrs">
<xi:include href="../helpers.html" />
<span py:if="error and not error.error_dict" class="field-error" py:content="error" />
<table class="field-list" py:attrs="list_attrs">
<tbody>
<py:for each="i, field in enumerate(fields)"
py:with="required = field.is_required and ' required' or None;
help_url = getattr(field, 'help_url', None);
is_submit = getattr(field, 'type', None) == 'submit';
render_label = show_labels and not field.suppress_label;
render_error = error is not None and not field.show_error;">
<tr py:if="field.name == 'url'">
<td>
<br />
<div class="field-error"
py:if="'_the_form' in tmpl_context.form_errors"
py:content="tmpl_context.form_errors['_the_form']">
Display the error from the media controller, if any
</div>
</td>
</tr>
<tr class="title" py:if="render_label and not (is_submit or field.show_error)">
<td>
<label py:if="render_label" py:content="field.label_text and _(field.label_text) or None" id="${field.id}-label" class="form-label" for="${field.id}" />
<a py:if="field.help_text and help_url" py:content="field.help_text and _(field.help_text) or None" href="${help_url}" class="field-help" />
<span py:if="field.help_text and not help_url" py:content="field.help_text and _(field.help_text) or None" class="field-help" />
<span py:if="not field.show_error" class="field-error" py:content="error_for(field)" />
</td>
</tr>
<tr>
<td class="${render_error and (error_for(field) is not None and 'err' or 'noerr') or ''}">
${field.display(value_for(field), **args_for(field))}
<!-- The following 4 elements are used only by the SwiffUploadManager javascript -->
<div py:if="field.name == 'file'" id="bottombar">
<button id="browse-button" class="mcore-btn f-lft"><span>Choose a file to upload</span></button>
<div id="file-info" class="f-lft" />
</div>
</td>
</tr>
<tr py:if="field.name == 'description'" class="${field.name}-rel">
<td py:content="xhtml_description('description')" />
</tr>
</py:for>
</tbody>
</table>
</form>
|
using WowPacketParser.Enums;
using WowPacketParser.Hotfix;
namespace <API key>.V8_0_1_27101.Hotfix
{
[HotfixStructure(DB2Hash.WorldEffect, HasIndexInData = false)]
public class WorldEffectEntry
{
public uint <API key> { get; set; }
public byte WhenToDisplay { get; set; }
public sbyte TargetType { get; set; }
public int TargetAsset { get; set; }
public uint PlayerConditionID { get; set; }
public ushort CombatConditionID { get; set; }
}
}
|
<?php
namespace Magento\Framework\Interception\ObjectManager\Config;
use Magento\Framework\Interception\ObjectManager\ConfigInterface;
use Magento\Framework\ObjectManager\DefinitionInterface;
use Magento\Framework\ObjectManager\RelationsInterface;
use Magento\Framework\ObjectManager\<API key>;
class Developer extends \Magento\Framework\ObjectManager\Config\Config implements ConfigInterface
{
/**
* @var <API key>
*/
private $<API key>;
/**
* @param RelationsInterface $relations
* @param DefinitionInterface $definitions
* @param <API key> $<API key>
*/
public function __construct(
RelationsInterface $relations = null,
DefinitionInterface $definitions = null,
<API key> $<API key> = null
) {
$this-><API key> = $<API key> ?: new <API key>();
parent::__construct($relations, $definitions);
}
/**
* @var \Magento\Framework\Interception\ConfigInterface
*/
protected $interceptionConfig;
/**
* Set Interception config
*
* @param \Magento\Framework\Interception\ConfigInterface $interceptionConfig
* @return void
*/
public function <API key>(\Magento\Framework\Interception\ConfigInterface $interceptionConfig)
{
$this->interceptionConfig = $interceptionConfig;
}
/**
* Retrieve instance type with interception processing
*
* @param string $instanceName
* @return string
*/
public function getInstanceType($instanceName)
{
$type = parent::getInstanceType($instanceName);
if ($this->interceptionConfig && $this->interceptionConfig->hasPlugins($instanceName)
&& $this-><API key>->validate($instanceName)
) {
return $type . '\\Interceptor';
}
return $type;
}
/**
* Retrieve instance type without interception processing
*
* @param string $instanceName
* @return string
*/
public function <API key>($instanceName)
{
return parent::getInstanceType($instanceName);
}
}
|
<?php
namespace TYPO3\Neos\Routing;
use TYPO3\Flow\Annotations as Flow;
/**
* A route part handler for finding nodes specifically in the website's frontend.
*
* @Flow\Scope("singleton")
*/
class <API key> extends \TYPO3\Flow\Mvc\Routing\DynamicRoutePart
{
/**
* @Flow\Inject
* @var \TYPO3\Flow\Persistence\<API key>
*/
protected $persistenceManager;
/**
* Iterate through the configured modules, find the matching module and set
* the route path accordingly
*
* @param array $value (contains action, controller and package of the module controller)
* @return boolean
*/
protected function resolveValue($value)
{
if (is_array($value)) {
$this->value = isset($value['@action']) && $value['@action'] !== 'index' ? $value['@action'] : '';
if ($this->value !== '' && isset($value['@format'])) {
$this->value .= '.' . $value['@format'];
}
$exceedingArguments = array();
foreach ($value as $argumentKey => $argumentValue) {
if (substr($argumentKey, 0, 1) !== '@' && substr($argumentKey, 0, 2) !== '__') {
$exceedingArguments[$argumentKey] = $argumentValue;
}
}
if ($exceedingArguments !== array()) {
$exceedingArguments = \TYPO3\Flow\Utility\Arrays::<API key>($exceedingArguments);
$exceedingArguments = $this->persistenceManager-><API key>($exceedingArguments);
$queryString = http_build_query(array($this->name => $exceedingArguments), null, '&');
if ($queryString !== '') {
$this->value .= '?' . $queryString;
}
}
}
return true;
}
}
|
#include "meshSearch.H"
#include "polyMesh.H"
#include "indexedOctree.H"
#include "DynamicList.H"
#include "demandDrivenData.H"
#include "treeDataCell.H"
#include "treeDataFace.H"
#include "treeDataPoint.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
<API key>(Foam::meshSearch, 0);
Foam::scalar Foam::meshSearch::tol_ = 1E-3;
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
bool Foam::meshSearch::findNearer
(
const point& sample,
const pointField& points,
label& nearestI,
scalar& nearestDistSqr
)
{
bool nearer = false;
forAll(points, pointI)
{
scalar distSqr = magSqr(points[pointI] - sample);
if (distSqr < nearestDistSqr)
{
nearestDistSqr = distSqr;
nearestI = pointI;
nearer = true;
}
}
return nearer;
}
bool Foam::meshSearch::findNearer
(
const point& sample,
const pointField& points,
const labelList& indices,
label& nearestI,
scalar& nearestDistSqr
)
{
bool nearer = false;
forAll(indices, i)
{
label pointI = indices[i];
scalar distSqr = magSqr(points[pointI] - sample);
if (distSqr < nearestDistSqr)
{
nearestDistSqr = distSqr;
nearestI = pointI;
nearer = true;
}
}
return nearer;
}
// tree based searching
Foam::label Foam::meshSearch::findNearestCellTree(const point& location) const
{
const indexedOctree<treeDataPoint>& tree = cellCentreTree();
scalar span = tree.bb().mag();
pointIndexHit info = tree.findNearest(location, Foam::sqr(span));
if (!info.hit())
{
info = tree.findNearest(location, Foam::sqr(GREAT));
}
return info.index();
}
// linear searching
Foam::label Foam::meshSearch::<API key>(const point& location) const
{
const vectorField& centres = mesh_.cellCentres();
label nearestIndex = 0;
scalar minProximity = magSqr(centres[nearestIndex] - location);
findNearer
(
location,
centres,
nearestIndex,
minProximity
);
return nearestIndex;
}
// walking from seed
Foam::label Foam::meshSearch::findNearestCellWalk
(
const point& location,
const label seedCellI
) const
{
if (seedCellI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestCellWalk(const point&, const label)"
) << "illegal seedCell:" << seedCellI << exit(FatalError);
}
// Walk in direction of face that decreases distance
label curCellI = seedCellI;
scalar distanceSqr = magSqr(mesh_.cellCentres()[curCellI] - location);
bool closer;
do
{
// Try neighbours of curCellI
closer = findNearer
(
location,
mesh_.cellCentres(),
mesh_.cellCells()[curCellI],
curCellI,
distanceSqr
);
} while (closer);
return curCellI;
}
// tree based searching
Foam::label Foam::meshSearch::findNearestFaceTree(const point& location) const
{
// Search nearest cell centre.
const indexedOctree<treeDataPoint>& tree = cellCentreTree();
scalar span = tree.bb().mag();
// Search with decent span
pointIndexHit info = tree.findNearest(location, Foam::sqr(span));
if (!info.hit())
{
// Search with desparate span
info = tree.findNearest(location, Foam::sqr(GREAT));
}
// Now check any of the faces of the nearest cell
const vectorField& centres = mesh_.faceCentres();
const cell& ownFaces = mesh_.cells()[info.index()];
label nearestFaceI = ownFaces[0];
scalar minProximity = magSqr(centres[nearestFaceI] - location);
findNearer
(
location,
centres,
ownFaces,
nearestFaceI,
minProximity
);
return nearestFaceI;
}
// linear searching
Foam::label Foam::meshSearch::<API key>(const point& location) const
{
const vectorField& centres = mesh_.faceCentres();
label nearestFaceI = 0;
scalar minProximity = magSqr(centres[nearestFaceI] - location);
findNearer
(
location,
centres,
nearestFaceI,
minProximity
);
return nearestFaceI;
}
// walking from seed
Foam::label Foam::meshSearch::findNearestFaceWalk
(
const point& location,
const label seedFaceI
) const
{
if (seedFaceI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestFaceWalk(const point&, const label)"
) << "illegal seedFace:" << seedFaceI << exit(FatalError);
}
const vectorField& centres = mesh_.faceCentres();
// Walk in direction of face that decreases distance
label curFaceI = seedFaceI;
scalar distanceSqr = magSqr(centres[curFaceI] - location);
while (true)
{
label betterFaceI = curFaceI;
findNearer
(
location,
centres,
mesh_.cells()[mesh_.faceOwner()[curFaceI]],
betterFaceI,
distanceSqr
);
if (mesh_.isInternalFace(curFaceI))
{
findNearer
(
location,
centres,
mesh_.cells()[mesh_.faceNeighbour()[curFaceI]],
betterFaceI,
distanceSqr
);
}
if (betterFaceI == curFaceI)
{
break;
}
curFaceI = betterFaceI;
}
return curFaceI;
}
Foam::label Foam::meshSearch::findCellLinear(const point& location) const
{
bool cellFound = false;
label n = 0;
label cellI = -1;
while ((!cellFound) && (n < mesh_.nCells()))
{
if (pointInCell(location, n))
{
cellFound = true;
cellI = n;
}
else
{
n++;
}
}
if (cellFound)
{
return cellI;
}
else
{
return -1;
}
}
Foam::label Foam::meshSearch::<API key>
(
const point& location,
const label seedFaceI
) const
{
if (seedFaceI < 0)
{
FatalErrorIn
(
"meshSearch::<API key>"
"(const point&, const label)"
) << "illegal seedFace:" << seedFaceI << exit(FatalError);
}
// Start off from seedFaceI
label curFaceI = seedFaceI;
const face& f = mesh_.faces()[curFaceI];
scalar minDist = f.nearestPoint
(
location,
mesh_.points()
).distance();
bool closer;
do
{
closer = false;
// Search through all neighbouring boundary faces by going
// across edges
label lastFaceI = curFaceI;
const labelList& myEdges = mesh_.faceEdges()[curFaceI];
forAll (myEdges, myEdgeI)
{
const labelList& neighbours = mesh_.edgeFaces()[myEdges[myEdgeI]];
// Check any face which uses edge, is boundary face and
// is not curFaceI itself.
forAll(neighbours, nI)
{
label faceI = neighbours[nI];
if
(
(faceI >= mesh_.nInternalFaces())
&& (faceI != lastFaceI)
)
{
const face& f = mesh_.faces()[faceI];
pointHit curHit = f.nearestPoint
(
location,
mesh_.points()
);
// If the face is closer, reset current face and distance
if (curHit.distance() < minDist)
{
minDist = curHit.distance();
curFaceI = faceI;
closer = true; // a closer neighbour has been found
}
}
}
}
} while (closer);
return curFaceI;
}
Foam::vector Foam::meshSearch::offset
(
const point& bPoint,
const label bFaceI,
const vector& dir
) const
{
// Get the neighbouring cell
label ownerCellI = mesh_.faceOwner()[bFaceI];
const point& c = mesh_.cellCentres()[ownerCellI];
// Typical dimension: distance from point on face to cell centre
scalar typDim = mag(c - bPoint);
return tol_*typDim*dir;
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from components
Foam::meshSearch::meshSearch(const polyMesh& mesh, const bool faceDecomp)
:
mesh_(mesh),
faceDecomp_(faceDecomp),
cloud_(mesh_, IDLList<passiveParticle>()),
boundaryTreePtr_(NULL),
cellTreePtr_(NULL),
cellCentreTreePtr_(NULL)
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::meshSearch::~meshSearch()
{
clearOut();
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
const Foam::indexedOctree<Foam::treeDataFace>& Foam::meshSearch::boundaryTree()
const
{
if (!boundaryTreePtr_)
{
// Construct tree
// all boundary faces (not just walls)
labelList bndFaces(mesh_.nFaces()-mesh_.nInternalFaces());
forAll(bndFaces, i)
{
bndFaces[i] = mesh_.nInternalFaces() + i;
}
treeBoundBox overallBb(mesh_.points());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
boundaryTreePtr_ = new indexedOctree<treeDataFace>
(
treeDataFace // all information needed to search faces
(
false, // do not cache bb
mesh_,
bndFaces // boundary faces only
),
overallBb, // overall search domain
8, // maxLevel
10, // leafsize
3.0 // duplicity
);
}
return *boundaryTreePtr_;
}
const Foam::indexedOctree<Foam::treeDataCell>& Foam::meshSearch::cellTree()
const
{
if (!cellTreePtr_)
{
// Construct tree
treeBoundBox overallBb(mesh_.points());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
cellTreePtr_ = new indexedOctree<treeDataCell>
(
treeDataCell
(
false, // not cache bb
mesh_
),
overallBb, // overall search domain
8, // maxLevel
10, // leafsize
3.0 // duplicity
);
}
return *cellTreePtr_;
}
const Foam::indexedOctree<Foam::treeDataPoint>&
Foam::meshSearch::cellCentreTree() const
{
if (!cellCentreTreePtr_)
{
// Construct tree
treeBoundBox overallBb(mesh_.cellCentres());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
cellCentreTreePtr_ = new indexedOctree<treeDataPoint>
(
treeDataPoint(mesh_.cellCentres()),
overallBb, // overall search domain
10, // max levels
10.0, // maximum ratio of cubes v.s. cells
100.0 // max. duplicity; n/a since no bounding boxes.
);
}
return *cellCentreTreePtr_;
}
// Is the point in the cell
// Works by checking if there is a face inbetween the point and the cell
// centre.
// Check for internal uses proper face decomposition or just average normal.
bool Foam::meshSearch::pointInCell(const point& p, label cellI) const
{
if (faceDecomp_)
{
const point& ctr = mesh_.cellCentres()[cellI];
vector dir(p - ctr);
scalar magDir = mag(dir);
// Check if any faces are hit by ray from cell centre to p.
// If none -> p is in cell.
const labelList& cFaces = mesh_.cells()[cellI];
// Make sure half_ray does not pick up any faces on the wrong
// side of the ray.
scalar oldTol = intersection::setPlanarTol(0.0);
forAll(cFaces, i)
{
label faceI = cFaces[i];
pointHit inter = mesh_.faces()[faceI].ray
(
ctr,
dir,
mesh_.points(),
intersection::HALF_RAY,
intersection::VECTOR
);
if (inter.hit())
{
scalar dist = inter.distance();
if (dist < magDir)
{
// Valid hit. Hit face so point is not in cell.
intersection::setPlanarTol(oldTol);
return false;
}
}
}
intersection::setPlanarTol(oldTol);
// No face inbetween point and cell centre so point is inside.
return true;
}
else
{
const labelList& f = mesh_.cells()[cellI];
const labelList& owner = mesh_.faceOwner();
const vectorField& cf = mesh_.faceCentres();
const vectorField& Sf = mesh_.faceAreas();
forAll(f, facei)
{
label nFace = f[facei];
vector proj = p - cf[nFace];
vector normal = Sf[nFace];
if (owner[nFace] == cellI)
{
if ((normal & proj) > 0)
{
return false;
}
}
else
{
if ((normal & proj) < 0)
{
return false;
}
}
}
return true;
}
}
Foam::label Foam::meshSearch::findNearestCell
(
const point& location,
const label seedCellI,
const bool useTreeSearch
) const
{
if (seedCellI == -1)
{
if (useTreeSearch)
{
return findNearestCellTree(location);
}
else
{
return <API key>(location);
}
}
else
{
return findNearestCellWalk(location, seedCellI);
}
}
Foam::label Foam::meshSearch::findNearestFace
(
const point& location,
const label seedFaceI,
const bool useTreeSearch
) const
{
if (seedFaceI == -1)
{
if (useTreeSearch)
{
return findNearestFaceTree(location);
}
else
{
return <API key>(location);
}
}
else
{
return findNearestFaceWalk(location, seedFaceI);
}
}
Foam::label Foam::meshSearch::findCell
(
const point& location,
const label seedCellI,
const bool useTreeSearch
) const
{
// Find the nearest cell centre to this location
label nearCellI = findNearestCell(location, seedCellI, useTreeSearch);
if (debug)
{
Pout<< "findCell : nearCellI:" << nearCellI
<< " ctr:" << mesh_.cellCentres()[nearCellI]
<< endl;
}
if (pointInCell(location, nearCellI))
{
return nearCellI;
}
else
{
if (useTreeSearch)
{
// Start searching from cell centre of nearCell
point curPoint = mesh_.cellCentres()[nearCellI];
vector edgeVec = location - curPoint;
edgeVec /= mag(edgeVec);
do
{
// Walk neighbours (using tracking) to get closer
passiveParticle tracker(cloud_, curPoint, nearCellI);
if (debug)
{
Pout<< "findCell : tracked from curPoint:" << curPoint
<< " nearCellI:" << nearCellI;
}
tracker.track(location);
if (debug)
{
Pout<< " to " << tracker.position()
<< " need:" << location
<< " onB:" << tracker.onBoundary()
<< " cell:" << tracker.cell()
<< " face:" << tracker.face() << endl;
}
if (!tracker.onBoundary())
{
// stopped not on boundary -> reached location
return tracker.cell();
}
// stopped on boundary face. Compare positions
scalar typDim = sqrt(mag(mesh_.faceAreas()[tracker.face()]));
if ((mag(tracker.position() - location)/typDim) < SMALL)
{
return tracker.cell();
}
// tracking stopped at boundary. Find next boundary
// intersection from current point (shifted out a little bit)
// in the direction of the destination
curPoint =
tracker.position()
+ offset(tracker.position(), tracker.face(), edgeVec);
if (debug)
{
Pout<< "Searching for next boundary from curPoint:"
<< curPoint
<< " to location:" << location << endl;
}
pointIndexHit curHit = intersection(curPoint, location);
if (debug)
{
Pout<< "Returned from line search with ";
curHit.write(Pout);
Pout<< endl;
}
if (!curHit.hit())
{
return -1;
}
else
{
nearCellI = mesh_.faceOwner()[curHit.index()];
curPoint =
curHit.hitPoint()
+ offset(curHit.hitPoint(), curHit.index(), edgeVec);
}
}
while(true);
}
else
{
return findCellLinear(location);
}
}
return -1;
}
Foam::label Foam::meshSearch::<API key>
(
const point& location,
const label seedFaceI,
const bool useTreeSearch
) const
{
if (seedFaceI == -1)
{
if (useTreeSearch)
{
const indexedOctree<treeDataFace>& tree = boundaryTree();
scalar span = tree.bb().mag();
pointIndexHit info = boundaryTree().findNearest
(
location,
Foam::sqr(span)
);
if (!info.hit())
{
info = boundaryTree().findNearest
(
location,
Foam::sqr(GREAT)
);
}
return tree.shapes().faceLabels()[info.index()];
}
else
{
scalar minDist = GREAT;
label minFaceI = -1;
for
(
label faceI = mesh_.nInternalFaces();
faceI < mesh_.nFaces();
faceI++
)
{
const face& f = mesh_.faces()[faceI];
pointHit curHit =
f.nearestPoint
(
location,
mesh_.points()
);
if (curHit.distance() < minDist)
{
minDist = curHit.distance();
minFaceI = faceI;
}
}
return minFaceI;
}
}
else
{
return <API key>(location, seedFaceI);
}
}
Foam::pointIndexHit Foam::meshSearch::intersection
(
const point& pStart,
const point& pEnd
) const
{
pointIndexHit curHit = boundaryTree().findLine(pStart, pEnd);
if (curHit.hit())
{
// Change index into octreeData into face label
curHit.setIndex(boundaryTree().shapes().faceLabels()[curHit.index()]);
}
return curHit;
}
Foam::List<Foam::pointIndexHit> Foam::meshSearch::intersections
(
const point& pStart,
const point& pEnd
) const
{
DynamicList<pointIndexHit> hits;
vector edgeVec = pEnd - pStart;
edgeVec /= mag(edgeVec);
point pt = pStart;
pointIndexHit bHit;
do
{
bHit = intersection(pt, pEnd);
if (bHit.hit())
{
hits.append(bHit);
const vector& area = mesh_.faceAreas()[bHit.index()];
scalar typDim = Foam::sqrt(mag(area));
if ((mag(bHit.hitPoint() - pEnd)/typDim) < SMALL)
{
break;
}
// Restart from hitPoint shifted a little bit in the direction
// of the destination
pt =
bHit.hitPoint()
+ offset(bHit.hitPoint(), bHit.index(), edgeVec);
}
} while(bHit.hit());
hits.shrink();
return hits;
}
bool Foam::meshSearch::isInside(const point& p) const
{
return
boundaryTree().getVolumeType(p)
== indexedOctree<treeDataFace>::INSIDE;
}
// Delete all storage
void Foam::meshSearch::clearOut()
{
<API key>(boundaryTreePtr_);
<API key>(cellTreePtr_);
<API key>(cellCentreTreePtr_);
}
void Foam::meshSearch::correct()
{
clearOut();
}
|
#include "simulation/Elements.h"
//#TPT-Directive ElementClass Element_FRZZ PT_FRZZ 100
Element_FRZZ::Element_FRZZ()
{
Identifier = "DEFAULT_PT_FRZZ";
Name = "FRZZ";
Colour = PIXPACK(0xC0E0FF);
MenuVisible = 1;
MenuSection = SC_POWDERS;
Enabled = 1;
Advection = 0.7f;
AirDrag = 0.01f * CFDS;
AirLoss = 0.96f;
Loss = 0.90f;
Collision = -0.1f;
Gravity = 0.05f;
Diffusion = 0.01f;
HotAir = -0.00005f* CFDS;
Falldown = 1;
Flammable = 0;
Explosive = 0;
Meltable = 0;
Hardness = 20;
Weight = 50;
Temperature = 253.15f;
HeatConduct = 46;
Description = "Freeze powder. When melted, forms ice that always cools. Spreads with regular water.";
State = ST_SOLID;
Properties = TYPE_PART;
LowPressure = IPL;
<API key> = NT;
HighPressure = 1.8f;
<API key> = PT_SNOW;
LowTemperature = 50.0f;
<API key> = PT_ICEI;
HighTemperature = 273.15;
<API key> = PT_WATR;
Update = &Element_FRZZ::update;
}
//#TPT-Directive ElementHeader Element_FRZZ static int update(UPDATE_FUNC_ARGS)
int Element_FRZZ::update(UPDATE_FUNC_ARGS)
{
int r, rx, ry;
for (rx=-1; rx<2; rx++)
for (ry=-1; ry<2; ry++)
if (x+rx>=0 && y+ry>0 && x+rx<XRES && y+ry<YRES && (rx || ry))
{
r = pmap[y+ry][x+rx];
if (!r)
continue;
if ((r&0xFF)==PT_WATR&&5>rand()%100)
{
sim->part_change_type(r>>8,x+rx,y+ry,PT_FRZW);
parts[r>>8].life = 100;
parts[i].type = PT_NONE;
}
}
if (parts[i].type==PT_NONE) {
sim->kill_part(i);
return 1;
}
return 0;
}
Element_FRZZ::~Element_FRZZ() {}
|
package net.minecraft.inventory;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
// CraftBukkit start
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import org.bukkit.craftbukkit.inventory.<API key>;
import org.bukkit.craftbukkit.inventory.CraftInventoryView;
// CraftBukkit end
public class ContainerPlayer extends Container
{
public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2);
public IInventory craftResult = new <API key>();
public boolean isLocalWorld;
private final EntityPlayer thePlayer;
// CraftBukkit start
private CraftInventoryView bukkitEntity = null;
private InventoryPlayer player;
// CraftBukkit end
private static final String __OBFID = "CL_00001754";
public ContainerPlayer(final InventoryPlayer p_i1819_1_, boolean p_i1819_2_, EntityPlayer p_i1819_3_)
{
this.isLocalWorld = p_i1819_2_;
this.thePlayer = p_i1819_3_;
this.craftResult = new <API key>(); // CraftBukkit - moved to before InventoryCrafting construction
this.craftMatrix = new InventoryCrafting(this, 2, 2, p_i1819_1_.player); // CraftBukkit - pass player
this.craftMatrix.resultInventory = this.craftResult; // CraftBukkit - let InventoryCrafting know about its result slot
this.player = p_i1819_1_; // CraftBukkit - save player
this.addSlotToContainer(new SlotCrafting(p_i1819_1_.player, this.craftMatrix, this.craftResult, 0, 144, 36));
int i;
int j;
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 2; ++j)
{
this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18));
}
}
for (i = 0; i < 4; ++i)
{
final int k = i;
this.addSlotToContainer(new Slot(p_i1819_1_, p_i1819_1_.getSizeInventory() - 1 - i, 8, 8 + i * 18)
{
private static final String __OBFID = "CL_00001755";
public int getSlotStackLimit()
{
return 1;
}
public boolean isItemValid(ItemStack p_75214_1_)
{
if (p_75214_1_ == null) return false;
return p_75214_1_.getItem().isValidArmor(p_75214_1_, k, thePlayer);
}
@SideOnly(Side.CLIENT)
public IIcon <API key>()
{
return ItemArmor.func_94602_b(k);
}
});
}
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 9; ++j)
{
this.addSlotToContainer(new Slot(p_i1819_1_, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18));
}
}
for (i = 0; i < 9; ++i)
{
this.addSlotToContainer(new Slot(p_i1819_1_, i, 8 + i * 18, 142));
}
// this.<API key>(this.craftMatrix); // CraftBukkit - unneeded since it just sets result slot to empty
}
public void <API key>(IInventory p_75130_1_)
{
// CraftBukkit start (Note: the following line would cause an error if called during construction)
CraftingManager.getInstance().lastCraftView = getBukkitView();
ItemStack craftResult = CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj);
this.craftResult.<API key>(0, craftResult);
if (super.crafters.size() < 1)
{
return;
}
EntityPlayerMP player = (EntityPlayerMP) super.crafters.get(0); // TODO: Is this _always_ correct? Seems like it.
player.<API key>.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, 0, craftResult));
// CraftBukkit end
}
public void onContainerClosed(EntityPlayer p_75134_1_)
{
super.onContainerClosed(p_75134_1_);
for (int i = 0; i < 4; ++i)
{
ItemStack itemstack = this.craftMatrix.<API key>(i);
if (itemstack != null)
{
p_75134_1_.<API key>(itemstack, false);
}
}
this.craftResult.<API key>(0, (ItemStack)null);
}
public boolean canInteractWith(EntityPlayer p_75145_1_)
{
return true;
}
public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_)
{
ItemStack itemstack = null;
Slot slot = (Slot)this.inventorySlots.get(p_82846_2_);
if (slot != null && slot.getHasStack())
{
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (p_82846_2_ == 0)
{
if (!this.mergeItemStack(itemstack1, 9, 45, true))
{
return null;
}
slot.onSlotChange(itemstack1, itemstack);
}
else if (p_82846_2_ >= 1 && p_82846_2_ < 5)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 5 && p_82846_2_ < 9)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack())
{
int j = 5 + ((ItemArmor)itemstack.getItem()).armorType;
if (!this.mergeItemStack(itemstack1, j, j + 1, false))
{
return null;
}
}
else if (p_82846_2_ >= 9 && p_82846_2_ < 36)
{
if (!this.mergeItemStack(itemstack1, 36, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 36 && p_82846_2_ < 45)
{
if (!this.mergeItemStack(itemstack1, 9, 36, false))
{
return null;
}
}
else if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
if (itemstack1.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
else
{
slot.onSlotChanged();
}
if (itemstack1.stackSize == itemstack.stackSize)
{
return null;
}
slot.onPickupFromSlot(p_82846_1_, itemstack1);
}
return itemstack;
}
public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_)
{
return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_);
}
// CraftBukkit start
public CraftInventoryView getBukkitView()
{
if (bukkitEntity != null)
{
return bukkitEntity;
}
<API key> inventory = new <API key>(this.craftMatrix, this.craftResult);
bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this);
return bukkitEntity;
}
// CraftBukkit end
}
|
#include "opj_includes.h"
opj_image_t* opj_image_create0(void)
{
opj_image_t *image = (opj_image_t*)opj_calloc(1, sizeof(opj_image_t));
return image;
}
opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts,
<API key> *cmptparms, OPJ_COLOR_SPACE clrspc)
{
int compno;
opj_image_t *image = NULL;
image = (opj_image_t*) opj_calloc(1, sizeof(opj_image_t));
if (image) {
image->color_space = clrspc;
image->numcomps = numcmpts;
/* allocate memory for the per-component information */
image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof(
opj_image_comp_t));
if (!image->comps) {
fprintf(stderr, "Unable to allocate memory for image.\n");
opj_image_destroy(image);
return NULL;
}
/* create the individual image components */
for (compno = 0; compno < numcmpts; compno++) {
opj_image_comp_t *comp = &image->comps[compno];
comp->dx = cmptparms[compno].dx;
comp->dy = cmptparms[compno].dy;
comp->w = cmptparms[compno].w;
comp->h = cmptparms[compno].h;
comp->x0 = cmptparms[compno].x0;
comp->y0 = cmptparms[compno].y0;
comp->prec = cmptparms[compno].prec;
comp->bpp = cmptparms[compno].bpp;
comp->sgnd = cmptparms[compno].sgnd;
comp->data = (int*) opj_calloc(comp->w * comp->h, sizeof(int));
if (!comp->data) {
fprintf(stderr, "Unable to allocate memory for image.\n");
opj_image_destroy(image);
return NULL;
}
}
}
return image;
}
void OPJ_CALLCONV opj_image_destroy(opj_image_t *image)
{
int i;
if (image) {
if (image->comps) {
/* image components */
for (i = 0; i < image->numcomps; i++) {
opj_image_comp_t *image_comp = &image->comps[i];
if (image_comp->data) {
opj_free(image_comp->data);
}
}
opj_free(image->comps);
}
opj_free(image);
}
}
|
#include "spammer.h"
SpammerType Settings::Spammer::type = SpammerType::SPAMMER_NONE;
bool Settings::Spammer::say_team = false;
bool Settings::Spammer::KillSpammer::enabled = false;
bool Settings::Spammer::KillSpammer::sayTeam = false;
std::vector<std::string> Settings::Spammer::KillSpammer::messages = {
"$nick owned by ELITE4",
"$nick suck's again"
};
bool Settings::Spammer::RadioSpammer::enabled = false;
std::vector<std::string> Settings::Spammer::NormalSpammer::messages = {
"I'AM BAD CODER",
"DON'T LIKE TOMATOES",
"SUPREME HACK",
"ELITE4 OWNS U AND ALL",
"ELITE4LEGIT.TK",
"ELITE4HVH.TK"
};
int Settings::Spammer::PositionSpammer::team = 1;
bool Settings::Spammer::PositionSpammer::showName = true;
bool Settings::Spammer::PositionSpammer::showWeapon = true;
bool Settings::Spammer::PositionSpammer::showRank = true;
bool Settings::Spammer::PositionSpammer::showWins = true;
bool Settings::Spammer::PositionSpammer::showHealth = true;
bool Settings::Spammer::PositionSpammer::showMoney = true;
bool Settings::Spammer::PositionSpammer::showLastplace = true;
std::vector<int> killedPlayerQueue;
void Spammer::BeginFrame(float frameTime)
{
if (!engine->IsInGame())
return;
// Grab the current time in milliseconds
long currentTime_ms = Util::GetEpochTime();
static long timeStamp = currentTime_ms;
if (currentTime_ms - timeStamp < 850)
return;
// Kill spammer
if (Settings::Spammer::KillSpammer::enabled && killedPlayerQueue.size() > 0)
{
IEngineClient::player_info_t playerInfo;
engine->GetPlayerInfo(killedPlayerQueue[0], &playerInfo);
// Prepare dead player's nickname without ';' & '"' characters
// as they might cause user to execute a command.
std::string dead_player_name = std::string(playerInfo.name);
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), ';'), dead_player_name.end());
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '"'), dead_player_name.end());
// Remove end line character
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '\n'), dead_player_name.end());
// Construct a command with our message
pstring str;
str << (Settings::Spammer::KillSpammer::sayTeam ? "say_team" : "say");
std::string message = Settings::Spammer::KillSpammer::messages[std::rand() % Settings::Spammer::KillSpammer::messages.size()];
str << " \"" << Util::ReplaceString(message, "$nick", dead_player_name) << "\"";
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
// Remove the first element from the vector
killedPlayerQueue.erase(killedPlayerQueue.begin(), killedPlayerQueue.begin() + 1);
return;
}
if (Settings::Spammer::RadioSpammer::enabled)
{
const char* radioCommands[] = {
"coverme",
"takepoint",
"holdpos",
"regroup",
"followme",
"takingfire",
"go",
"fallback",
"sticktog",
"report",
"roger",
"enemyspot",
"needbackup",
"sectorclear",
"inposition",
"reportingin",
"getout",
"negative",
"enemydown",
};
engine-><API key>(radioCommands[std::rand() % IM_ARRAYSIZE(radioCommands)]);
}
if (Settings::Spammer::type == SpammerType::SPAMMER_NORMAL)
{
if (Settings::Spammer::NormalSpammer::messages.empty())
return;
// Grab a random message string
std::string message = Settings::Spammer::NormalSpammer::messages[std::rand() % Settings::Spammer::NormalSpammer::messages.size()];
// Construct a command with our message
pstring str;
str << (Settings::Spammer::say_team ? "say_team" : "say") << " ";
str << message;
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
}
else if (Settings::Spammer::type == SpammerType::SPAMMER_POSITIONS)
{
C_BasePlayer* localplayer = (C_BasePlayer*) entityList->GetClientEntity(engine->GetLocalPlayer());
static int lastId = 1;
for (int i = lastId; i < engine->GetMaxClients(); i++)
{
C_BasePlayer* player = (C_BasePlayer*) entityList->GetClientEntity(i);
lastId++;
if (lastId == engine->GetMaxClients())
lastId = 1;
if (!player
|| player->GetDormant()
|| !player->GetAlive())
continue;
if (Settings::Spammer::PositionSpammer::team == 0 && player->GetTeam() != localplayer->GetTeam())
continue;
if (Settings::Spammer::PositionSpammer::team == 1 && player->GetTeam() == localplayer->GetTeam())
continue;
IEngineClient::player_info_t entityInformation;
engine->GetPlayerInfo(i, &entityInformation);
C_BaseCombatWeapon* activeWeapon = (C_BaseCombatWeapon*) entityList-><API key>(player->GetActiveWeapon());
// Prepare player's nickname without ';' & '"' characters
// as they might cause user to execute a command.
std::string playerName = std::string(entityInformation.name);
playerName.erase(std::remove(playerName.begin(), playerName.end(), ';'), playerName.end());
playerName.erase(std::remove(playerName.begin(), playerName.end(), '"'), playerName.end());
// Remove end line character
playerName.erase(std::remove(playerName.begin(), playerName.end(), '\n'), playerName.end());
// Construct a command with our message
pstring str;
str << (Settings::Spammer::say_team ? "say_team" : "say") << " \"";
if (Settings::Spammer::PositionSpammer::showName)
str << playerName << " | ";
if (Settings::Spammer::PositionSpammer::showWeapon)
str << Util::Items::GetItemDisplayName(*activeWeapon-><API key>()) << " | ";
if (Settings::Spammer::PositionSpammer::showRank)
str << ESP::ranks[*(*csPlayerResource)-><API key>(i)] << " | ";
if (Settings::Spammer::PositionSpammer::showWins)
str << *(*csPlayerResource)->GetCompetitiveWins(i) << " wins | ";
if (Settings::Spammer::PositionSpammer::showHealth)
str << player->GetHealth() << "HP | ";
if (Settings::Spammer::PositionSpammer::showMoney)
str << "$" << player->GetMoney() << " | ";
if (Settings::Spammer::PositionSpammer::showLastplace)
str << player->GetLastPlaceName();
str << "\"";
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
break;
}
}
// Update the time stamp
timeStamp = currentTime_ms;
}
void Spammer::FireGameEvent(IGameEvent* event)
{
if (!Settings::Spammer::KillSpammer::enabled)
return;
if (!engine->IsInGame())
return;
if (strcmp(event->GetName(), "player_death") != 0)
return;
int attacker_id = engine->GetPlayerForUserID(event->GetInt("attacker"));
int deadPlayer_id = engine->GetPlayerForUserID(event->GetInt("userid"));
// Make sure it's not a suicide.x
if (attacker_id == deadPlayer_id)
return;
// Make sure we're the one who killed someone...
if (attacker_id != engine->GetLocalPlayer())
return;
killedPlayerQueue.push_back(deadPlayer_id);
}
|
package com.app.server.repository;
import com.athena.server.repository.SearchInterface;
import com.athena.annotation.Complexity;
import com.athena.annotation.<API key>;
import com.athena.framework.server.exception.repository.<API key>;
import java.util.List;
import com.athena.framework.server.exception.biz.<API key>;
@<API key>(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Title Master table Entity", complexity = Complexity.LOW)
public interface TitleRepository<T> extends SearchInterface {
public List<T> findAll() throws <API key>;
public T save(T entity) throws <API key>;
public List<T> save(List<T> entity) throws <API key>;
public void delete(String id) throws <API key>;
public void update(T entity) throws <API key>, <API key>;
public void update(List<T> entity) throws <API key>;
public T findById(String titleId) throws Exception, <API key>;
}
|
body {
background: #EEE;
font-family: arial, helvetica, sans-serif;
}
.controls {
position: relative;
width: 640px;
}
#seek {
width: 400px;
position: absolute;
right: 0;
top: 0;
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>RebeccaAIML: Class Members</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.5 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li id="current"><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="namespaces.html"><span>Namespace List</span></a></li>
<li id="current"><a href="namespacemembers.html"><span>Namespace Members</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li id="current"><a href="namespacemembers.html"><span>All</span></a></li>
<li><a href="<API key>.html"><span>Functions</span></a></li>
<li><a href="<API key>.html"><span>Typedefs</span></a></li>
</ul>
</div>
Here is a list of all documented namespace members with links to the namespaces they belong to:
<p>
<ul>
<li>MapStringLinks
: <a class="el" href="<API key>.html#<API key>">customTag::impl</a><li><API key>
: <a class="el" href="<API key>.html#<API key>">customTag::impl</a><li>operator<()
: <a class="el" href="<API key>.html#<API key>">customTag::impl</a><li>sanitizeString()
: <a class="el" href="<API key>.html#<API key>">customTag::impl</a></ul>
<hr size="1"><address style="align: right;"><small>Generated on Tue Feb 14 22:44:55 2006 for RebeccaAIML by
<a href="http:
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.5 </small></address>
</body>
</html>
|
#pragma once
#include <common/except.h>
#include <string>
namespace caspar { namespace ffmpeg {
struct ffmpeg_error : virtual caspar_exception{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct averror_eof : virtual ffmpeg_error{};
struct averror_exit : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
struct <API key> : virtual ffmpeg_error{};
std::string av_error_str(int errn);
void <API key>(int ret, const char* source, const char* func, const char* local_func, const char* file, int line);
void <API key>(int ret, const std::wstring& source, const char* func, const char* local_func, const char* file, int line);
//#define THROW_ON_ERROR(ret, source, func) <API key>(ret, source, __FUNC__, __FILE__, __LINE__)
#define THROW_ON_ERROR_STR_(call) #call
#define THROW_ON_ERROR_STR(call) THROW_ON_ERROR_STR_(call)
#define THROW_ON_ERROR(ret, func, source) \
<API key>(ret, source, func, __FUNCTION__, __FILE__, __LINE__);
#define THROW_ON_ERROR2(call, source) \
[&]() -> int \
{ \
int ret = call; \
<API key>(ret, source, THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \
return ret; \
}()
#define LOG_ON_ERROR2(call, source) \
[&]() -> int \
{ \
int ret = -1;\
try{ \
ret = call; \
<API key>(ret, source, THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \
return ret; \
}catch(...){<API key>();} \
return ret; \
}()
#define FF_RET(ret, func) \
caspar::ffmpeg::<API key>(ret, L"", func, __FUNCTION__, __FILE__, __LINE__);
#define FF(call) \
[&]() -> int \
{ \
auto ret = call; \
caspar::ffmpeg::<API key>(static_cast<int>(ret), L"", THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \
return ret; \
}()
}}
|
# Makefile Makefile for the systemV init suite.
# Targets: all compiles everything
# install installs the binaries (not the scripts)
# clean cleans up object files
# clobber really cleans up
CPPFLAGS =
CFLAGS ?= -ansi -O2 -fomit-frame-pointer
override CFLAGS += -W -Wall -D_GNU_SOURCE
override CFLAGS += $(shell getconf LFS_CFLAGS)
STATIC =
# For some known distributions we do not build all programs, otherwise we do.
BIN =
SBIN = init halt shutdown runlevel killall5 fstab-decode
USRBIN = last mesg
MAN1 = last.1 lastb.1 mesg.1
MAN5 = initscript.5 inittab.5
MAN8 = halt.8 init.8 killall5.8 pidof.8 poweroff.8 reboot.8 runlevel.8
MAN8 += shutdown.8 telinit.8 fstab-decode.8
ifeq ($(DISTRO),)
BIN += mountpoint
SBIN += sulogin bootlogd
USRBIN += utmpdump wall
MAN1 += utmpdump.1 mountpoint.1 wall.1
MAN8 += sulogin.8 bootlogd.8
endif
ifeq ($(DISTRO),Debian)
CPPFLAGS+= -DACCTON_OFF
BIN += mountpoint
SBIN += sulogin bootlogd
MAN1 += mountpoint.1
MAN8 += sulogin.8 bootlogd.8
endif
ifeq ($(DISTRO),Owl)
USRBIN += wall
MAN1 += wall.1
endif
ifeq ($(DISTRO),SuSE)
CPPFLAGS+= -DUSE_SYSFS -DSANE_TIO -DSIGINT_ONLYONCE -DUSE_ONELINE
BIN += mountpoint
SBIN += sulogin
USRBIN += utmpdump
MAN1 += utmpdump.1 mountpoint.1
MAN8 += sulogin.8
endif
ID = $(shell id -u)
BIN_OWNER = root
BIN_GROUP = root
BIN_COMBO = $(BIN_OWNER):$(BIN_GROUP)
ifeq ($(ID),0)
INSTALL_EXEC = install -o $(BIN_OWNER) -g $(BIN_GROUP) -m 755
INSTALL_DATA = install -o $(BIN_OWNER) -g $(BIN_GROUP) -m 644
else
INSTALL_EXEC = install -m 755
INSTALL_DATA = install -m 644
endif
INSTALL_DIR = install -m 755 -d
MANDIR = /usr/share/man
ifeq ($(WITH_SELINUX),yes)
SELINUX_DEF = -DWITH_SELINUX
INITLIBS += -lsepol -lselinux
SULOGINLIBS = -lselinux
else
SELINUX_DEF =
INITLIBS =
SULOGINLIBS =
endif
# Additional libs for GNU libc.
ifneq ($(wildcard /usr/lib*/libcrypt.a),)
SULOGINLIBS += -lcrypt
endif
all: $(BIN) $(SBIN) $(USRBIN)
# $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
#%.o: %.c
# $(CC) $(CFLAGS) $(CPPFLAGS) -c $^ -o $@
init: LDLIBS += $(INITLIBS) $(STATIC)
init: init.o init_utmp.o
halt: halt.o ifdown.o hddown.o utmp.o reboot.h
last: last.o oldutmp.h
mesg: mesg.o
mountpoint: mountpoint.o
utmpdump: utmpdump.o
runlevel: runlevel.o
sulogin: LDLIBS += $(SULOGINLIBS) $(STATIC)
sulogin: sulogin.o
wall: dowall.o wall.o
shutdown: dowall.o shutdown.o utmp.o reboot.h
bootlogd: LDLIBS += -lutil
bootlogd: bootlogd.o
sulogin.o: CPPFLAGS += $(SELINUX_DEF)
sulogin.o: sulogin.c
init.o: CPPFLAGS += $(SELINUX_DEF)
init.o: init.c init.h set.h reboot.h initreq.h
utmp.o: utmp.c init.h
init_utmp.o: CPPFLAGS += -DINIT_MAIN
init_utmp.o: utmp.c init.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
cleanobjs:
rm -f *.o *.bak
clean: cleanobjs
@echo Type \"make clobber\" to really clean up.
clobber: cleanobjs
rm -f $(BIN) $(SBIN) $(USRBIN)
distclean: clobber
install:
$(INSTALL_DIR) $(ROOT)/bin/ $(ROOT)/sbin/
$(INSTALL_DIR) $(ROOT)/usr/bin/
for i in $(BIN); do \
$(INSTALL_EXEC) $$i $(ROOT)/bin/ ; \
done
for i in $(SBIN); do \
$(INSTALL_EXEC) $$i $(ROOT)/sbin/ ; \
done
for i in $(USRBIN); do \
$(INSTALL_EXEC) $$i $(ROOT)/usr/bin/ ; \
done
# $(INSTALL_DIR) $(ROOT)/etc/
# $(INSTALL_EXEC) initscript.sample $(ROOT)/etc/
ln -sf halt $(ROOT)/sbin/reboot
ln -sf halt $(ROOT)/sbin/poweroff
ln -sf init $(ROOT)/sbin/telinit
ln -sf /sbin/killall5 $(ROOT)/bin/pidof
if [ ! -f $(ROOT)/usr/bin/lastb ]; then \
ln -sf last $(ROOT)/usr/bin/lastb; \
fi
$(INSTALL_DIR) $(ROOT)/usr/include/
$(INSTALL_DATA) initreq.h $(ROOT)/usr/include/
$(INSTALL_DIR) $(ROOT)$(MANDIR)/man1/
$(INSTALL_DIR) $(ROOT)$(MANDIR)/man5/
$(INSTALL_DIR) $(ROOT)$(MANDIR)/man8/
for i in $(MAN1); do \
$(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man1/; \
done
for i in $(MAN5); do \
$(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man5/; \
done
for i in $(MAN8); do \
$(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man8/; \
done
ifeq ($(ROOT),)
# This part is skipped on Debian systems, the
# debian.preinst script takes care of it.
@if [ ! -p /dev/initctl ]; then \
echo "Creating /dev/initctl"; \
rm -f /dev/initctl; \
mknod -m 600 /dev/initctl p; fi
endif
|
<?php
namespace OxidEsales\EshopCommunity\Tests\Integration\Seo;
use OxidEsales\Eshop\Application\Model\Article;
use OxidEsales\Eshop\Application\Model\Category;
use OxidEsales\Eshop\Application\Model\Object2Category;
use OxidEsales\Eshop\Core\DatabaseProvider;
use OxidEsales\Eshop\Core\Field;
/**
* Class PaginationSeoTest
*
* @package OxidEsales\EshopCommunity\Tests\Integration\Seo
*/
class PaginationSeoTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/** @var string Original theme */
private $origTheme;
/**
* @var string
*/
private $seoUrl = '';
/**
* @var string
*/
private $categoryOxid = '';
/**
* Sets up test
*/
protected function setUp(): void
{
parent::setUp();
$this->origTheme = $this->getConfig()->getConfigParam('sTheme');
$this->activateTheme('azure');
$this->getConfig()->saveShopConfVar('bool', 'blEnableSeoCache', false);
$this->cleanRegistry();
$this->cleanSeoTable();
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
oxNew(\OxidEsales\Eshop\Application\Model\ArticleList::class)-><API key>();
oxNew(\OxidEsales\Eshop\Core\SystemEventHandler::class)->onShopEnd();
}
/**
* Tear down test.
*/
protected function tearDown(): void
{
//restore theme, do it directly in database as it might be dummy 'basic' theme
$query = "UPDATE `oxconfig` SET `OXVARVALUE` = '" . $this->origTheme . "' WHERE `OXVARNAME` = 'sTheme'";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$this->cleanRegistry();
$this->cleanSeoTable();
$_GET = [];
parent::tearDown();
}
/**
* Call with a seo url that is not yet stored in oxseo table.
* Category etc exists.
* We hit the 404 as no entry for this url exists in oxseo table.
* But when shop shows the 404 page, it creates the main category seo urls.
*/
public function <API key>()
{
$this->callCurl('');
$this->callCurl($this->seoUrl);
$this->cleanRegistry();
$this->cleanSeoTable();
$this->clearProxyCache();
$seoUrl = $this->seoUrl;
$checkResponse = '404 Not Found';
//before
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` like '%" . $seoUrl . "%'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEmpty($res);
//check what shop does
$response = $this->callCurl($seoUrl);
$this-><API key>($checkResponse, $response, "Should get $checkResponse");
}
/**
* Call with a standard url that is not yet stored in oxseo table.
* Category etc exists. No pgNr is provided.
*
*
*/
public function <API key>()
{
$urlToCall = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
$checkResponse = 'HTTP/1.1 200 OK';
//Check entries in oxseo table for oxtype = 'oxcategory'
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEmpty($res);
$response = $this->callCurl($urlToCall);
$this-><API key>($checkResponse, $response, "Should get $checkResponse");
}
/**
* Call shop with standard url, no matching entry in seo table exists atm.
*/
public function <API key>()
{
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
//No match in oxseo table
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertFalse($redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(<API key>, $controller->noIndex());
$controller->init();
$this->assertEquals(<API key>, $controller->noIndex());
$this->assertEmpty($this-><API key>());
}
/**
* Call shop with standard url, a matching entry in seo table already exists.
*/
public function <API key>()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl, $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(<API key>, $controller->noIndex());
$controller->init();
$this->assertEquals(<API key>, $controller->noIndex());
$this->assertEquals(1, count($this-><API key>()));
}
/**
* Call shop with standard url and append pgNr request parameter.
* Blank seo url already is stored in oxseo table.
* Case that pgNr should exist as there are sufficient items in that category.
*/
public function testSeoUrlWithPgNr()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=2';
//base seo url is found in database and page part appended
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=2', $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(<API key>, $controller->noIndex());
$controller->init();
$this->assertEquals(<API key>, $controller->noIndex());
}
/**
* Test paginated entries. Call with standard url with appended pgNr parameter.
*/
public function <API key>()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$this-><API key>();
//Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case.
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=1';
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=1', $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(<API key>, $controller->noIndex());
$controller->init();
$this->assertEquals(<API key>, $controller->noIndex());
}
/**
* Test paginated entries. Call with standard url with appended pgNr parameter.
* Dofference to test case before: call with ot existing page Nr.
*/
public function <API key>()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$this-><API key>();
//Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case.
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=20';
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=20', $redirectUrl);
}
public function <API key>()
{
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
$data = [];
$data['plain_seo_url'] = ['params' => $this->seoUrl,
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0']
];
$data['<API key>'] = ['params' => $this->seoUrl . '2/',
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => 1]
];
return $data;
}
/**
* Test decoding seo calls.
*
* @param string $params
* @param array $expected
*
* @dataProvider <API key>
*/
public function testDecodeNewSeoUrl($params, $expected)
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
$decoded = $seoDecoder->decodeUrl($params); //decoded new url
$this->assertEquals($expected, $decoded);
}
public function <API key>()
{
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
$data = [];
$data['plain_seo_url'] = ['request' => $this->seoUrl,
'get' => [],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0']
];
$data['paginated_page'] = ['request' => $this->seoUrl . '2/',
'get' => ['pgNr' => '1'],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => '1']
];
$data['pgnr_as_get'] = ['params' => $this->seoUrl . '?pgNr=2',
'get' => ['pgNr' => '2'],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => '2']
];
return $data;
}
/**
* Test decoding seo calls. Call shop with seo main page plus pgNr parameter.
* No additional paginated pages are stored in oxseo table. pgNr parameter
* come in via GET and all other needed parameters for processing the call
* are extracted via decodeUrl.
* To be able to correctly decode an url like 'Geschenke/2/' without having
* a matching entry stored in oxseo table, we need to parse this url into
* 'Geschenke/' plus pgNr parameter.
*
* @param string $params
* @param array $get
* @param array $expected
*
* @dataProvider <API key>
*/
public function <API key>($request, $get, $expected)
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
$_GET = $get;
$seoDecoder->processSeoCall($request, '/');
$this->assertEquals($expected, $_GET);
$this-><API key>();
}
/**
* Test SeoEncoderCategory::getCategoryPageUrl()
*/
public function <API key>()
{
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$category = oxNew(\OxidEsales\Eshop\Application\Model\Category::class);
$category->load($this->categoryOxid);
$seoEncoderCategory = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class);
$result = $seoEncoderCategory->getCategoryPageUrl($category, 2);
$this->assertEquals($shopUrl . $this->seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderCategory = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class, ['_saveToDb']);
$seoEncoderCategory->expects($this->never())->method('_saveToDb');
$seoEncoderCategory->getCategoryPageUrl($category, 0);
$seoEncoderCategory->getCategoryPageUrl($category, 1);
$seoEncoderCategory->getCategoryPageUrl($category, 2);
}
/**
* Test SeoEncoderVendor::getVendorPageUrl()
*/
public function <API key>()
{
$facts = new \OxidEsales\Facts\Facts();
if ('EE' != $facts->getEdition()) {
$this->markTestSkipped('missing testdata');
}
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$vendorOxid = 'd2e44d9b31fcce448.08890330';
$seoUrl = 'Nach-Lieferant/Hersteller-1/';
$vendor = oxNew(\OxidEsales\Eshop\Application\Model\Vendor::class);
$vendor->load($vendorOxid);
$seoEncoderVendor = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class);
$result = $seoEncoderVendor->getVendorPageUrl($vendor, 2);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderVendor = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class, ['_saveToDb']);
$seoEncoderVendor->expects($this->never())->method('_saveToDb');
$seoEncoderVendor->getVendorPageUrl($vendor, 0);
$seoEncoderVendor->getVendorPageUrl($vendor, 1);
$seoEncoderVendor->getVendorPageUrl($vendor, 2);
}
/**
* Test <API key>::<API key>()
*/
public function <API key>()
{
$facts = new \OxidEsales\Facts\Facts();
if ('EE' != $facts->getEdition()) {
$this->markTestSkipped('missing testdata');
}
$languageId = 1;
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$manufacturerOxid = '<API key>';
$seoUrl = 'en/By-manufacturer/Manufacturer-2/';
$manufacturer = oxNew(\OxidEsales\Eshop\Application\Model\Manufacturer::class);
$manufacturer->load($manufacturerOxid);
$<API key> = oxNew(\OxidEsales\Eshop\Application\Model\<API key>::class);
$result = $<API key>-><API key>($manufacturer, 2, $languageId);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
}
/**
* Test SeoEncoderRecomm::getRecommPageUrl()
*/
public function <API key>()
{
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$seoUrl = 'testTitle/';
$recomm = $this->getMock(\OxidEsales\Eshop\Application\Model\RecommendationList::class, ['getId', 'getBaseStdLink']);
$recomm->expects($this->any())->method('getId')->will($this->returnValue('testRecommId'));
$recomm->expects($this->any())->method('getBaseStdLink')->will($this->returnValue('testStdLink'));
$recomm-><API key> = new \OxidEsales\Eshop\Core\Field('testTitle');
$seoEncoderRecomm = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class);
$result = $seoEncoderRecomm->getRecommPageUrl($recomm, 2);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderRecomm = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class, ['_saveToDb']);
$seoEncoderRecomm->expects($this->never())->method('_saveToDb');
$seoEncoderRecomm->getRecommPageUrl($recomm, 0);
$seoEncoderRecomm->getRecommPageUrl($recomm, 1);
$seoEncoderRecomm->getRecommPageUrl($recomm, 2);
}
public function providerCheckSeoUrl()
{
$facts = new \OxidEsales\Facts\Facts();
$oxidLiving = ('EE' != $facts->getEdition()) ? '8a142c3e44ea4e714.31136811' : '30e44ab83b6e585c9.63147165';
$data = [
['Eco-Fashion/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['Eco-Fashion/3/', ['404 Not Found'], [], ['Eco-Fashion/']],
['Eco-Fashion/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], []],
['Eco-Fashion/?pgNr=34', ['404 Not Found'],[], []],
['index.php?cl=alist&cnid=oxmore', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=0', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=10', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=20', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=' . $oxidLiving, ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=100', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=200', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]]
];
if (('EE' == $facts->getEdition())) {
$data[] = ['Fuer-Sie/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []];
$data[] = ['Fuer-Sie/45/', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']];
$data[] = ['Fuer-Sie/?pgNr=0', ['HTTP/1.1 200 OK'], [ 'Location', 'ROBOTS'], []];
$data[] = ['Fuer-Sie/?pgNr=34', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']];
} else {
$data[] = ['Geschenke/', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving]];
$data[] = ['Geschenke/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=100', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/30/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=1', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=3', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=4', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/4/', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1',]];
$data[] = ['Geschenke/10/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1', 'Geschenke/4/']];
}
return $data;
}
/**
* Calling not existing pagenumbers must not result in additional entries in oxseo table.
*
* @dataProvider providerCheckSeoUrl
*
* @param string $urlToCall Url to call
* @param array $responseContains Curl call response must contain.
* @param array $responseNotContains Curl call response must not contain.
* @param array $prepareUrls To make test cases independent, call this url first.
*/
public function testCheckSeoUrl(
$urlToCall,
$responseContains,
$responseNotContains,
$prepareUrls
) {
$this-><API key>();
foreach ($prepareUrls as $url) {
$this->callCurl($url);
}
$response = $this->callCurl($urlToCall);
foreach ($responseContains as $checkFor) {
$this-><API key>($checkFor, $response, "Should get $checkFor");
}
foreach ($responseNotContains as $checkFor) {
$this-><API key>($checkFor, $response, "Should not get $checkFor");
}
}
public function <API key>()
{
$this-><API key>();
$this-><API key>();
$seoUrl = 'testSeoUrl/';
$<API key> = $this-><API key>($seoUrl);
$this->callCurl($seoUrl . '?pgNr=0');
$this->clearProxyCache();
$this->callCurl($seoUrl . '?pgNr=0');
$<API key> = $this-><API key>($seoUrl);
$productsPerPage = 10;
$this->assertEquals(
$<API key> + $productsPerPage,
$<API key>
);
}
public function <API key>()
{
$this-><API key>();
$seoUrl = 'testSeoUrl/';
$this->callCurl($seoUrl);
$this->assertCount(
1,
$this->getCategorySeoUrls($seoUrl)
);
$this->callCurl($seoUrl . '?pgNr=0');
$this->callCurl($seoUrl . '1');
$this->assertCount(
1,
$this->getCategorySeoUrls($seoUrl)
);
}
private function <API key>()
{
$this->clearProxyCache();
$this->callCurl(''); //call shop startpage
$this->clearProxyCache();
}
private function <API key>($url)
{
$query = "
SELECT
count(*)
FROM
`oxseo`
WHERE
oxseourl LIKE '%" . $url . "%'
AND oxtype = 'oxarticle'
";
return DatabaseProvider::getDb()->getOne($query);
}
private function getCategorySeoUrls($url)
{
$query = "
SELECT
oxseourl
FROM
`oxseo`
WHERE
oxseourl LIKE '%" . $url . "%'
AND oxtype = 'oxcategory'
";
return DatabaseProvider::getDb()->getAll($query);
}
private function <API key>()
{
$seoUrl = 'testSeoUrl';
$shopId = $this->getConfig()->getBaseShopId();
$category = oxNew(Category::class);
$category-><API key> = new Field(1, Field::T_RAW);
$category-><API key> = new Field('oxrootid', Field::T_RAW);
$category-><API key> = new Field($shopId, Field::T_RAW);
$category-><API key> = new Field($seoUrl, Field::T_RAW);
$category->save();
for ($i = 1; $i <= 20; $i++) {
$product = oxNew(Article::class);
$product->oxarticles__oxtitle = new Field($seoUrl, Field::T_RAW);
$product->save();
$relation = oxNew(Object2Category::class);
$relation->setCategoryId($category->getId());
$relation->setProductId($product->getId());
$relation->save();
}
}
/**
* Clean oxseo for testing.
*/
private function cleanSeoTable()
{
$query = "DELETE FROM oxseo WHERE oxtype in ('oxcategory', 'oxarticle')";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
}
/**
* Ensure that whatever mocks were added are removed from Registry.
*/
private function cleanRegistry()
{
$seoEncoder = oxNew(\OxidEsales\Eshop\Core\SeoEncoder::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoEncoder::class, $seoEncoder);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoDecoder::class, $seoDecoder);
$utils = oxNew(\OxidEsales\Eshop\Core\Utils::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = oxNew(\OxidEsales\Eshop\Core\Request::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
}
/**
* @param string $fileUrlPart Shop url part to call.
*
* @return string
*/
private function callCurl($fileUrlPart)
{
$url = $this->getConfig()->getShopMainUrl() . $fileUrlPart;
$curl = oxNew(\OxidEsales\Eshop\Core\Curl::class);
$curl->setOption('CURLOPT_HEADER', true);
$curl->setOption('<API key>', true);
$curl->setUrl($url);
$return = $curl->execute();
sleep(0.5); // for master slave: please wait before checking the results.
return $return;
}
/**
* Test helper to check for paginated seo pages.
*/
private function <API key>()
{
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` LIKE '{$this->seoUrl}'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}%pgNr%'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}1/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}2/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}3/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}4/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}5/'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEquals(1, count($res));
}
/**
* Test helper.
*
* @return array
*/
private function <API key>()
{
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" .
" AND oxtype = 'oxcategory'";
return \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
}
/**
* Test helper.
*/
private function clearProxyCache()
{
$cacheService = oxNew(\OxidEsales\TestingLibrary\Services\Library\Cache::class);
$cacheService-><API key>();
}
}
|
// Purpose:
// $NoKeywords: $
#include <vgui/IBorder.h>
#include <vgui/IInputInternal.h>
#include <vgui/IPanel.h>
#include <vgui/IScheme.h>
#include <vgui/IVGui.h>
#include <vgui/KeyCode.h>
#include <KeyValues.h>
#include <vgui/MouseCode.h>
#include <vgui/ISurface.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/Controls.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/PropertySheet.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/ToolWindow.h>
#include <vgui_controls/TextImage.h>
#include <vgui_controls/ImagePanel.h>
#include <vgui_controls/PropertyPage.h>
#include "vgui_controls/AnimationController.h"
#include "strtools_local.h" // TODO: temp
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui2;
namespace vgui2
{
class ContextLabel : public Label
{
<API key>(ContextLabel, Label);
public:
ContextLabel(Button *parent, char const *panelName, char const *text)
: BaseClass((Panel *)parent, panelName, text),
m_pTabButton(parent)
{
<API key>(true);
}
virtual void OnMousePressed(MouseCode code)
{
if(m_pTabButton)
{
m_pTabButton->FireActionSignal();
}
}
virtual void OnMouseReleased(MouseCode code)
{
BaseClass::OnMouseReleased(code);
if(GetParent())
{
GetParent()->OnCommand("ShowContextMenu");
}
}
virtual void ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
HFont marlett = pScheme->GetFont("Marlett");
SetFont(marlett);
SetTextInset(0, 0);
SetContentAlignment(Label::a_northwest);
if(GetParent())
{
SetFgColor(pScheme->GetColor("Button.TextColor", GetParent()->GetFgColor()));
SetBgColor(GetParent()->GetBgColor());
}
}
private:
Button *m_pTabButton;
};
// Purpose: Helper for drag drop
// Input : msglist -
// Output : static PropertySheet
static PropertySheet *IsDroppingSheet(CUtlVector<KeyValues *> &msglist)
{
if(msglist.Count() == 0)
return NULL;
KeyValues *data = msglist[0];
PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet"));
if(sheet)
return sheet;
return NULL;
}
// Purpose: A single tab
class PageTab : public Button
{
<API key>(PageTab, Button);
private:
bool _active;
SDK_Color _textColor;
SDK_Color _dimTextColor;
int m_bMaxTabWidth;
IBorder *m_pActiveBorder;
IBorder *m_pNormalBorder;
PropertySheet *m_pParent;
Panel *m_pPage;
ImagePanel *m_pImage;
char *m_pszImageName;
bool m_bShowContextLabel;
ContextLabel *m_pContextLabel;
public:
PageTab(PropertySheet *parent, const char *panelName, const char *text, char const *imageName, int maxTabWidth, Panel *page, bool showContextButton)
: Button((Panel *)parent, panelName, text),
m_pParent(parent),
m_pPage(page),
m_pImage(0),
m_pszImageName(0),
m_bShowContextLabel(showContextButton)
{
SetCommand(new KeyValues("TabPressed"));
_active = false;
m_bMaxTabWidth = maxTabWidth;
SetDropEnabled(true);
SetDragEnabled(m_pParent->IsDraggableTab());
if(imageName)
{
m_pImage = new ImagePanel(this, text);
int buflen = Q_strlen(imageName) + 1;
m_pszImageName = new char[buflen];
Q_strncpy(m_pszImageName, imageName, buflen);
}
<API key>(MOUSE_RIGHT, true);
m_pContextLabel = m_bShowContextLabel ? new ContextLabel(this, "Context", "9") : NULL;
<API key>(_textColor, "selectedcolor");
<API key>(_dimTextColor, "unselectedcolor");
}
~PageTab()
{
delete[] m_pszImageName;
}
virtual void Paint()
{
BaseClass::Paint();
}
virtual bool IsDroppable(CUtlVector<KeyValues *> &msglist)
{
// It's never droppable, but should activate
FireActionSignal();
SetSelected(true);
Repaint();
if(!GetParent())
return false;
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
return GetParent()->IsDroppable(msglist);
}
// Defer to active page...
Panel *active = m_pParent->GetActivePage();
if(!active || !active->IsDroppable(msglist))
return false;
return active->IsDroppable(msglist);
}
virtual void <API key>(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
Panel *target = GetParent()->GetDropTarget(msglist);
if(target)
{
// Fixme, mouse pos could be wrong...
target-><API key>(msglist, dragPanels);
return;
}
}
// Just highlight the tab if dropping onto active page via the tab
BaseClass::<API key>(msglist, dragPanels);
}
virtual void OnPanelDropped(CUtlVector<KeyValues *> &msglist)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
Panel *target = GetParent()->GetDropTarget(msglist);
if(target)
{
// Fixme, mouse pos could be wrong...
target->OnPanelDropped(msglist);
}
}
// Defer to active page...
Panel *active = m_pParent->GetActivePage();
if(!active || !active->IsDroppable(msglist))
return;
active->OnPanelDropped(msglist);
}
virtual void OnDragFailed(CUtlVector<KeyValues *> &msglist)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
return;
// Create a new property sheet
if(m_pParent->IsDraggableTab())
{
if(msglist.Count() == 1)
{
KeyValues *data = msglist[0];
int screenx = data->GetInt("screenx");
int screeny = data->GetInt("screeny");
// m_pParent->ScreenToLocal( screenx, screeny );
if(!m_pParent->IsWithin(screenx, screeny))
{
Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage"));
PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet"));
char const *title = data->GetString("tabname", "");
if(!page || !sheet)
return;
// Can only create if sheet was part of a ToolWindow derived object
ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent());
if(tw)
{
IToolWindowFactory *factory = tw-><API key>();
if(factory)
{
bool hasContextMenu = sheet->PageHasContextMenu(page);
sheet->RemovePage(page);
factory->InstanceToolWindow(tw->GetParent(), sheet-><API key>(), page, title, hasContextMenu);
if(sheet->GetNumPages() == 0)
{
tw->MarkForDeletion();
}
}
}
}
}
}
}
virtual void OnCreateDragData(KeyValues *msg)
{
Assert(m_pParent->IsDraggableTab());
msg->SetPtr("propertypage", m_pPage);
msg->SetPtr("propertysheet", m_pParent);
char sz[256];
GetText(sz, sizeof(sz));
msg->SetString("tabname", sz);
msg->SetString("text", sz);
}
virtual void ApplySchemeSettings(IScheme *pScheme)
{
// set up the scheme settings
Button::ApplySchemeSettings(pScheme);
_textColor = GetSchemeColor("PropertySheet.SelectedTextColor", GetFgColor(), pScheme);
_dimTextColor = GetSchemeColor("PropertySheet.TextColor", GetFgColor(), pScheme);
m_pActiveBorder = pScheme->GetBorder("TabActiveBorder");
m_pNormalBorder = pScheme->GetBorder("TabBorder");
if(m_pImage)
{
ClearImages();
m_pImage->SetImage(scheme()->GetImage(m_pszImageName, false));
AddImage(m_pImage->GetImage(), 2);
int w, h;
m_pImage->GetSize(w, h);
w += m_pContextLabel ? 10 : 0;
if(m_pContextLabel)
{
m_pImage->SetPos(10, 0);
}
SetSize(w + 4, h + 2);
}
else
{
int wide, tall;
int contentWide, contentTall;
GetSize(wide, tall);
GetContentSize(contentWide, contentTall);
wide = std::max(m_bMaxTabWidth, contentWide + 10); // 10 = 5 pixels margin on each side
wide += m_pContextLabel ? 10 : 0;
SetSize(wide, tall);
}
if(m_pContextLabel)
{
SetTextInset(12, 0);
}
}
virtual void OnCommand(char const *cmd)
{
if(!Q_stricmp(cmd, "ShowContextMenu"))
{
KeyValues *kv = new KeyValues("OpenContextMenu");
kv->SetPtr("page", m_pPage);
kv->SetPtr("contextlabel", m_pContextLabel);
PostActionSignal(kv);
return;
}
BaseClass::OnCommand(cmd);
}
IBorder *GetBorder(bool depressed, bool armed, bool selected, bool keyfocus)
{
if(_active)
{
return m_pActiveBorder;
}
return m_pNormalBorder;
}
virtual SDK_Color GetButtonFgColor()
{
if(_active)
{
return _textColor;
}
else
{
return _dimTextColor;
}
}
virtual void SetActive(bool state)
{
_active = state;
InvalidateLayout();
Repaint();
}
virtual bool CanBeDefaultButton(void)
{
return false;
}
//Fire action signal when mouse is pressed down instead of on release.
virtual void OnMousePressed(MouseCode code)
{
// check for context menu open
if(!IsEnabled())
return;
if(!IsMouseClickEnabled(code))
return;
if(<API key>())
{
{
RequestFocus();
FireActionSignal();
SetSelected(true);
Repaint();
}
// lock mouse input to going to this button
input()->SetMouseCapture(GetVPanel());
}
}
virtual void OnMouseReleased(MouseCode code)
{
// ensure mouse capture gets released
if(<API key>())
{
input()->SetMouseCapture(NULL_HANDLE);
}
// make sure the button gets unselected
SetSelected(false);
Repaint();
if(code == MOUSE_RIGHT)
{
KeyValues *kv = new KeyValues("OpenContextMenu");
kv->SetPtr("page", m_pPage);
kv->SetPtr("contextlabel", m_pContextLabel);
PostActionSignal(kv);
}
}
virtual void PerformLayout()
{
BaseClass::PerformLayout();
if(m_pContextLabel)
{
int w, h;
GetSize(w, h);
m_pContextLabel->SetBounds(0, 0, 10, h);
}
}
};
}; // namespace vgui2
// Purpose: Constructor
PropertySheet::PropertySheet(
Panel *parent,
const char *panelName,
bool draggableTabs /*= false*/)
: BaseClass(parent, panelName)
{
_activePage = NULL;
_activeTab = NULL;
_tabWidth = 64;
_activeTabIndex = 0;
_showTabs = true;
_combo = NULL;
_tabFocus = false;
<API key> = 0.0f;
m_bSmallTabs = false;
m_tabFont = 0;
m_bDraggableTabs = draggableTabs;
if(m_bDraggableTabs)
{
SetDropEnabled(true);
}
<API key> = true;
}
// Purpose: Constructor, associates pages with a combo box
PropertySheet::PropertySheet(Panel *parent, const char *panelName, ComboBox *combo)
: BaseClass(parent, panelName)
{
_activePage = NULL;
_activeTab = NULL;
_tabWidth = 64;
_activeTabIndex = 0;
_combo = combo;
_combo-><API key>(this);
_showTabs = false;
_tabFocus = false;
<API key> = 0.0f;
m_bSmallTabs = false;
m_tabFont = 0;
m_bDraggableTabs = false;
}
// Purpose: Destructor
PropertySheet::~PropertySheet()
{
}
// Purpose: ToolWindow uses this to drag tools from container to container by dragging the tab
// Input : -
// Output : Returns true on success, false on failure.
bool PropertySheet::IsDraggableTab() const
{
return m_bDraggableTabs;
}
void PropertySheet::SetDraggableTabs(bool state)
{
m_bDraggableTabs = state;
}
// Purpose: Lower profile tabs
// Input : state -
void PropertySheet::SetSmallTabs(bool state)
{
m_bSmallTabs = state;
m_tabFont = scheme()->GetIScheme(GetScheme())->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default");
int c = m_PageTabs.Count();
for(int i = 0; i < c; ++i)
{
PageTab *tab = m_PageTabs[i];
Assert(tab);
tab->SetFont(m_tabFont);
}
}
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
bool PropertySheet::IsSmallTabs() const
{
return m_bSmallTabs;
}
// Purpose:
// Input : state -
void PropertySheet::ShowContextButtons(bool state)
{
m_bContextButton = state;
}
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
bool PropertySheet::<API key>() const
{
return m_bContextButton;
}
int PropertySheet::FindPage(Panel *page) const
{
int c = m_Pages.Count();
for(int i = 0; i < c; ++i)
{
if(m_Pages[i].page == page)
return i;
}
return m_Pages.InvalidIndex();
}
// Purpose: adds a page to the sheet
void PropertySheet::AddPage(Panel *page, const char *title, char const *imageName /*= NULL*/, bool bHasContextMenu /*= false*/)
{
if(!page)
return;
// don't add the page if we already have it
if(FindPage(page) != m_Pages.InvalidIndex())
return;
PageTab *tab = new PageTab(this, "tab", title, imageName, _tabWidth, page, m_bContextButton && bHasContextMenu);
if(m_bDraggableTabs)
{
tab->SetDragEnabled(true);
}
tab->SetFont(m_tabFont);
if(_showTabs)
{
tab-><API key>(this);
}
else if(_combo)
{
_combo->AddItem(title, NULL);
}
m_PageTabs.AddToTail(tab);
Page_t info;
info.page = page;
info.contextMenu = m_bContextButton && bHasContextMenu;
m_Pages.AddToTail(info);
page->SetParent(this);
page-><API key>(this);
PostMessage(page, new KeyValues("ResetData"));
page->SetVisible(false);
InvalidateLayout();
if(!_activePage)
{
// first page becomes the active page
ChangeActiveTab(0);
if(_activePage)
{
_activePage->RequestFocus(0);
}
}
}
// Purpose:
void PropertySheet::SetActivePage(Panel *page)
{
// walk the list looking for this page
int index = FindPage(page);
if(!m_Pages.IsValidIndex(index))
return;
ChangeActiveTab(index);
}
// Purpose:
void PropertySheet::SetTabWidth(int pixels)
{
_tabWidth = pixels;
InvalidateLayout();
}
// Purpose: reloads the data in all the property page
void PropertySheet::ResetAllData()
{
// iterate all the dialogs resetting them
for(int i = 0; i < m_Pages.Count(); i++)
{
ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ResetData"), GetVPanel());
}
}
// Purpose: Applies any changes made by the dialog
void PropertySheet::ApplyChanges()
{
// iterate all the dialogs resetting them
for(int i = 0; i < m_Pages.Count(); i++)
{
ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ApplyChanges"), GetVPanel());
}
}
// Purpose: gets a pointer to the currently active page
Panel *PropertySheet::GetActivePage()
{
return _activePage;
}
// Purpose: gets a pointer to the currently active tab
Panel *PropertySheet::GetActiveTab()
{
return _activeTab;
}
// Purpose: returns the number of panels in the sheet
int PropertySheet::GetNumPages()
{
return m_Pages.Count();
}
// Purpose: returns the name contained in the active tab
// Input : a text buffer to contain the output
void PropertySheet::GetActiveTabTitle(char *textOut, int bufferLen)
{
if(_activeTab)
_activeTab->GetText(textOut, bufferLen);
}
// Purpose: returns the name contained in the active tab
// Input : a text buffer to contain the output
bool PropertySheet::GetTabTitle(int i, char *textOut, int bufferLen)
{
if(i < 0 && i > m_PageTabs.Count())
{
return false;
}
m_PageTabs[i]->GetText(textOut, bufferLen);
return true;
}
// Purpose: Returns the index of the currently active page
int PropertySheet::GetActivePageNum()
{
for(int i = 0; i < m_Pages.Count(); i++)
{
if(m_Pages[i].page == _activePage)
{
return i;
}
}
return -1;
}
// Purpose: Forwards focus requests to current active page
void PropertySheet::RequestFocus(int direction)
{
if(direction == -1 || direction == 0)
{
if(_activePage)
{
_activePage->RequestFocus(direction);
_tabFocus = false;
}
}
else
{
if(_showTabs && _activeTab)
{
_activeTab->RequestFocus(direction);
_tabFocus = true;
}
else if(_activePage)
{
_activePage->RequestFocus(direction);
_tabFocus = false;
}
}
}
// Purpose: moves focus back
bool PropertySheet::RequestFocusPrev(VPANEL panel)
{
if(_tabFocus || !_showTabs || !_activeTab)
{
_tabFocus = false;
return BaseClass::RequestFocusPrev(panel);
}
else
{
if(GetVParent())
{
PostMessage(GetVParent(), new KeyValues("FindDefaultButton"));
}
_activeTab->RequestFocus(-1);
_tabFocus = true;
return true;
}
}
// Purpose: moves focus forward
bool PropertySheet::RequestFocusNext(VPANEL panel)
{
if(!_tabFocus || !_activePage)
{
return BaseClass::RequestFocusNext(panel);
}
else
{
if(!_activeTab)
{
return BaseClass::RequestFocusNext(panel);
}
else
{
_activePage->RequestFocus(1);
_tabFocus = false;
return true;
}
}
}
// Purpose: Gets scheme settings
void PropertySheet::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
// a little <API key> with old scheme files
IBorder *pBorder = pScheme->GetBorder("PropertySheetBorder");
if(pBorder == pScheme->GetBorder("Default"))
{
// get the old name
pBorder = pScheme->GetBorder("RaisedBorder");
}
SetBorder(pBorder);
<API key> = atof(pScheme->GetResourceString("PropertySheet.<API key>"));
m_tabFont = pScheme->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default");
}
// Purpose: Paint our border specially, with the tabs in mind
void PropertySheet::PaintBorder()
{
IBorder *border = GetBorder();
if(!border)
return;
// draw the border, but with a break at the active tab
int px = 0, py = 0, pwide = 0, ptall = 0;
if(_activeTab)
{
_activeTab->GetBounds(px, py, pwide, ptall);
ptall -= 1;
}
// draw the border underneath the buttons, with a break
int wide, tall;
GetSize(wide, tall);
border->Paint(0, py + ptall, wide, tall, IBorder::SIDE_TOP, px + 1, px + pwide - 1);
}
// Purpose: Lays out the dialog
void PropertySheet::PerformLayout()
{
BaseClass::PerformLayout();
int x, y, wide, tall;
GetBounds(x, y, wide, tall);
if(_activePage)
{
int tabHeight = IsSmallTabs() ? 14 : 28;
if(_showTabs)
{
_activePage->SetBounds(0, tabHeight, wide, tall - tabHeight);
}
else
{
_activePage->SetBounds(0, 0, wide, tall);
}
_activePage->InvalidateLayout();
}
int xtab;
int limit = m_PageTabs.Count();
xtab = 0;
// draw the visible tabs
if(_showTabs)
{
for(int i = 0; i < limit; i++)
{
int tabHeight = IsSmallTabs() ? 13 : 27;
int width, tall;
m_PageTabs[i]->GetSize(width, tall);
if(m_PageTabs[i] == _activeTab)
{
// active tab is taller
_activeTab->SetBounds(xtab, 2, width, tabHeight);
}
else
{
m_PageTabs[i]->SetBounds(xtab, 4, width, tabHeight - 2);
}
m_PageTabs[i]->SetVisible(true);
xtab += (width + 1);
}
}
else
{
for(int i = 0; i < limit; i++)
{
m_PageTabs[i]->SetVisible(false);
}
}
// ensure draw order (page drawing over all the tabs except one)
if(_activePage)
{
_activePage->MoveToFront();
_activePage->Repaint();
}
if(_activeTab)
{
_activeTab->MoveToFront();
_activeTab->Repaint();
}
}
// Purpose: Switches the active panel
void PropertySheet::OnTabPressed(Panel *panel)
{
// look for the tab in the list
for(int i = 0; i < m_PageTabs.Count(); i++)
{
if(m_PageTabs[i] == panel)
{
// flip to the new tab
ChangeActiveTab(i);
return;
}
}
}
// Purpose: returns the panel associated with index i
// Input : the index of the panel to return
Panel *PropertySheet::GetPage(int i)
{
if(i < 0 && i > m_Pages.Count())
{
return NULL;
}
return m_Pages[i].page;
}
// Purpose: disables page by name
void PropertySheet::DisablePage(const char *title)
{
SetPageEnabled(title, false);
}
// Purpose: enables page by name
void PropertySheet::EnablePage(const char *title)
{
SetPageEnabled(title, true);
}
// Purpose: enabled or disables page by name
void PropertySheet::SetPageEnabled(const char *title, bool state)
{
for(int i = 0; i < m_PageTabs.Count(); i++)
{
if(_showTabs)
{
char tmp[50];
m_PageTabs[i]->GetText(tmp, 50);
if(!strnicmp(title, tmp, strlen(tmp)))
{
m_PageTabs[i]->SetEnabled(state);
}
}
else
{
_combo->SetItemEnabled(title, state);
}
}
}
void PropertySheet::RemoveAllPages()
{
int c = m_Pages.Count();
for(int i = c - 1; i >= 0; --i)
{
RemovePage(m_Pages[i].page);
}
}
// Purpose: deletes the page associated with panel
// Input : *panel - the panel of the page to remove
void PropertySheet::RemovePage(Panel *panel)
{
int location = FindPage(panel);
if(location == m_Pages.InvalidIndex())
return;
// Since it's being deleted, don't animate!!!
<API key> = NULL;
_activeTab = NULL;
// ASSUMPTION = that the number of pages equals number of tabs
if(_showTabs)
{
m_PageTabs[location]-><API key>(this);
}
// now remove the tab
PageTab *tab = m_PageTabs[location];
m_PageTabs.Remove(location);
tab->MarkForDeletion();
// Remove from page list
m_Pages.Remove(location);
// Unparent
panel->SetParent((Panel *)NULL);
if(_activePage == panel)
{
_activePage = NULL;
// if this page is currently active, backup to the page before this.
ChangeActiveTab(std::max(location - 1, 0));
}
PerformLayout();
}
// Purpose: deletes the page associated with panel
// Input : *panel - the panel of the page to remove
void PropertySheet::DeletePage(Panel *panel)
{
Assert(panel);
RemovePage(panel);
panel->MarkForDeletion();
}
// Purpose: flips to the new tab, sending out all the right notifications
// flipping to a tab activates the tab.
void PropertySheet::ChangeActiveTab(int index)
{
if(!m_Pages.IsValidIndex(index))
{
_activeTab = NULL;
if(m_Pages.Count() > 0)
{
_activePage = NULL;
ChangeActiveTab(0);
}
return;
}
if(m_Pages[index].page == _activePage)
{
if(_activeTab)
{
_activeTab->RequestFocus();
}
_tabFocus = true;
return;
}
int c = m_Pages.Count();
for(int i = 0; i < c; ++i)
{
m_Pages[i].page->SetVisible(false);
}
<API key> = _activePage;
// notify old page
if(_activePage)
{
ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageHide"), GetVPanel());
KeyValues *msg = new KeyValues("PageTabActivated");
msg->SetPtr("panel", (Panel *)NULL);
ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel());
}
if(_activeTab)
{
//_activeTabIndex=index;
_activeTab->SetActive(false);
// does the old tab have the focus?
_tabFocus = _activeTab->HasFocus();
}
else
{
_tabFocus = false;
}
// flip page
_activePage = m_Pages[index].page;
_activeTab = m_PageTabs[index];
_activeTabIndex = index;
_activePage->SetVisible(true);
_activePage->MoveToFront();
_activeTab->SetVisible(true);
_activeTab->MoveToFront();
_activeTab->SetActive(true);
if(_tabFocus)
{
// if a tab already has focused,give the new tab the focus
_activeTab->RequestFocus();
}
else
{
// otherwise, give the focus to the page
_activePage->RequestFocus();
}
if(!_showTabs)
{
_combo->ActivateItemByRow(index);
}
_activePage->MakeReadyForUse();
// transition effect
if(<API key>)
{
if(<API key>.Get())
{
// fade out the previous page
<API key>()->RunAnimationCommand(<API key>, "Alpha", 0.0f, 0.0f, <API key> / 2, AnimationController::INTERPOLATOR_LINEAR);
}
// fade in the new page
_activePage->SetAlpha(0);
<API key>()->RunAnimationCommand(_activePage, "Alpha", 255.0f, <API key> / 2, <API key> / 2, AnimationController::INTERPOLATOR_LINEAR);
}
else
{
if(<API key>.Get())
{
// no transition, just hide the previous page
<API key>->SetVisible(false);
}
_activePage->SetAlpha(255);
}
// notify
ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageShow"), GetVPanel());
KeyValues *msg = new KeyValues("PageTabActivated");
msg->SetPtr("panel", (Panel *)_activeTab);
ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel());
// tell parent
PostActionSignal(new KeyValues("PageChanged"));
// Repaint
InvalidateLayout();
Repaint();
}
// Purpose: Gets the panel with the specified hotkey, from the current page
Panel *PropertySheet::HasHotkey(wchar_t key)
{
if(!_activePage)
return NULL;
for(int i = 0; i < _activePage->GetChildCount(); i++)
{
Panel *hot = _activePage->GetChild(i)->HasHotkey(key);
if(hot)
{
return hot;
}
}
return NULL;
}
// Purpose: catches the opencontextmenu event
void PropertySheet::OnOpenContextMenu(KeyValues *params)
{
// tell parent
KeyValues *kv = params->MakeCopy();
PostActionSignal(kv);
Panel *page = reinterpret_cast<Panel *>(params->GetPtr("page"));
if(page)
{
PostMessage(page->GetVPanel(), params->MakeCopy());
}
}
// Purpose: Handle key presses, through tabs.
void PropertySheet::OnKeyCodeTyped(KeyCode code)
{
bool shift = (input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT));
bool ctrl = (input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL));
bool alt = (input()->IsKeyDown(KEY_LALT) || input()->IsKeyDown(KEY_RALT));
if(ctrl && shift && alt && code == KEY_B)
{
// enable build mode
EditablePanel *ep = dynamic_cast<EditablePanel *>(GetActivePage());
if(ep)
{
ep->ActivateBuildMode();
return;
}
}
if(<API key>())
{
switch(code)
{
// for now left and right arrows just open or close submenus if they are there.
case KEY_RIGHT:
{
ChangeActiveTab(_activeTabIndex + 1);
break;
}
case KEY_LEFT:
{
ChangeActiveTab(_activeTabIndex - 1);
break;
}
default:
BaseClass::OnKeyCodeTyped(code);
break;
}
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
// Purpose: Called by the associated combo box (if in that mode), changes the current panel
void PropertySheet::OnTextChanged(Panel *panel, const wchar_t *wszText)
{
if(panel == _combo)
{
wchar_t tabText[30];
for(int i = 0; i < m_PageTabs.Count(); i++)
{
tabText[0] = 0;
m_PageTabs[i]->GetText(tabText, 30);
if(!wcsicmp(wszText, tabText))
{
ChangeActiveTab(i);
}
}
}
}
// Purpose:
void PropertySheet::OnCommand(const char *command)
{
// propogate the close command to our parent
if(!stricmp(command, "Close") && GetVParent())
{
CallParentFunction(new KeyValues("Command", "command", command));
}
}
// Purpose:
void PropertySheet::OnApplyButtonEnable()
{
// tell parent
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
// Purpose:
void PropertySheet::<API key>(Panel *defaultButton)
{
// forward the message up
if(GetVParent())
{
KeyValues *msg = new KeyValues("<API key>");
msg->SetPtr("button", defaultButton);
PostMessage(GetVParent(), msg);
}
}
// Purpose:
void PropertySheet::OnDefaultButtonSet(Panel *defaultButton)
{
// forward the message up
if(GetVParent())
{
KeyValues *msg = new KeyValues("DefaultButtonSet");
msg->SetPtr("button", defaultButton);
PostMessage(GetVParent(), msg);
}
}
// Purpose:
void PropertySheet::OnFindDefaultButton()
{
if(GetVParent())
{
PostMessage(GetVParent(), new KeyValues("FindDefaultButton"));
}
}
bool PropertySheet::PageHasContextMenu(Panel *page) const
{
int pageNum = FindPage(page);
if(pageNum == m_Pages.InvalidIndex())
return false;
return m_Pages[pageNum].contextMenu;
}
void PropertySheet::OnPanelDropped(CUtlVector<KeyValues *> &msglist)
{
if(msglist.Count() != 1)
{
return;
}
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
{
// Defer to active page
if(_activePage && _activePage->IsDropEnabled())
{
return _activePage->OnPanelDropped(msglist);
}
return;
}
KeyValues *data = msglist[0];
Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage"));
char const *title = data->GetString("tabname", "");
if(!page || !sheet)
return;
// Can only create if sheet was part of a ToolWindow derived object
ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent());
if(tw)
{
IToolWindowFactory *factory = tw-><API key>();
if(factory)
{
bool showContext = sheet->PageHasContextMenu(page);
sheet->RemovePage(page);
if(sheet->GetNumPages() == 0)
{
tw->MarkForDeletion();
}
AddPage(page, title, NULL, showContext);
}
}
}
bool PropertySheet::IsDroppable(CUtlVector<KeyValues *> &msglist)
{
if(!m_bDraggableTabs)
return false;
if(msglist.Count() != 1)
{
return false;
}
int mx, my;
input()->GetCursorPos(mx, my);
ScreenToLocal(mx, my);
int tabHeight = IsSmallTabs() ? 14 : 28;
if(my > tabHeight)
return false;
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
{
return false;
}
if(sheet == this)
return false;
return true;
}
// Mouse is now over a droppable panel
void PropertySheet::<API key>(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels)
{
// Convert this panel's bounds to screen space
int x, y, w, h;
GetSize(w, h);
int tabHeight = IsSmallTabs() ? 14 : 28;
h = tabHeight + 4;
x = y = 0;
LocalToScreen(x, y);
surface()->DrawSetColor(GetDropFrameColor());
// Draw 2 pixel frame
surface()->DrawOutlinedRect(x, y, x + w, y + h);
surface()->DrawOutlinedRect(x + 1, y + 1, x + w - 1, y + h - 1);
if(!IsDroppable(msglist))
{
return;
}
if(!_showTabs)
{
return;
}
// Draw a fake new tab...
x = 0;
y = 2;
w = 1;
h = tabHeight;
int last = m_PageTabs.Count();
if(last != 0)
{
m_PageTabs[last - 1]->GetBounds(x, y, w, h);
}
// Compute left edge of "fake" tab
x += (w + 1);
// Compute size of new panel
KeyValues *data = msglist[0];
char const *text = data->GetString("tabname", "");
Assert(text);
PageTab *fakeTab = new PageTab(this, "FakeTab", text, NULL, _tabWidth, NULL, false);
fakeTab->SetBounds(x, 4, w, tabHeight - 4);
fakeTab->SetFont(m_tabFont);
SETUP_PANEL(fakeTab);
fakeTab->Repaint();
surface()->SolveTraverse(fakeTab->GetVPanel(), true);
surface()->PaintTraverse(fakeTab->GetVPanel());
delete fakeTab;
}
// Purpose:
// Input : state -
void PropertySheet::<API key>(bool state)
{
<API key> = state;
}
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
bool PropertySheet::<API key>() const
{
return <API key>;
}
|
import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class <API key>:
# features extension supports
features = ()
def __init__(self, parent, window):
self._parent = parent
self._window = window
self._application = self._parent._application
# create user interface
self._container = gtk.VBox(False, 5)
self._controls = gtk.HBox(False, 5)
separator = gtk.HSeparator()
# pack interface
self._container.pack_end(separator, False, False, 0)
self._container.pack_end(self._controls, False, False, 0)
def can_handle(self, uri):
"""Returns boolean denoting if specified URI can be handled by this extension"""
return False
def get_container(self):
"""Return container widget"""
return self._container
def get_information(self):
"""Returns information about extension"""
icon = None
name = None
return icon, name
def unmount(self, uri):
"""Method called by the mount manager for unmounting the selected URI"""
pass
def focus_object(self):
"""Method called by the mount manager for focusing main object"""
pass
@classmethod
def get_features(cls):
"""Returns set of features supported by extension"""
return cls.features
|
<?php // content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_gantt.php');
$graph = new GanttGraph();
$graph->SetBox();
$graph->SetShadow();
// Add title and subtitle
$graph->title->Set("Example of captions");
$graph->title->SetFont(FF_ARIAL,FS_BOLD,12);
$graph->subtitle->Set("(ganttex16.php)");
// Show day, week and month scale
$graph->ShowHeaders(GANTT_HDAY | GANTT_HWEEK | GANTT_HMONTH);
// Set table title
$graph->scale->tableTitle->Set("(Rev: 1.22)");
$graph->scale->tableTitle->SetFont(FF_FONT1,FS_BOLD);
$graph->scale-><API key>("silver");
$graph->scale->tableTitle->Show();
// Use the short name of the month together with a 2 digit year
// on the month scale
$graph->scale->month->SetStyle(<API key>);
$graph->scale->month->SetFontColor("white");
$graph->scale->month->SetBackgroundColor("blue");
// 0 % vertical label margin
$graph-><API key>(1);
// Format the bar for the first activity
// ($row,$title,$startdate,$enddate)
$activity = new GanttBar(0,"Project","2001-12-21","2002-01-07","[50%]");
// Yellow diagonal line pattern on a red background
$activity->SetPattern(BAND_RDIAG,"yellow");
$activity->SetFillColor("red");
// Set absolute height
$activity->SetHeight(10);
// Specify progress to 60%
$activity->progress->Set(0.6);
$activity->progress->SetPattern(BAND_HVCROSS,"blue");
// Format the bar for the second activity
// ($row,$title,$startdate,$enddate)
$activity2 = new GanttBar(1,"Project","2001-12-21","2002-01-02","[30%]");
// Yellow diagonal line pattern on a red background
$activity2->SetPattern(BAND_RDIAG,"yellow");
$activity2->SetFillColor("red");
// Set absolute height
$activity2->SetHeight(10);
// Specify progress to 30%
$activity2->progress->Set(0.3);
$activity2->progress->SetPattern(BAND_HVCROSS,"blue");
// Finally add the bar to the graph
$graph->Add($activity);
$graph->Add($activity2);
// Add a vertical line
$vline = new GanttVLine("2001-12-24","Phase 1");
$vline->SetDayOffset(0.5);
//$graph->Add($vline);
// ... and display it
$graph->Stroke();
?>
|
package cn.nukkit.math;
public class Vector3 implements Cloneable {
public double x;
public double y;
public double z;
public Vector3() {
this(0, 0, 0);
}
public Vector3(double x) {
this(x, 0, 0);
}
public Vector3(double x, double y) {
this(x, y, 0);
}
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getZ() {
return this.z;
}
public int getFloorX() {
return (int) Math.floor(this.x);
}
public int getFloorY() {
return (int) Math.floor(this.y);
}
public int getFloorZ() {
return (int) Math.floor(this.z);
}
public double getRight() {
return this.x;
}
public double getUp() {
return this.y;
}
public double getForward() {
return this.z;
}
public double getSouth() {
return this.x;
}
public double getWest() {
return this.z;
}
public Vector3 add(double x) {
return this.add(x, 0, 0);
}
public Vector3 add(double x, double y) {
return this.add(x, y, 0);
}
public Vector3 add(double x, double y, double z) {
return new Vector3(this.x + x, this.y + y, this.z + z);
}
public Vector3 add(Vector3 x) {
return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ());
}
public Vector3 subtract() {
return this.subtract(0, 0, 0);
}
public Vector3 subtract(double x) {
return this.subtract(x, 0, 0);
}
public Vector3 subtract(double x, double y) {
return this.subtract(x, y, 0);
}
public Vector3 subtract(double x, double y, double z) {
return this.add(-x, -y, -z);
}
public Vector3 subtract(Vector3 x) {
return this.add(-x.getX(), -x.getY(), -x.getZ());
}
public Vector3 multiply(double number) {
return new Vector3(this.x * number, this.y * number, this.z * number);
}
public Vector3 divide(double number) {
return new Vector3(this.x / number, this.y / number, this.z / number);
}
public Vector3 ceil() {
return new Vector3((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z));
}
public Vector3 floor() {
return new Vector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
public Vector3 round() {
return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z));
}
public Vector3 abs() {
return new Vector3((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z));
}
public Vector3 getSide(BlockFace face) {
return this.getSide(face, 1);
}
public Vector3 getSide(BlockFace face, int step) {
return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step);
}
public Vector3 up() {
return up(1);
}
public Vector3 up(int step) {
return getSide(BlockFace.UP, step);
}
public Vector3 down() {
return down(1);
}
public Vector3 down(int step) {
return getSide(BlockFace.DOWN, step);
}
public Vector3 north() {
return north(1);
}
public Vector3 north(int step) {
return getSide(BlockFace.NORTH, step);
}
public Vector3 south() {
return south(1);
}
public Vector3 south(int step) {
return getSide(BlockFace.SOUTH, step);
}
public Vector3 east() {
return east(1);
}
public Vector3 east(int step) {
return getSide(BlockFace.EAST, step);
}
public Vector3 west() {
return west(1);
}
public Vector3 west(int step) {
return getSide(BlockFace.WEST, step);
}
public double distance(Vector3 pos) {
return Math.sqrt(this.distanceSquared(pos));
}
public double distanceSquared(Vector3 pos) {
return Math.pow(this.x - pos.x, 2) + Math.pow(this.y - pos.y, 2) + Math.pow(this.z - pos.z, 2);
}
public double maxPlainDistance() {
return this.maxPlainDistance(0, 0);
}
public double maxPlainDistance(double x) {
return this.maxPlainDistance(x, 0);
}
public double maxPlainDistance(double x, double z) {
return Math.max(Math.abs(this.x - x), Math.abs(this.z - z));
}
public double maxPlainDistance(Vector2 vector) {
return this.maxPlainDistance(vector.x, vector.y);
}
public double maxPlainDistance(Vector3 x) {
return this.maxPlainDistance(x.x, x.z);
}
public double length() {
return Math.sqrt(this.lengthSquared());
}
public double lengthSquared() {
return this.x * this.x + this.y * this.y + this.z * this.z;
}
public Vector3 normalize() {
double len = this.lengthSquared();
if (len > 0) {
return this.divide(Math.sqrt(len));
}
return new Vector3(0, 0, 0);
}
public double dot(Vector3 v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
public Vector3 cross(Vector3 v) {
return new Vector3(
this.y * v.z - this.z * v.y,
this.z * v.x - this.x * v.z,
this.x * v.y - this.y * v.x
);
}
/**
* Returns a new vector with x value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 <API key>(Vector3 v, double x) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (xDiff * xDiff < 0.0000001) {
return null;
}
double f = (x - this.x) / xDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with y value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 <API key>(Vector3 v, double y) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (yDiff * yDiff < 0.0000001) {
return null;
}
double f = (y - this.y) / yDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with z value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 <API key>(Vector3 v, double z) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (zDiff * zDiff < 0.0000001) {
return null;
}
double f = (z - this.z) / zDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
public Vector3 setComponents(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public String toString() {
return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")";
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Vector3)) {
return false;
}
Vector3 other = (Vector3) obj;
return this.x == other.x && this.y == other.y && this.z == other.z;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32);
return hash;
}
public int rawHashCode() {
return super.hashCode();
}
@Override
public Vector3 clone() {
try {
return (Vector3) super.clone();
} catch (<API key> e) {
return null;
}
}
public Vector3f asVector3f() {
return new Vector3f((float) this.x, (float) this.y, (float) this.z);
}
public BlockVector3 asBlockVector3() {
return new BlockVector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
}
|
<?php
namespace Magento\Newsletter\Controller\Adminhtml\Template;
class NewAction extends \Magento\Newsletter\Controller\Adminhtml\Template
{
/**
* Create new Newsletter Template
*
* @return void
*/
public function execute()
{
$this->_forward('edit');
}
}
|
// StyleDressApp.h
// DressApp
// This file is part of DressApp.
// DressApp is free software: you can redistribute it and/or modify
// (at your option) any later version.
// DressApp is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
typedef enum {
StyleTypeVintage = 1,
StyleTypeModern =2,
} StyleType;
typedef enum {
<API key>,
<API key>,
<API key>,
StyleColorPRHeader,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
StyleColorCOHeader,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
StyleColorHelpCell,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
} StyleColorType;
typedef enum {
StyleFontMainType,
StyleFontFlat,
StyleFontBottomBtns,
StyleFontActionView,
<API key>,
<API key>,
} StyleFontType;
@interface StyleDressApp : NSObject
+(void) setStyle:(StyleType)newAppStyle;
+(StyleType) getStyle;
+(UIImage*) imageWithStyleNamed:(NSString*)imageName;
+(UIColor*) <API key>:(StyleColorType)styleColor;
+(UIFont*) fontWithStyleNamed:(StyleFontType)newFontType AndSize:(CGFloat)newFontSize;
@end
|
#include "TileElement.h"
#include "../core/Guard.hpp"
#include "../interface/Window.h"
#include "../localisation/Localisation.h"
#include "../ride/Track.h"
#include "Banner.h"
#include "LargeScenery.h"
#include "Scenery.h"
uint8_t TileElementBase::GetType() const
{
return this->type & <API key>;
}
void TileElementBase::SetType(uint8_t newType)
{
this->type &= ~<API key>;
this->type |= (newType & <API key>);
}
Direction TileElementBase::GetDirection() const
{
return this->type & <API key>;
}
void TileElementBase::SetDirection(Direction direction)
{
this->type &= ~<API key>;
this->type |= (direction & <API key>);
}
Direction TileElementBase::<API key>(uint8_t offset) const
{
return ((this->type & <API key>) + offset) & <API key>;
}
bool TileElementBase::IsLastForTile() const
{
return (this->flags & <API key>) != 0;
}
void TileElementBase::SetLastForTile(bool on)
{
if (on)
flags |= <API key>;
else
flags &= ~<API key>;
}
bool TileElementBase::IsGhost() const
{
return (this->flags & <API key>) != 0;
}
void TileElementBase::SetGhost(bool isGhost)
{
if (isGhost)
{
this->flags |= <API key>;
}
else
{
this->flags &= ~<API key>;
}
}
bool <API key>(TileElement* tileElement)
{
do
{
tileElement++;
if ((tileElement - 1)->IsLastForTile())
return false;
} while (tileElement->GetType() != <API key>);
return true;
}
BannerIndex <API key>(TileElement* tileElement)
{
rct_scenery_entry* sceneryEntry;
switch (tileElement->GetType())
{
case <API key>:
sceneryEntry = tileElement->AsLargeScenery()->GetEntry();
if (sceneryEntry->large_scenery.scrolling_mode == SCROLLING_MODE_NONE)
return BANNER_INDEX_NULL;
return tileElement->AsLargeScenery()->GetBannerIndex();
case <API key>:
sceneryEntry = tileElement->AsWall()->GetEntry();
if (sceneryEntry == nullptr || sceneryEntry->wall.scrolling_mode == SCROLLING_MODE_NONE)
return BANNER_INDEX_NULL;
return tileElement->AsWall()->GetBannerIndex();
case <API key>:
return tileElement->AsBanner()->GetIndex();
default:
return BANNER_INDEX_NULL;
}
}
void <API key>(TileElement* tileElement, BannerIndex bannerIndex)
{
switch (tileElement->GetType())
{
case <API key>:
tileElement->AsWall()->SetBannerIndex(bannerIndex);
break;
case <API key>:
tileElement->AsLargeScenery()->SetBannerIndex(bannerIndex);
break;
case <API key>:
tileElement->AsBanner()->SetIndex(bannerIndex);
break;
default:
log_error("Tried to set banner index on unsuitable tile element!");
Guard::Assert(false);
}
}
void <API key>(TileElement* tileElement)
{
auto bannerIndex = <API key>(tileElement);
auto banner = GetBanner(bannerIndex);
if (banner != nullptr)
{
<API key>(WC_BANNER, bannerIndex);
*banner = {};
}
}
uint8_t <API key>(const TileElement* tileElement)
{
switch (tileElement->GetType())
{
case <API key>:
return tileElement->AsTrack()->GetRideIndex();
case <API key>:
return tileElement->AsEntrance()->GetRideIndex();
case <API key>:
return tileElement->AsPath()->GetRideIndex();
default:
return RIDE_ID_NULL;
}
}
void TileElement::ClearAs(uint8_t newType)
{
type = newType;
flags = 0;
base_height = 2;
clearance_height = 2;
std::fill_n(pad_04, sizeof(pad_04), 0x00);
std::fill_n(pad_08, sizeof(pad_08), 0x00);
}
void TileElementBase::Remove()
{
tile_element_remove((TileElement*)this);
}
// Rotate both of the values amount
const QuarterTile QuarterTile::Rotate(uint8_t amount) const
{
switch (amount)
{
case 0:
return QuarterTile{ *this };
break;
case 1:
{
auto rotVal1 = _val << 1;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b11101110;
// Clear the bit from the zQuarter
rotVal2 &= 0b00010001;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
case 2:
{
auto rotVal1 = _val << 2;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b11001100;
// Clear the bit from the zQuarter
rotVal2 &= 0b00110011;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
case 3:
{
auto rotVal1 = _val << 3;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b10001000;
// Clear the bit from the zQuarter
rotVal2 &= 0b01110111;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
default:
log_error("Tried to rotate QuarterTile invalid amount.");
return QuarterTile{ 0 };
}
}
uint8_t TileElementBase::<API key>() const
{
return flags & <API key>;
}
void TileElementBase::<API key>(uint8_t quadrants)
{
flags &= ~<API key>;
flags |= (quadrants & <API key>);
}
int32_t TileElementBase::GetBaseZ() const
{
return base_height * 8;
}
void TileElementBase::SetBaseZ(int32_t newZ)
{
base_height = (newZ / 8);
}
int32_t TileElementBase::GetClearanceZ() const
{
return clearance_height * 8;
}
void TileElementBase::SetClearanceZ(int32_t newZ)
{
clearance_height = (newZ / 8);
}
|
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#define DEBUG (1)
/* Basic signal handler closes nfq hooks on exit */
static void sig_handler(int signum) {
printf("\nCaught Signal ...\n\n");
exit(0);
}
int main(int argc, char **argv) {
struct sockaddr_in sin;
struct sockaddr_in sout;
int s = socket(AF_INET,SOCK_STREAM,0);
unsigned int slen = sizeof(sout);
unsigned int len = 0;
char line[500];
long delay = 0;
unsigned int cntr = 0;
int port = 1194;
int tmp = 0;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = INADDR_ANY;
/* make stdin non-blocking, i.e. optional */
int flags = fcntl(0, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(0, F_SETFL, flags);
/* close nfq hooks on exit */
if (signal(SIGINT, sig_handler) == SIG_IGN)
signal(SIGINT, SIG_IGN);
if (signal(SIGHUP, sig_handler) == SIG_IGN)
signal(SIGHUP, SIG_IGN);
if (signal(SIGTERM, sig_handler) == SIG_IGN)
signal(SIGTERM, SIG_IGN);
// wait for conn, store peer in sout
bind(s, (struct sockaddr *)&sin, sizeof(sin));
listen(s, 2);
int c = accept(s, (struct sockaddr *)&sout, &tmp);
tmp=1;
if (setsockopt(c, IPPROTO_TCP, TCP_NODELAY, &tmp, sizeof(tmp)) < 0)
fprintf(stderr, "Error when disabling buffer..\n");
printf("Got connection from %s:%d, start sending..\n",
inet_ntoa(sout.sin_addr), ntohs(sout.sin_port));
len = snprintf(line, 499, "%010d\n",cntr++);
send(c, line, len+1,0);
while (1) {
if (fgets(line, 49, stdin)) {
delay = atol(line);
}
else {
if (argc > 1)
exit(0);
delay = 5000;
}
if (delay < 0)
delay = 0;
usleep(delay);
len = snprintf(line, 499, "%010d\n",cntr++);
send(c, line, len+1,0);
}
}
|
#include "common/platform.h"
#include <gtest/gtest.h>
#include "common/chunk_read_planner.h"
#include "unittests/<API key>.h"
#include "unittests/plan_tester.h"
static ChunkPartType xor_part(int level, int part) {
return slice_traits::xors::ChunkPartType(level, part);
}
static void checkReadingChunk(std::map<ChunkPartType, std::vector<uint8_t>> &part_data,
int first_block, int block_count,
const ChunkReadPlanner::PartsContainer &available_parts) {
ChunkReadPlanner planner;
planner.prepare(first_block, block_count, available_parts);
ASSERT_TRUE(planner.isReadingPossible());
std::unique_ptr<ReadPlan> plan = planner.buildPlan();
unittests::ReadPlanTester tester;
std::cout << to_string(*plan) << std::endl;
ASSERT_TRUE(tester.executePlan(std::move(plan), part_data) >= 0);
EXPECT_TRUE(unittests::ReadPlanTester::compareBlocks(
tester.output_buffer_, 0, part_data[slice_traits::standard::ChunkPartType()],
first_block * MFSBLOCKSIZE, block_count));
}
static void checkReadingChunk(int first_block, int block_count,
const ChunkReadPlanner::PartsContainer &available_parts) {
std::map<ChunkPartType, std::vector<uint8_t>> part_data;
unittests::ReadPlanTester::buildData(part_data, available_parts);
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()});
checkReadingChunk(part_data, first_block, block_count, available_parts);
}
/*
TEST(<API key>, Unrecoverable1) {
checkUnrecoverable(xor_p_of_4, {xor_1_of_4, xor_2_of_4, xor_3_of_4});
}
TEST(<API key>, Unrecoverable2) {
checkUnrecoverable(xor_p_of_4, {xor_1_of_4, xor_2_of_4, xor_3_of_4});
}
TEST(<API key>, Unrecoverable3) {
checkUnrecoverable(xor_p_of_2, {xor_1_of_4, xor_2_of_4, xor_p_of_4});
}
TEST(<API key>, Unrecoverable4) {
checkUnrecoverable(xor_p_of_4, {xor_p_of_2});
}
*/
TEST(<API key>, VerifyRead1) {
std::map<ChunkPartType, std::vector<uint8_t>> part_data;
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::xors::ChunkPartType(5, 1)});
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()});
for (int i = 1; i <= 10; ++i) {
checkReadingChunk(part_data, 0, i, {xor_part(5, 0), xor_part(5, 1), xor_part(5, 2),
xor_part(5, 3), xor_part(5, 4), xor_part(5, 5)});
}
}
TEST(<API key>, VerifyRead2) {
std::map<ChunkPartType, std::vector<uint8_t>> part_data;
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::xors::ChunkPartType(5, 1)});
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()});
for (int i = 1; i <= 10; ++i) {
checkReadingChunk(part_data, i, 2, {xor_part(5, 0), xor_part(5, 1), xor_part(5, 2),
xor_part(5, 3), xor_part(5, 4), xor_part(5, 5)});
}
}
TEST(<API key>, VerifyRead3) {
checkReadingChunk(0, 10, {xor_p_of_4, xor_2_of_4, xor_3_of_4, xor_4_of_4});
}
TEST(<API key>, VerifyRead4) {
checkReadingChunk(10, 100, {xor_p_of_7, xor_1_of_7, xor_2_of_7, xor_3_of_7, xor_4_of_7,
xor_5_of_7, xor_6_of_7, xor_7_of_7});
}
|
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
defined('MOODLE_INTERNAL') || die();
class <API key> extends <API key> {
protected $buttons = array('<API key>', 'tiny_mce_wiris_CAS');
protected function update_init_params(array &$params, context $context,
array $options = null) {
global $PAGE, $CFG;
$PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/baseURL.js', false);
// Add button after emoticon button in advancedbuttons3.
$added = $this->add_button_after($params, 3, '<API key>', '', false);
$added = $this->add_button_after($params, 3, '<API key>', '', false);
$added = $this->add_button_after($params, 3, 'tiny_mce_wiris_CAS', '', false);
// Add JS file, which uses default name.
$this->add_js_plugin($params);
$filterwiris = $CFG->dirroot . '/filter/wiris/filter.php';
if (!file_exists($filterwiris)) {
$PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/js/message.js', false);
}
}
}
|
var searchData=
[
['save_5fcomments',['save_comments',['../<API key>.html#<API key>',1,'useful_functions.php']]],
['<API key>',['<API key>',['../<API key>.html#<API key>',1,'choose_experiments.php']]],
['save_5fsessions',['save_sessions',['../<API key>.html#<API key>',1,'useful_functions.php']]],
['<API key>',['save_signup_to_db',['../<API key>.html#<API key>',1,'useful_functions.php']]],
['<API key>',['<API key>',['../<API key>.html#<API key>',1,'useful_functions.php']]],
['signup_5fexists',['signup_exists',['../<API key>.html#<API key>',1,'useful_functions.php']]]
];
|
<?php
class UserMySQLDAO extends PDODAO implements UserDAO {
/**
* Get the SQL to generate <API key> number
* @TODO rename "tweets" "posts"
* @return str SQL calcuation
*/
private function <API key>() {
return "round(post_count/(datediff(curdate(), joined)), 2) as avg_tweets_per_day";
}
public function isUserInDB($user_id, $network) {
$q = "SELECT user_id ";
$q .= "FROM #prefix#users ";
$q .= "WHERE user_id = :user_id AND network = :network;";
$vars = array(
':user_id'=>(string)$user_id,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataIsReturned($ps);
}
public function isUserInDBByName($username, $network) {
$q = "SELECT user_id ";
$q .= "FROM #prefix#users ";
$q .= "WHERE user_name = :username AND network = :network";
$vars = array(
':username'=>$username,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataIsReturned($ps);
}
public function updateUsers($users_to_update) {
$count = 0;
$status_message = "";
if (sizeof($users_to_update) > 0) {
$status_message .= count($users_to_update)." users queued for insert or update; ";
foreach ($users_to_update as $user) {
$count += $this->updateUser($user);
}
$status_message .= "$count users affected.";
}
$this->logger->logInfo($status_message, __METHOD__.','.__LINE__);
$status_message = "";
return $count;
}
public function updateUser($user) {
if (!isset($user->username)) {
return 0;
}
$status_message = "";
$has_friend_count = $user->friend_count != '' ? true : false;
$has_favorites_count = $user->favorites_count != '' ? true : false;
$has_last_post = $user->last_post != '' ? true : false;
$has_last_post_id = $user->last_post_id != '' ? true : false;
$network = $user->network != '' ? $user->network : 'twitter';
$user->follower_count = $user->follower_count != '' ? $user->follower_count : 0;
$user->post_count = $user->post_count != '' ? $user->post_count : 0;
$vars = array(
':user_id'=>(string)$user->user_id,
':username'=>$user->username,
':full_name'=>$user->full_name,
':avatar'=>$user->avatar,
':location'=>$user->location,
':description'=>$user->description,
':url'=>$user->url,
':is_protected'=>$this->convertBoolToDB($user->is_protected),
':follower_count'=>$user->follower_count,
':post_count'=>$user->post_count,
':found_in'=>$user->found_in,
':joined'=>$user->joined,
':network'=>$user->network
);
$is_user_in_storage = false;
$is_user_in_storage = $this->isUserInDB($user->user_id, $user->network);
if (!$is_user_in_storage) {
$q = "INSERT INTO #prefix#users (user_id, user_name, full_name, avatar, location, description, url, ";
$q .= "is_protected, follower_count, post_count, ".($has_friend_count ? "friend_count, " : "")." ".
($has_favorites_count ? "favorites_count, " : "")." ".
($has_last_post ? "last_post, " : "")." found_in, joined, network ".
($has_last_post_id ? ", last_post_id" : "").") ";
$q .= "VALUES ( :user_id, :username, :full_name, :avatar, :location, :description, :url, :is_protected, ";
$q .= ":follower_count, :post_count, ".($has_friend_count ? ":friend_count, " : "")." ".
($has_favorites_count ? ":favorites_count, " : "")." ".
($has_last_post ? ":last_post, " : "")." :found_in, :joined, :network ".
($has_last_post_id ? ", :last_post_id " : "")." )";
} else {
$q = "UPDATE #prefix#users SET full_name = :full_name, avatar = :avatar, location = :location, ";
$q .= "user_name = :username, description = :description, url = :url, is_protected = :is_protected, ";
$q .= "follower_count = :follower_count, post_count = :post_count, ".
($has_friend_count ? "friend_count= :friend_count, " : "")." ".
($has_favorites_count ? "favorites_count= :favorites_count, " : "")." ".
($has_last_post ? "last_post= :last_post, " : "")." last_updated = NOW(), found_in = :found_in, ";
$q .= "joined = :joined, network = :network ".
($has_last_post_id ? ", last_post_id = :last_post_id" : "")." ";
$q .= "WHERE user_id = :user_id AND network = :network;";
}
if ($has_friend_count) {
$vars[':friend_count'] = $user->friend_count;
}
if ($has_favorites_count) {
$vars[':favorites_count'] = $user->favorites_count;
}
if ($has_last_post) {
$vars[':last_post'] = $user->last_post;
}
if ($has_last_post_id) {
$vars[':last_post_id'] = $user->last_post_id;
}
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
$results = $this->getUpdateCount($ps);
return $results;
}
public function getDetails($user_id, $network) {
$q = "SELECT * , ".$this-><API key>()." ";
$q .= "FROM #prefix#users u ";
$q .= "WHERE u.user_id = :user_id AND u.network = :network;";
$vars = array(
':user_id'=>(string)$user_id,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataRowAsObject($ps, "User");
}
public function getUserByName($user_name, $network) {
$q = "SELECT * , ".$this-><API key>()." ";
$q .= "FROM #prefix#users u ";
$q .= "WHERE u.user_name = :user_name AND u.network = :network";
$vars = array(
':user_name'=>$user_name,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataRowAsObject($ps, "User");
}
}
|
# NgrxSimpleLab4
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.1.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http:
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package VerilogCompiler.SyntacticTree;
import VerilogCompiler.SemanticCheck.ErrorHandler;
import VerilogCompiler.SemanticCheck.ExpressionType;
import VerilogCompiler.SyntacticTree.Expressions.Expression;
public class Range extends VNode {
Expression minValue;
Expression maxValue;
public Range(Expression minValue, Expression maxValue, int line, int column) {
super(line, column);
this.minValue = minValue;
this.maxValue = maxValue;
}
public Expression getMinValue() {
return minValue;
}
public void setMinValue(Expression minValue) {
this.minValue = minValue;
}
public Expression getMaxValue() {
return maxValue;
}
public void setMaxValue(Expression maxValue) {
this.maxValue = maxValue;
}
@Override
public String toString() {
return String.format("[%s:%s]", this.minValue, this.maxValue);
}
@Override
public ExpressionType validateSemantics() {
ExpressionType minReturnType = minValue.validateSemantics();
ExpressionType maxReturnType = maxValue.validateSemantics();
if (minReturnType != ExpressionType.INTEGER || maxReturnType != ExpressionType.INTEGER)
{
ErrorHandler.getInstance().handleError(line, column, "range min and max value must be integer");
}
return null;
}
@Override
public VNode getCopy() {
return new Range((Expression)minValue.getCopy(), (Expression)maxValue.getCopy(), line, column);
}
}
|
import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class <API key>(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = <API key>.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = <API key>.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
|
'use strict';
var async = require('async');
var nconf = require('nconf');
var querystring = require('querystring');
var meta = require('../meta');
var pagination = require('../pagination');
var user = require('../user');
var topics = require('../topics');
var plugins = require('../plugins');
var helpers = require('./helpers');
var unreadController = module.exports;
unreadController.get = function (req, res, next) {
var page = parseInt(req.query.page, 10) || 1;
var results;
var cid = req.query.cid;
var filter = req.query.filter || '';
var settings;
async.waterfall([
function (next) {
plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next);
},
function (data, _next) {
if (!data.filters[filter]) {
return next();
}
async.parallel({
watchedCategories: function (next) {
helpers.<API key>(req.uid, cid, next);
},
settings: function (next) {
user.getSettings(req.uid, next);
},
}, _next);
},
function (_results, next) {
results = _results;
settings = results.settings;
var start = Math.max(0, (page - 1) * settings.topicsPerPage);
var stop = start + settings.topicsPerPage - 1;
var cutoff = req.session.unreadCutoff ? req.session.unreadCutoff : topics.unreadCutoff();
topics.getUnreadTopics({
cid: cid,
uid: req.uid,
start: start,
stop: stop,
filter: filter,
cutoff: cutoff,
}, next);
},
function (data, next) {
user.blocks.filter(req.uid, data.topics, function (err, filtered) {
data.topics = filtered;
next(err, data);
});
},
function (data) {
data.title = meta.config.homePageTitle || '[[pages:home]]';
data.pageCount = Math.max(1, Math.ceil(data.topicCount / settings.topicsPerPage));
data.pagination = pagination.create(page, data.pageCount, req.query);
if (settings.usePagination && (page < 1 || page > data.pageCount)) {
req.query.page = Math.max(1, Math.min(data.pageCount, page));
return helpers.redirect(res, '/unread?' + querystring.stringify(req.query));
}
data.categories = results.watchedCategories.categories;
data.allCategoriesUrl = 'unread' + helpers.buildQueryString('', filter, '');
data.selectedCategory = results.watchedCategories.selectedCategory;
data.selectedCids = results.watchedCategories.selectedCids;
if (req.originalUrl.startsWith(nconf.get('relative_path') + '/api/unread') || req.originalUrl.startsWith(nconf.get('relative_path') + '/unread')) {
data.title = '[[pages:unread]]';
data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[unread:title]]' }]);
}
data.filters = helpers.buildFilters('unread', filter, req.query);
data.selectedFilter = data.filters.find(function (filter) {
return filter && filter.selected;
});
res.render('unread', data);
},
], next);
};
unreadController.unreadTotal = function (req, res, next) {
var filter = req.query.filter || '';
async.waterfall([
function (next) {
plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next);
},
function (data, _next) {
if (!data.filters[filter]) {
return next();
}
topics.getTotalUnread(req.uid, filter, _next);
},
function (data) {
res.json(data);
},
], next);
};
|
# This file is part of Indico.
# Indico is free software; you can redistribute it and/or
# published by the Free Software Foundation; either version 3 of the
# Indico is distributed in the hope that it will be useful, but
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
class Serializer(object):
schemaless = True
encapsulate = True
registry = {}
def __init__(self, query_params, pretty=False, **kwargs):
self.pretty = pretty
self._query_params = query_params
self._fileName = None
self._lastModified = None
self._extra_args = kwargs
@classmethod
def register(cls, tag, serializer):
cls.registry[tag] = serializer
@classmethod
def getAllFormats(cls):
return list(cls.registry)
@classmethod
def create(cls, dformat, query_params=None, **kwargs):
"""
A serializer factory
"""
query_params = query_params or {}
serializer = cls.registry.get(dformat)
if serializer:
return serializer(query_params, **kwargs)
else:
raise Exception("Serializer for '%s' does not exist!" % dformat)
def getMIMEType(self):
return self._mime
def set_headers(self, response):
response.content_type = self.getMIMEType()
def __call__(self, obj, *args, **kwargs):
self._obj = obj
self._data = self._execute(obj, *args, **kwargs)
return self._data
from indico.web.http_api.metadata.json import JSONSerializer
from indico.web.http_api.metadata.xml import XMLSerializer
|
<?php
namespace Magento\Sales\Model\Spi;
/**
* Interface ResourceInterface
*/
interface <API key>
{
/**
* Save object data
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
public function save(\Magento\Framework\Model\AbstractModel $object);
/**
* Load an object
*
* @param mixed $value
* @param \Magento\Framework\Model\AbstractModel $object
* @param string|null $field field to load by (defaults to model id)
* @return mixed
*/
public function load(\Magento\Framework\Model\AbstractModel $object, $value, $field = null);
/**
* Delete the object
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return mixed
*/
public function delete(\Magento\Framework\Model\AbstractModel $object);
}
|
#!/usr/bin/perl
# $Id: Chain.pm,v 1.12 2001/06/18 08:27:53 heikki Exp $
# bioperl module for Bio::LiveSeq::Chain
# Cared for by Joseph Insana <insana@ebi.ac.uk> <jinsana@gmx.net>
# You may distribute this module under the same terms as perl itself
# POD documentation - main docs before the code
=head1 NAME
Bio::LiveSeq::Chain - DoubleChain DataStructure for Perl
=head1 SYNOPSIS
#documentation needed
=head1 DESCRIPTION
This is a general purpose module (that's why it's not in object-oriented
form) that introduces a novel datastructure in PERL. It implements
the "double linked chain". The elements of the chain can contain basically
everything. From chars to strings, from object references to arrays or hashes.
It is used in the LiveSequence project to create a dynamical DNA sequence,
easier to manipulate and change. It's use is mainly for sequence variation
analysis but it could be used - for example - in e-cell projects.
The Chain module in itself doesn't have any biological bias, so can be
used for any programming purpose.
Each element of the chain (with the exclusion of the first and the last of the
chain) is connected to other two elements (the PREVious and the NEXT one).
There is no absolute position (like in an array), hence if positions are
important, they need to be computed (methods are provided).
Otherwise it's easy to keep track of the elements with their "LABELs".
There is one LABEL (think of it as a pointer) to each ELEMENT. The labels
won't change after insertions or deletions of the chain. So it's
always possible to retrieve an element even if the chain has been
modified by successive insertions or deletions.
From this the high potential profit for bioinformatics: dealing with
sequences in a way that doesn't have to rely on positions, without
the need of constantly updating them if the sequence changes, even
dramatically.
=head1 AUTHOR - Joseph A.L. Insana
Email: Insana@ebi.ac.uk, jinsana@gmx.net
Address:
EMBL Outstation, European Bioinformatics Institute
Wellcome Trust Genome Campus, Hinxton
Cambs. CB10 1SD, United Kingdom
=head1 APPENDIX
The rest of the documentation details each of the object
methods. Internal methods are usually preceded with a _
=cut
# Let the code begin...
# DoubleChain Data Structure for PERL
# by Joseph A.L. Insana - Deathson - Filius Mortis - Fal Mortais
# insana@ebi.ac.uk, jinsana@gmx.net
package Bio::LiveSeq::Chain;
# Version history:
# Fri Mar 10 16:46:51 GMT 2000 v1.0 begun working on chains in perl
# Sat Mar 11 05:47:21 GMT 2000 v.1.4 working on splice method
# Sun Mar 12 14:08:31 GMT 2000 v.1.5
# Sun Mar 12 17:21:51 GMT 2000 v.2.0 splice method working, is_updownstream made
# Sun Mar 12 18:11:22 GMT 2000 v.2.04 wrapped all in package Chain.pm
# Sun Mar 12 18:49:23 GMT 2000 v.2.08 added elements()
# Sun Mar 12 21:18:04 GMT 2000 v.2.1 done array2dchain, working on *insert*
# Sun Mar 12 23:04:40 GMT 2000 v.2.16 done *insert*, up_element, create_elems
# Sun Mar 12 23:45:32 GMT 2000 v.2.17 debugged and checked
# Mon Mar 13 00:44:51 GMT 2000 v.2.2 added mutate()
# Mon Mar 13 02:00:32 GMT 2000 v 2.21 added invert_dchain()
# Mon Mar 13 03:01:21 GMT 2000 v 2.22 created updown_chain2string
# Mon Mar 13 03:45:50 GMT 2000 v.2.24 added subchain_length()
# Mon Mar 13 17:25:04 GMT 2000 v.2.26 added element_at_pos and pos_of_element
# Wed Mar 15 23:05:06 GMT 2000 v.2.27 use strict enforced
# Thu Mar 16 19:05:34 GMT 2000 v.2.3 changed dchain->chain everywhere
# Fri Mar 17 01:48:36 GMT 2000 v.2.33 mutate_element renamed, created new
# methods: set_value, get_value...
# Fri Mar 17 05:03:15 GMT 2000 v.2.4 set_value_at_pos, get_value_at_pos
# get_label_at_pos...
# Fri Mar 17 15:51:07 GMT 2000 v.2.41 renamed pos_of_element -> get_pos_of_label
# Fri Mar 17 18:10:36 GMT 2000 v.2.44 recoded subchain_length and pos_of_label
# Fri Mar 17 20:12:27 GMT 2000 v.2.5 NAMING change: index->label everywhere
# Mon Mar 20 18:33:10 GMT 2000 v.2.52 label_exists(), start(), end()
# Mon Mar 20 23:10:28 GMT 2000 v.2.6 labels() created
# Wed Mar 22 18:35:17 GMT 2000 v.2.61 chain2string() rewritten
# Tue Dec 12 14:47:58 GMT 2000 v 2.66 optimized with /use integer/
# Tue Dec 12 16:28:45 GMT 2000 v 2.7 rewritten comments to methods in pod style
$VERSION=2.7;
# TODO_list:
# *??* create hash2dchain ???? (with hashkeys used for label)
# **????** how about using array of arrays instead than hash of arrays??
# further strict complaints:
# in verbose $string assignment around line 721 ???
# TERMINOLOGY update, naming convention:
# "chain" the datastructure
# "element" the individual units that compose a chain
# "label" the unique name of a single element
# "position" the position of an element into the chain according to a
# particular coordinate system (e.g. counting from the start)
# "value" what is stored in a single element
use Carp qw(croak cluck carp); # as of 2.3
use strict; # as of 2.27
use integer; # WARNING: this is to increase performance
# a little bit of attention has to be given if float need to
# be stored as elements of the array
# the use of this "integer" affects all operations but not
# assignments. So float CAN be assigned as elements of the chain
# BUT, if you assign $z=-1.8;, $z will be equal to -1 because
# "-" counts as a unary operation!
=head2 <API key>
Title : chain2string
Usage : $string = Bio::LiveSeq::Chain::chain2string("down",$chain,6,9)
Function: reads the contents of the chain, outputting a string
Returns : a string
Examples:
: down_chain2string($chain) -> all the chain from begin to end
: down_chain2string($chain,6) -> from 6 to the end
: down_chain2string($chain,6,4) -> from 6, going on 4 elements
: down_chain2string($chain,6,"",10) -> from 6 to 10
: up_chain2string($chain,10,"",6) -> from 10 to 6 upstream
Defaults: start=first element; if len undef, goes to last
if last undef, goes to end
if last defined, it overrides len (undefining it)
Error code: -1
Args : "up"||"down" as first argument to specify the reading direction
reference (to the chain)
[first] [len] [last] optional integer arguments to specify how
much and from (and to) where to read
=cut
# methods rewritten 2.61
sub up_chain2string {
<API key>("up",@_);
}
sub down_chain2string {
<API key>("down",@_);
}
sub <API key> {
my ($direction,$chain,$first,$len,$last)=@_;
unless($chain) { cluck "no chain input"; return (-1); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
unless ($first) { $first=$end; } # if undef or 0, use $end
} else { # defaults to "down"
$flow=1; # used to determine the direction of chain navigation
unless ($first) { $first=$begin; } # if undef or 0, use $begin
}
unless($chain->{$first}) {
cluck "label for first not defined"; return (-1); }
if ($last) { # if last is defined, it gets priority and len is not used
unless($chain->{$last}) {
cluck "label for last not defined"; return (-1); }
if ($len) {
warn "Warning chain2string: argument LAST:$last overriding LEN:$len!";
undef $len;
}
} else {
if ($direction eq "up") {
$last=$begin; # if last not defined, go 'till begin (or upto len elements)
} else {
$last=$end; # if last not defined, go 'till end (or upto len elements)
}
}
my ($string,@array);
my $label=$first; my $i=1;
my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
# proceed for len elements or until last, whichever comes first
# if $len undef goes till end
while (($label) && ($label != $afterlast) && ($i <= ($len || $i + 1))) {
@array=@{$chain->{$label}};
$string .= $array[0];
$label = $array[$flow];
$i++;
}
return ($string); # if chain is interrupted $string won't be complete
}
=head2 _updown_labels
Title : labels
Usage : @labels = Bio::LiveSeq::Chain::_updown_labels("down",$chain,4,16)
Function: returns all the labels in a chain or those between two
specified ones (termed "first" and "last")
Returns : a reference to an array containing the labels
Args : "up"||"down" as first argument to specify the reading direction
reference (to the chain)
[first] [last] (integer for the starting and eneding labels)
=cut
# arguments: CHAIN_REF [FIRSTLABEL] [LASTLABEL]
# returns: reference to array containing the labels
sub down_labels {
my ($chain,$first,$last)=@_;
_updown_labels("down",$chain,$first,$last);
}
sub up_labels {
my ($chain,$first,$last)=@_;
_updown_labels("up",$chain,$first,$last);
}
# arguments: "up"||"down" CHAIN_REF [FIRSTLABEL] [LASTLABEL]
# returns: reference to array containing the labels
sub _updown_labels {
my ($direction,$chain,$first,$last)=@_;
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") { $flow=2;
unless ($first) { $first=$end; }
unless ($last) { $last=$begin; }
} else { $flow=1;
unless ($last) { $last=$end; }
unless ($first) { $first=$begin; }
}
unless($chain->{$first}) { warn "not existing label $first"; return (0); }
unless($chain->{$last}) { warn "not existing label $last"; return (0); }
my $label=$first; my @labels;
my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
while (($label)&&($label != $afterlast)) {
push(@labels,$label);
$label=$chain->{$label}[$flow];
}
return (\@labels); # if chain is interrupted @labels won't be complete
}
=head2 start
Title : start
Usage : $start = Bio::LiveSeq::Chain::start()
Returns : the label marking the start of the chain
Errorcode: -1
Args : none
=cut
sub start {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (-1); }
return ($chain->{'begin'});
}
=head2 end
Title : end
Usage : $end = Bio::LiveSeq::Chain::end()
Returns : the label marking the end of the chain
Errorcode: -1
Args : none
=cut
sub end {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (-1); }
return ($chain->{'end'});
}
=head2 label_exists
Title : label_exists
Usage : $check = Bio::LiveSeq::Chain::label_exists($chain,$label)
Function: It checks if a label is defined, i.e. if an element is there or
is not there anymore
Returns : 1 if the label exists, 0 if it is not there, -1 error
Errorcode: -1
Args : reference to the chain, integer
=cut
sub label_exists {
my ($chain,$label)=@_;
unless($chain) { cluck "no chain input"; return (-1); }
if ($label && $chain->{$label}) { return (1); } else { return (0) };
}
=head2 <API key>
Title : <API key>
Usage : $position = Bio::LiveSeq::Chain::<API key>($chain,$label,$first)
Function: returns the position of $label counting from $first, i.e. taking
$first as 1 of coordinate system. If $first is not specified it will
count from the start of the chain.
Returns :
Errorcode: 0
Args : reference to the chain, integer (the label of interest)
optional: integer (a different label that will be taken as the
first one, i.e. the one to count from)
Note: It counts "downstream". To proceed backward use up_get_pos_of_label
=cut
sub <API key> {
#down_chain2string($_[0],$_[2],undef,$_[1],"counting");
my ($chain,$label,$first)=@_;
_updown_count("down",$chain,$first,$label);
}
sub up_get_pos_of_label {
#up_chain2string($_[0],$_[2],undef,$_[1],"counting");
my ($chain,$label,$first)=@_;
_updown_count("up",$chain,$first,$label);
}
=head2 <API key>
Title : <API key>
Usage : $length = Bio::LiveSeq::Chain::<API key>($chain,$first,$last)
Function: returns the length of the chain between the labels "first" and "last", included
Returns : integer
Errorcode: 0
Args : reference to the chain, integer, integer
Note: It counts "downstream". To proceed backward use up_subchain_length
=cut
# arguments: chain_ref [first] [last]
# returns the length of the chain between first and last (included)
sub <API key> {
#down_chain2string($_[0],$_[1],undef,$_[2],"counting");
my ($chain,$first,$last)=@_;
_updown_count("down",$chain,$first,$last);
}
sub up_subchain_length {
#up_chain2string($_[0],$_[1],undef,$_[2],"counting");
my ($chain,$first,$last)=@_;
_updown_count("up",$chain,$first,$last);
}
# arguments: DIRECTION CHAIN_REF FIRSTLABEL LASTLABEL
# errorcode 0
sub _updown_count {
my ($direction,$chain,$first,$last)=@_;
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") { $flow=2;
unless ($first) { $first=$end; }
unless ($last) { $last=$begin; }
} else { $flow=1;
unless ($last) { $last=$end; }
unless ($first) { $first=$begin; }
}
unless($chain->{$first}) { warn "not existing label $first"; return (0); }
unless($chain->{$last}) { warn "not existing label $last"; return (0); }
my $label=$first; my $count;
my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
while (($label)&&($label != $afterlast)) {
$count++;
$label=$chain->{$label}[$flow];
}
return ($count); # if chain is interrupted, $i will be up to the breaking point
}
=head2 invert_chain
Title : invert_chain
Usage : $errorcode=Bio::LiveSeq::Chain::invert_chain($chain)
Function: completely inverts the order of the chain elements; begin is swapped with end and all links updated (PREV&NEXT fields swapped)
Returns : 1 if all OK, 0 if errors
Errorcode: 0
Args : reference to the chain
=cut
sub invert_chain {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the last element
my ($label,@array);
$label=$begin; # starts from the beginning
while ($label) { # proceed with linked elements, swapping PREV and NEXT
@array=@{$chain->{$label}};
($chain->{$label}[1],$chain->{$label}[2])=($array[2],$array[1]); # swap
$label = $array[1]; # go to the next one
}
# now swap begin and end fields
($chain->{'begin'},$chain->{'end'})=($end,$begin);
return (1); # that's it
}
# warning that method has changed name
#sub mutate_element {
#croak "Warning: old method name. Please update code to 'set_value_at_label'\n";
# &set_value_at_label;
=head2 <API key>
Title : <API key>
Usage : $value = Bio::LiveSeq::Chain::<API key>($chain,$position,$first)
Function: used to access the value of the chain at a particular position instead than directly with a label pointer. It will count the position from the start of the chain or from the label $first, if $first is specified
Returns : whatever is stored in the element of the chain
Errorcode: 0
Args : reference to the chain, integer, [integer]
Note: It works "downstream". To proceed backward use up_get_value_at_pos
=cut
#sub get_value_at_pos {
#croak "Please use instead: <API key>";
##&<API key>;
sub <API key> {
my ($chain,$position,$first)=@_;
my $label=<API key>($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
return _get_value($chain,$label);
}
sub up_get_value_at_pos {
my ($chain,$position,$first)=@_;
my $label=up_get_label_at_pos($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
return _get_value($chain,$label);
}
=head2 <API key>
Title : <API key>
Usage : $errorcode = Bio::LiveSeq::Chain::<API key>($chain,$newvalue,$position,$first)
Function: used to store a new value inside an element of the chain at a particular position instead than directly with a label pointer. It will count the position from the start of the chain or from the label $first, if $first is specified
Returns : 1
Errorcode: 0
Args : reference to the chain, newvalue, integer, [integer]
(newvalue can be: integer, string, object reference, hash ref)
Note: It works "downstream". To proceed backward use up_set_value_at_pos
Note2: If the $newvalue is undef, it will delete the contents of the
element but it won't remove the element from the chain.
=cut
#sub set_value_at_pos {
#croak "Please use instead: <API key>";
##&<API key>;
sub <API key> {
my ($chain,$value,$position,$first)=@_;
my $label=<API key>($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
_set_value($chain,$label,$value);
return (1);
}
sub up_set_value_at_pos {
my ($chain,$value,$position,$first)=@_;
my $label=up_get_label_at_pos($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
_set_value($chain,$label,$value);
return (1);
}
=head2 <API key>
Title : <API key>
Usage : $errorcode = Bio::LiveSeq::Chain::<API key>($chain,$newvalue,$label)
Function: used to store a new value inside an element of the chain defined by its label.
Returns : 1
Errorcode: 0
Args : reference to the chain, newvalue, integer
(newvalue can be: integer, string, object reference, hash ref)
Note: It works "downstream". To proceed backward use <API key>
Note2: If the $newvalue is undef, it will delete the contents of the
element but it won't remove the element from the chain.
=cut
sub set_value_at_label {
my ($chain,$value,$label)=@_;
unless($chain) { cluck "no chain input"; return (0); }
# check place of change
unless($chain->{$label}) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
_set_value($chain,$label,$value);
return (1);
}
=head2 <API key>
Title : <API key>
Usage : $value = Bio::LiveSeq::Chain::<API key>($chain,$label)
Function: used to access the value of the chain from one element defined by its label.
Returns : whatever is stored in the element of the chain
Errorcode: 0
Args : reference to the chain, integer
Note: It works "downstream". To proceed backward use <API key>
=cut
sub get_value_at_label {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (0); }
my $label = $_[1]; # the name of the element
# check place of change
unless($chain->{$label}) { # complain if label doesn't exist
warn "not existing label $label"; return (0); }
return _get_value($chain,$label);
}
# arguments: CHAIN_REF LABEL VALUE
sub _set_value {
my ($chain,$label,$value)=@_;
$chain->{$label}[0]=$value;
}
# arguments: CHAIN_REF LABEL
sub _get_value {
my ($chain,$label)=@_;
return $chain->{$label}[0];
}
=head2 <API key>
Title : <API key>
Usage : $label = Bio::LiveSeq::Chain::<API key>($chain,$position,$first)
Function: used to retrieve the label of an an element of the chain at a particular position. It will count the position from the start of the chain or from the label $first, if $first is specified
Returns : integer
Errorcode: 0
Args : reference to the chain, integer, [integer]
Note: It works "downstream". To proceed backward use up_get_label_at_pos
=cut
# arguments: CHAIN_REF POSITION [FIRST]
# returns: LABEL of element found counting from FIRST
sub <API key> {
<API key>("down",@_);
}
sub up_get_label_at_pos {
<API key>("up",@_);
}
# arguments: [DIRECTION] CHAIN_REF POSITION [FIRST]
# Default DIRECTION="down"
# if FIRST is undefined, FIRST=START (if DIRECTION=down) or FIRST=END (up)
sub <API key> {
my ($direction,$chain,$position,$first)=@_;
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") { $flow=2; unless ($first) { $first=$end; }
} else { $flow=1; unless ($first) { $first=$begin; } }
unless($chain->{$first}) { warn "not existing label $first"; return (0); }
my $label=$first;
my $i=1;
while ($i < $position) {
$label=$chain->{$label}[$flow];
$i++;
unless ($label) { return (0); } # chain ended before position reached
}
return ($label);
}
# for english_concerned, latin_unconcerned people
sub preinsert_string { &praeinsert_string }
sub preinsert_array { &praeinsert_array }
# praeinsert_string CHAIN_REF STRING [POSITION]
# the chars of STRING are passed to praeinsert_array
# the chars are inserted in CHAIN, before POSITION
# if POSITION is undef, default is to prepend the string to the beginning
# i.e. POSITION is START of CHAIN
sub praeinsert_string {
my @string=split(
praeinsert_array($_[0],\@string,$_[2]);
}
# postinsert_string CHAIN_REF STRING [POSITION]
# the chars of STRING are passed to postinsert_array
# the chars are inserted in CHAIN, after POSITION
# if POSITION is undef, default is to append the string to the end
# i.e. POSITION is END of CHAIN
sub postinsert_string {
my @string=split(
postinsert_array($_[0],\@string,$_[2]);
}
# praeinsert_array CHAIN_REF ARRAY_REF [POSITION]
# the elements of ARRAY are inserted in CHAIN, before POSITION
# if POSITION is undef, default is to prepend the elements to the beginning
# i.e. POSITION is START of CHAIN
sub praeinsert_array {
<API key>($_[0],"prae",$_[1],$_[2]);
}
# postinsert_array CHAIN_REF ARRAY_REF [POSITION]
# the elements of ARRAY are inserted in CHAIN, after POSITION
# if POSITION is undef, default is to append the elements to the end
# i.e. POSITION is END of CHAIN
sub postinsert_array {
<API key>($_[0],"post",$_[1],$_[2]);
}
=head2 <API key>
Title : <API key>
Usage : ($insbegin,$insend) = Bio::LiveSeq::Chain::<API key>($chainref,"post",$arrayref,$position)
Function: the elements of the array specified by $arrayref are inserted (creating a new subchain) in the chain specified by $chainref, before or after (depending on the "prae"||"post" keyword passed as second argument) the specified position.
Returns : two labels: the first and the last of the inserted subchain
Defaults: if no position is specified, the new chain will be inserted after
(post) the first element of the chain
Errorcode: 0
Args : chainref, "prae"||"post", arrayref, integer (position)
=cut
# returns: 0 if errors, otherwise returns references of begin and end of
# the insertion
sub <API key> {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (0); }
my $praepost=$_[1] || "post"; # defaults to post
my ($prae,$post);
my $position=$_[3];
my $begin=$chain->{'begin'}; # the name of the first element of the chain
my $end=$chain->{'end'}; # the name of the the last element of the chain
# check if prae or post insertion and prepare accordingly
if ($praepost eq "prae") {
$prae=1;
unless (($position eq 0)||($position)) { $position=$begin; } # if undef, use $begin
} else {
$post=1;
unless (($position eq 0)||($position)) { $position=$end; } # if undef, use $end
}
# check place of insertion
unless($chain->{$position}) { # complain if position doesn't exist
warn ("Warning <API key>: not existing element $position");
return (0);
}
# check if there are elements to insert
my $elements=$_[2]; # reference to the array containing the new elements
my $elements_count=scalar(@{$elements});
unless ($elements_count) {
warn ("Warning <API key>: no elements input"); return (0); }
# create new chainelements with offset=firstfree(chain)
my ($insertbegin,$insertend)=<API key>($chain,$elements);
# DEBUGGING
#print "Executing ${praepost}insertion of $elements_count elements ('@{$elements}') at position: $position\n";
# attach the new chain to the old chain
# 4 cases: prae@begin, prae@middle, post@middle, post@end
# NOTE: in case of double joinings always join wisely so not to
# delete the PREV/NEXT attribute before it is needed
my $noerror=1;
if ($prae) {
if ($position==$begin) { # 1st case: prae@begin
$noerror=<API key>($chain,$insertend,$begin);
$chain->{'begin'}=$insertbegin;
} else { # 2nd case: prae@middle
$noerror=<API key>($chain,up_element($chain,$position),$insertbegin);
$noerror=<API key>($chain,$insertend,$position);
}
} elsif ($post) {
if ($position==$end) { # 4th case: post@end
$noerror=<API key>($chain,$end,$insertbegin);
$chain->{'end'}=$insertend;
} else { # 3rd case: post@middle # note the order of joins (important)
$noerror=<API key>($chain,$insertend,down_element($chain,$position));
$noerror=<API key>($chain,$position,$insertbegin);
}
} else { # this should never happen
die "<API key>: Something went very wrong";
}
# check for errors and return begin,end of insertion
if ($noerror) {
return ($insertbegin,$insertend);
} else { # something went wrong with the joinings
warn "Warning <API key>: Joining of insertion failed";
return (0);
}
}
# create new chain elements with offset=firstfree
# arguments: CHAIN_REF ARRAY_REF
# returns: pointers to BEGIN and END of new chained elements created
# returns 0 if error(s) encountered
sub <API key> {
my $chain=$_[0];
unless($chain) {
warn ("Warning <API key>: no chain input"); return (0); }
my $arrayref=$_[1];
my $array_count=scalar(@{$arrayref});
unless ($array_count) {
warn ("Warning <API key>: no elements input"); return (0); }
my $begin=$chain->{'firstfree'};
my $i=$begin-1;
my $element;
foreach $element (@{$arrayref}) {
$i++;
$chain->{$i}=[$element,$i+1,$i-1];
}
my $end=$i;
$chain->{'firstfree'}=$i+1; # what a new added element should be called
$chain->{'size'} += $end-$begin+1; # increase size of chain
# leave sticky edges (to be joined by whoever called this subroutine)
$chain->{$begin}[2]=undef;
$chain->{$end}[1]=undef;
return ($begin,$end); # return pointers to first and last of the newelements
}
# argument: CHAIN_REF ELEMENT
# returns: name of DOWN/NEXT element (the downstream one)
# returns -1 if error encountered (e.g. chain or elements undefined)
# returns 0 if there's no DOWN element
sub down_element {
_updown_element("down",@_);
}
# argument: CHAIN_REF ELEMENT
# returns: name of UP/PREV element (the upstream one)
# returns -1 if error encountered (e.g. chain or elements undefined)
# returns 0 if there's no UP element
sub up_element {
_updown_element("up",@_);
}
# used by both is_up_element and down_element
sub _updown_element {
my $direction=$_[0] || "down"; # defaults to downstream
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
} else {
$flow=1; # used to determine the direction of chain navigation
}
my $chain=$_[1];
unless($chain) {
warn ("Warning ${direction}_element: no chain input"); return (-1); }
my $me = $_[2]; # the name of the element
my $it = $chain->{$me}[$flow]; # the prev||next one, upstream||downstream
if ($it) {
return ($it); # return the name of prev||next element
} else {
return (0); # there is no prev||next element ($it is undef)
}
}
# used by both is_downstream and is_upstream
sub _is_updownstream {
my $direction=$_[0] || "down"; # defaults to downstream
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
} else {
$flow=1; # used to determine the direction of chain navigation
}
my $chain=$_[1];
unless($chain) {
warn ("Warning is_${direction}stream: no chain input"); return (-1); }
my $first=$_[2]; # the name of the first element
my $second=$_[3]; # the name of the first element
if ($first==$second) {
warn ("Warning is_${direction}stream: first==second!!"); return (0); }
unless($chain->{$first}) {
warn ("Warning is_${direction}stream: first element not defined"); return (-1); }
unless($chain->{$second}) {
warn ("Warning is_${direction}stream: second element not defined"); return (-1); }
my ($label,@array);
$label=$first;
my $found=0;
while (($label)&&(!($found))) { # searches till the end or till found
if ($label==$second) {
$found=1;
}
@array=@{$chain->{$label}};
$label = $array[$flow]; # go to the prev||next one, upstream||downstream
}
return $found;
}
=head2 is_downstream
Title : is_downstream
Usage : Bio::LiveSeq::Chain::is_downstream($chainref,$firstlabel,$secondlabel)
Function: checks if SECONDlabel follows FIRSTlabel
It runs downstream the elements of the chain from FIRST searching
for SECOND.
Returns : 1 if SECOND is found /after/ FIRST; 0 otherwise (i.e. if it
reaches the end of the chain without having found it)
Errorcode -1
Args : two labels (integer)
=cut
sub is_downstream {
_is_updownstream("down",@_);
}
=head2 is_upstream
Title : is_upstream
Usage : Bio::LiveSeq::Chain::is_upstream($chainref,$firstlabel,$secondlabel)
Function: checks if SECONDlabel follows FIRSTlabel
It runs upstream the elements of the chain from FIRST searching
for SECOND.
Returns : 1 if SECOND is found /after/ FIRST; 0 otherwise (i.e. if it
reaches the end of the chain without having found it)
Errorcode -1
Args : two labels (integer)
=cut
sub is_upstream {
_is_updownstream("up",@_);
}
=head2 check_chain
Title : check_chain
Usage : @errorcodes = Bio::LiveSeq::Chain::check_chain()
Function: a wraparound to a series of check for consistency of the chain
It will check for boundaries, size, backlinking and forwardlinking
Returns : array of 4 warn codes, each can be 1 (all ok) or 0 (something wrong)
Errorcode: 0
Args : none
Note : this is slow and through. It is not really needed. It is mostly
a code-developer tool.
=cut
sub check_chain {
my $chain=$_[0];
unless($chain) {
warn ("Warning check_chain: no chain input"); return (-1); }
my ($warnbound,$warnsize,$warnbacklink,$warnforlink);
$warnbound=&_boundcheck; # passes on the arguments of the subroutine
$warnsize=&_sizecheck;
$warnbacklink=&_downlinkcheck;
$warnforlink=&_uplinkcheck;
return ($warnbound,$warnsize,$warnbacklink,$warnforlink);
}
# consistency check for forwardlinks walking upstream
# argument: a chain reference
# returns: 1 all OK 0 problems
sub _uplinkcheck {
_updownlinkcheck("up",@_);
}
# consistency check for backlinks walking downstream
# argument: a chain reference
# returns: 1 all OK 0 problems
sub _downlinkcheck {
_updownlinkcheck("down",@_);
}
# consistency check for links, common to _uplinkcheck and _downlinkcheck
# argument: "up"||"down", check_ref
# returns: 1 all OK 0 problems
sub _updownlinkcheck {
my $direction=$_[0] || "down"; # defaults to downstream
my ($flow,$wolf);
my $chain=$_[1];
unless($chain) {
warn ("Warning _${direction}linkcheck: no chain input"); return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the last element
my ($label,@array,$me,$it,$itpoints);
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
$wolf=1;
$label=$end; # start from end
} else {
$flow=1; # used to determine the direction of chain navigation
$wolf=2;
$label=$begin; # start from beginning
}
my $warncode=1;
while ($label) { # proceed with linked elements, checking neighbours
$me=$label;
@array=@{$chain->{$label}};
$label = $array[$flow]; # go to the next one
$it=$label;
if ($it) { # no sense in checking if next one not defined (END element)
@array=@{$chain->{$label}};
$itpoints=$array[$wolf];
unless ($me==$itpoints) {
warn "Warning: ${direction}LinkCheck: LINK wrong in $it, that doesn't point back to me ($me). It points to $itpoints\n";
$warncode=0;
}
}
}
return $warncode;
}
# consistency check for size of chain
# argument: a chain reference
# returns: 1 all OK 0 wrong size
sub _sizecheck {
my $chain=$_[0];
unless($chain) {
warn ("Warning _sizecheck: no chain input"); return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $warncode=1;
my ($label,@array);
my $size=$chain->{'size'};
my $count=0;
$label=$begin;
while ($label) { # proceed with linked elements, counting
@array=@{$chain->{$label}};
$label = $array[1]; # go to the next one
$count++;
}
if ($size != $count) {
warn "Size check reports error: assumed size: $size, real size: $count ";
$warncode=0;
}
return $warncode;
}
# consistency check for begin and end (boundaries)
# argument: a chain reference
# returns: 1 all OK 0 problems
sub _boundcheck {
my $chain=$_[0];
unless($chain) {
warn ("Warning _boundcheck: no chain input"); return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the (supposedly) last element
my $warncode=1;
# check SYNC of beginning
if (($begin)&&($chain->{$begin})) { # if the BEGIN points to existing element
if ($chain->{$begin}[2]) { # if BEGIN element has PREV not undef
warn "Warning: BEGIN element has PREV field defined \n";
warn "\tWDEBUG begin: $begin\t";
warn "\tWDEBUG begin's PREV: $chain->{$begin}[2] \n";
$warncode=0;
}
} else {
warn "Warning: BEGIN key of chain does not point to existing element!\n";
warn "\tWDEBUG begin: $begin\n";
$warncode=0;
}
# check SYNC of end
if (($end)&&($chain->{$end})) { # if the END points to an existing element
if ($chain->{$end}[1]) { # if END element has NEXT not undef
warn "Warning: END element has NEXT field defined \n";
warn "\tWDEBUG end: $end\t";
warn "\tWDEBUG end's NEXT: $chain->{$end}[1] \n";
$warncode=0;
}
} else {
warn "Warning: END key of chain does not point to existing element!\n";
warn "\tWDEBUG end: $end\n";
$warncode=0;
}
return $warncode;
}
# arguments: chain_ref
# returns: the size of the chain (the number of elements)
# return code -1: unexistant chain, errors...
sub chain_length {
my $chain=$_[0];
unless($chain) {
warn ("Warning chain_length: no chain input"); return (-1); }
my $size=$chain->{'size'};
if ($size) {
return ($size);
} else {
return (-1);
}
}
# arguments: chain ref, first element name, second element name
# returns: 1 or 0 (1 ok, 0 errors)
sub <API key> {
my $chain=$_[0];
unless($chain) {
warn ("Warning <API key>: no chain input"); return (0); }
my $leftelem=$_[1];
my $rightelem=$_[2];
unless(($leftelem)&&($rightelem)) {
warn ("Warning <API key>: element arguments??"); return (0); }
if (($chain->{$leftelem})&&($chain->{$rightelem})) { # if the elements exist
$chain->{$leftelem}[1]=$rightelem;
$chain->{$rightelem}[2]=$leftelem;
return 1;
} else {
warn ("Warning <API key>: elements not defined");
return 0;
}
}
=head2 splice_chain
Title : splice_chain
Usage : @errorcodes = Bio::LiveSeq::Chain::splice_chain($chainref,$first,$length,$last)
Function: removes the elements designated by FIRST and LENGTH from a chain.
The chain shrinks accordingly. If LENGTH is omitted, removes
everything from FIRST onward.
If END is specified, LENGTH is ignored and instead the removal
occurs from FIRST to LAST.
Returns : the elements removed as a string
Errorcode: -1
Args : chainref, integer, integer, integer
=cut
sub splice_chain {
my $chain=$_[0];
unless($chain) {
warn ("Warning splice_chain: no chain input"); return (-1); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the (supposedly) last element
my $first=$_[1];
unless (($first eq 0)||($first)) { $first=$begin; } # if undef, use $begin
my $len=$_[2];
my $last=$_[3];
my (@array, $string);
my ($beforecut,$aftercut);
unless($chain->{$first}) {
warn ("Warning splice_chain: first element not defined"); return (-1); }
if ($last) { # if last is defined, it gets priority and len is not used
unless($chain->{$last}) {
warn ("Warning splice_chain: last element not defined"); return (-1); }
if ($len) {
warn ("Warning splice_chain: argument LAST:$last overriding LEN:$len!");
undef $len;
}
} else {
$last=$end; # if last not defined, go 'till end (or to len, whichever 1st)
}
$beforecut=$chain->{$first}[2]; # what's the element before 1st deleted?
# if it is undef then it means we are splicing since the beginning
my $i=1;
my $label=$first;
my $afterlast=$chain->{$last}[1]; # if $last=$end $afterlast should be undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
# proceed for len elements or until the end, whichever comes first
# if len undef goes till last
while (($label)&&($label != $afterlast) && ($i <= ($len || $i + 1))) {
@array=@{$chain->{$label}};
$string .= $array[0];
$aftercut = $array[1]; # what's the element next last deleted?
# also used as savevar to change label posdeletion
delete $chain->{$label}; # this can be deleted now
$label=$aftercut; # label is updated using the savevar
$i++;
}
# Now fix the chain (sticky edges, fields)
# 4 cases: cut in the middle, cut from beginning, cut till end, cut all
#print "\n\tstickyDEBUG beforecut: $beforecut "; # DEBUG
#print "\taftercut: $aftercut \n"; # DEBUG
if ($beforecut) {
if ($aftercut) { # 1st case, middle cut
<API key>($chain,$beforecut,$aftercut);
} else { # 3rd case, end cut
$chain->{'end'}=$beforecut; # update the END field
$chain->{$beforecut}[1]=undef; # since we cut till the end
}
} else {
if ($aftercut) { # 2nd case, begin cut
$chain->{'begin'}=$aftercut; # update the BEGIN field
$chain->{$aftercut}[2]=undef; # since we cut from beginning
} else { # 4th case, all has been cut
$chain->{'begin'}=undef;
$chain->{'end'}=undef;
}
}
$chain->{'size'}=($chain->{'size'}) - $i + 1; # update the SIZE field
return $string;
}
# arguments: CHAIN_REF POSITION [FIRST]
# returns: element counting POSITION from FIRST or from START if FIRST undef
# i.e. returns the element at POSITION counting from FIRST
#sub element_at_pos {
#croak "Warning: old method name. Please update code to '<API key>'\n";
##&down_element_at_pos;
#sub up_element_at_pos {
## old wraparound
##my @array=up_chain2string($_[0],$_[2],$_[1],undef,"elements");
##return $array[-1];
#croak "old method name. Update code to: <API key>";
##&up_get_label_at_pos;
#sub down_element_at_pos {
## old wraparound
##my @array=down_chain2string($_[0],$_[2],$_[1],undef,"elements");
##return $array[-1];
#croak "old method name. Update code to: <API key>";
##&<API key>;
# arguments: CHAIN_REF ELEMENT [FIRST]
# returns: the position of ELEMENT counting from FIRST or from START
#i if FIRST is undef
# i.e. returns the Number of elements between FIRST and ELEMENT
# i.e. returns the position of element taking FIRST as 1 of coordinate system
#sub pos_of_element {
#croak ("Warning: old and ambiguous method name. Please update code to '<API key>'\n");
##&down_pos_of_element;
#sub up_pos_of_element {
#croak ("Warning: old method name. Please update code to 'up_get_pos_of_label'\n");
##up_chain2string($_[0],$_[2],undef,$_[1],"counting");
#sub down_pos_of_element {
#croak ("Warning: old method name. Please update code to '<API key>'\n");
##down_chain2string($_[0],$_[2],undef,$_[1],"counting");
# wraparounds to calculate length of subchain from first to last
# arguments: chain_ref [first] [last]
#sub subchain_length {
#croak "Warning: old method name. Please update code to '<API key>'\n";
##&<API key>;
# wraparounds to have elements output
# same arguments as chain2string
# returns label|name of every element
#sub elements {
#croak ("Warning: method no more supported. Please update code to 'down_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n");
##&down_elements;
#sub up_elements {
#croak ("Warning: method no more supported. Please update code to 'up_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n");
##up_chain2string($_[0],$_[1],$_[2],$_[3],"elements");
#sub down_elements {
#croak ("Warning: method no more supported. Please update code to 'down_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n");
##down_chain2string($_[0],$_[1],$_[2],$_[3],"elements");
# wraparounds to have verbose output
# same arguments as chain2string
# returns the chain in a very verbose way
sub <API key> {
carp "Warning: method no more supported.\n";
&<API key>;
}
sub <API key> {
carp "Warning: method no more supported.\n";
old_up_chain2string($_[0],$_[1],$_[2],$_[3],"verbose");
}
sub <API key> {
carp "Warning: method no more supported.\n";
<API key>($_[0],$_[1],$_[2],$_[3],"verbose");
}
#sub chain2string {
#croak ("Warning: old method name. Please update code to 'down_chain2string'\n");
##&down_chain2string;
sub old_up_chain2string {
<API key>("up",@_);
}
sub <API key> {
<API key>("down",@_);
}
# common to up_chain2string and down_chain2string
# arguments: "up"||"down" chain_ref [first] [len] [last] [option]
# [option] can be any of "verbose", "counting", "elements"
# error: return -1
# defaults: start = first element; if len undef, goes to last
# if last undef, goes to end
# if last def it overrides len (that gets undef)
# returns: a string
# example usage: down_chain2string($chain) -> all the chain from begin to end
# example usage: down_chain2string($chain,6) -> from 6 to the end
# example usage: down_chain2string($chain,6,4) -> from 6, going on 4 elements
# example usage: down_chain2string($chain,6,"",10) -> from 6 to 10
# example usage: up_chain2string($chain,10,"",6) -> from 10 to 6 upstream
sub <API key> {
my ($direction,$chain,$first,$len,$last,$option)=@_;
unless($chain) {
warn ("Warning chain2string: no chain input"); return (-1); }
my $begin=$chain->{'begin'}; # the name of the BEGIN element
my $end=$chain->{'end'}; # the name of the END element
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
unless ($first) { $first=$end; } # if undef or 0, use $end
} else { # defaults to "down"
$flow=1; # used to determine the direction of chain navigation
unless ($first) { $first=$begin; } # if undef or 0, use $begin
}
unless($chain->{$first}) {
warn ("Warning chain2string: first element not defined"); return (-1); }
if ($last) { # if last is defined, it gets priority and len is not used
unless($chain->{$last}) {
warn ("Warning chain2string: last element not defined"); return (-1); }
if ($len) {
warn ("Warning chain2string: argument LAST:$last overriding LEN:$len!");
undef $len;
}
} else {
if ($direction eq "up") {
$last=$begin; # if last not defined, go 'till begin (or upto len elements)
} else {
$last=$end; # if last not defined, go 'till end (or upto len elements)
}
}
my (@array, $string, $count);
# call for verbosity (by way of <API key>);
my $verbose=0; my $elements=0; my @elements; my $counting=0;
if ($option) { # keep strict happy
if ($option eq "verbose") { $verbose=1; }
if ($option eq "elements") { $elements=1; }
if ($option eq "counting") { $counting=1; }
}
if ($verbose) {
print "BEGIN=$begin"; print " END=$end"; print " SIZE=$chain->{'size'}";
print " FIRSTFREE=$chain->{'firstfree'} \n";
}
my $i=1;
my $label=$first;
my $afterlast=$chain->{$last}[$flow]; # if $last=$end $afterlast should be undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
# proceed for len elements or until last, whichever comes first
# if $len undef goes till end
while (($label)&&($label != $afterlast) && ($i <= ($len || $i + 1))) {
@array=@{$chain->{$label}};
if ($verbose) {
$string .= "$array[2]_${label}_$array[1]=$array[0] ";
$count++;
} elsif ($elements) {
push (@elements,$label); # returning element names/references/identifiers
} elsif ($counting) {
$count++;
} else {
$string .= $array[0]; # returning element content
}
$label = $array[$flow]; # go to next||prev i.e. downstream||upstream
$i++;
}
#DEBUG#print "len: $len, first: $first, last: $last, afterlast=$afterlast \n";
if ($verbose) { print "TOTALprinted: $count\n"; }
if ($counting) {
return $count;
} elsif ($elements) {
return @elements;
} else {
return $string;
}
}
# sub string2schain
# creation of a single linked list/chain from a string
# omitting to set the 3rd field (label 2) containing the back links
# creation of a double linked list/chain from a string
# returns reference to a hash containing the chain
# arguments: STRING [OFFSET]
# defaults: OFFSET defaults to 1 if undef
# the chain will contain as elements the single characters in the string
sub string2chain {
my @string=split(
array2chain(\@string,$_[1]);
}
=head2 array2chain
Title : array2chain
Usage : $chainref = Bio::LiveSeq::Chain::array2chain($arrayref,$offset)
Function: creation of a double linked chain from an array
Returns : reference to a hash containing the chain
Defaults: OFFSET defaults to 1 if undef
Error code: 0
Args : a reference to an array containing the elements to be chainlinked
an optional integer > 0 (this will be the starting count for
the chain labels instead than having them begin from "1")
=cut
sub array2chain {
my $arrayref=$_[0];
my $array_count=scalar(@{$arrayref});
unless ($array_count) {
warn ("Warning array2chain: no elements input"); return (0); }
my $begin=$_[1];
if (defined $begin) {
if ($begin < 1) {
warn "Warning array2chain: Zero or Negative offsets not allowed"; return (0); }
} else {
$begin=1;
}
my ($element,%hash);
$hash{'begin'}=$begin;
my $i=$begin-1;
foreach $element (@{$arrayref}) {
$i++;
# hash with keys begin..end pointing to the arrays
$hash{$i}=[$element,$i+1,$i-1];
}
my $end=$i;
$hash{'end'}=$end;
$hash{firstfree}=$i+1; # what a new added element should be called
$hash{size}=$end-$begin+1; # how many elements in the chain
# eliminate pointers to unexisting elements
$hash{$begin}[2]=undef;
$hash{$end}[1]=undef;
return (\%hash);
}
1; # returns 1
|
(function () {
'use strict';
angular.module('driver.tools.export', [
'ui.bootstrap',
'ui.router',
'driver.customReports',
'driver.resources',
'angular-spinkit',
]);
})();
|
"use strict";
exports.__esModule = true;
var vueClient_1 = require("../../bibliotheque/vueClient");
console.log("* Chargement du script");
function centreNoeud() {
return JSON.parse(vueClient_1.contenuBalise(document, 'centre'));
}
function voisinsNoeud() {
var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins'));
var r = [];
var id;
for (id in v) {
r.push(v[id]);
}
return r;
}
function adresseServeur() {
return vueClient_1.contenuBalise(document, 'adresseServeur');
}
//# sourceMappingURL=clientChat.js.map
|
(function ($) {
function FewbricksDevHelper() {
var $this = this;
this.init = function() {
$this.cssClassFull = '<API key>';
if(!$this.initMainElm()) {
return;
}
$this.initToggler();
$this.$mainElm.show();
}
this.initMainElm = function() {
$this.$mainElm = $('#fewbricks-info-pane');
if($this.$mainElm.length === 0) {
return false;
}
if(typeof fewbricksInfoPane !== 'undefined' && typeof fewbricksInfoPane.startHeight !== 'undefined') {
$this.toggleMainElm(fewbricksInfoPane.startHeight);
}
return true;
}
this.initToggler = function() {
$('[<API key>]')
.unbind('click')
.on('click', function() {
let height = $(this).attr('<API key>');
$this.toggleMainElm(height);
document.cookie = '<API key>=' + height;
});
}
this.toggleMainElm = function(height) {
if(height === 'minimized') {
$this.$mainElm.attr('style', function(i, style)
{
return style && style.replace(/height[^;]+;?/g, '');
});
} else {
$this.$mainElm.height(height + 'vh');
}
}
/**
*
* @returns {*|boolean}
*/
this.mainElmIsFull = function() {
return $this.$mainElm.hasClass($this.cssClassFull);
}
}
$(document).ready(function () {
(new FewbricksDevHelper()).init();
});
})(jQuery);
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#ifndef <API key>
#define <API key>
#include "nsSVGPolyElement.h"
nsresult <API key>(nsIContent **aResult,
already_AddRefed<nsINodeInfo> aNodeInfo);
typedef nsSVGPolyElement <API key>;
namespace mozilla {
namespace dom {
class SVGPolylineElement MOZ_FINAL : public <API key>
{
protected:
SVGPolylineElement(already_AddRefed<nsINodeInfo> aNodeInfo);
virtual JSObject* WrapNode(JSContext *cx, JSObject *scope) MOZ_OVERRIDE;
friend nsresult (::<API key>(nsIContent **aResult,
already_AddRefed<nsINodeInfo> aNodeInfo));
public:
// nsIContent interface
virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
};
} // namespace mozilla
} // namespace dom
#endif // <API key>
|
/**
* ...
* @author paul
*/
function initCBX(object, id, options) {
var design = "assets";
if(object == null){
jQuery.noConflict();
var cboxClass;
cboxClass = jQuery(id).attr("class");
if(jQuery.browser.msie && parseInt(jQuery.browser.version)<8 ){
jQuery(id).colorbox();
}
else{
if(cboxClass.indexOf("cboxElement") == -1){
if(options.classes.image.id){
jQuery('.'+options.classes.image.id).colorbox({transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
if(options.classes.video){
if(options.classes.video.id){
jQuery('.'+options.classes.video.id).colorbox({iframe:true, innerWidth:options.classes.video.innerWidth, innerHeight:options.classes.video.innerHeight, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
if(options.classes.swf){
if(options.classes.swf.id){
var cbxSWFSrc = jQuery('.'+options.classes.swf.id).attr("href");
var objEmbd = '<OBJECT classid="clsid:<API key>" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" id="cbxSWF" ALIGN="">'+
'<PARAM NAME=movie VALUE="'+cbxSWFSrc+'">' +
'<PARAM NAME=quality VALUE=high>' +
'<PARAM NAME=wmode VALUE=transparent>'+
'<PARAM NAME=bgcolor VALUE=#333399>'+
'<EMBED src="'+cbxSWFSrc+'" quality=high wmode=transparent WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http:
'</OBJECT>';
jQuery('.'+options.classes.swf.id).colorbox({html:objEmbd, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
}
}
jQuery(id).trigger('click');
return;
}
loadjQuery = function(filename) {
loadjQuery.getScript(object.path+"/"+filename);
loadjQuery.retry(0);
}
loadColorbox = function(filename) {
loadColorbox.getScript(object.path+"/"+filename);
loadColorbox.retry(0);
}
loadjQuery.getScript = function(filename) {
if(typeof jQuery == "undefined"){
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.<API key>("head")[0].appendChild(script);
}
}
loadColorbox.getScript = function(filename) {
if(typeof jQuery.colorbox == "undefined"){
var link = document.createElement('link');
link.setAttribute('media', 'screen');
link.setAttribute('href', object.path+'/'+design+'/colorbox.css');
link.setAttribute('rel', 'stylesheet');
document.<API key>("head")[0].appendChild(link);
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.<API key>("head")[0].appendChild(script);
}
}
loadjQuery.retry = function(time_elapsed) {
if (typeof jQuery == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadjQuery.retry(" + (time_elapsed + 200) + ")", 200);
}
}
else {
if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
}
loadColorbox.retry = function(time_elapsed) {
if (typeof jQuery.colorbox == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadColorbox.retry(" + (time_elapsed + 200) + ")", 200);
}
}
}
if(typeof jQuery == "undefined"){
loadjQuery("jquery-1.7.2.min.js");
}
else if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
|
#include "gx2r_buffer.h"
#include "gx2r_displaylist.h"
#include "gx2_displaylist.h"
#include <common/log.h>
namespace gx2
{
void
<API key>(GX2RBuffer *displayList,
uint32_t unused,
GX2RResourceFlags flags)
{
if (!displayList || !displayList->buffer) {
return;
}
auto size = displayList->elemCount * displayList->elemSize;
<API key>(displayList->buffer, size, TRUE);
}
uint32_t
GX2REndDisplayList(GX2RBuffer *displayList)
{
auto size = GX2EndDisplayList(displayList->buffer);
decaf_check(size < (displayList->elemCount * displayList->elemSize));
return size;
}
void
GX2RCallDisplayList(GX2RBuffer *displayList,
uint32_t size)
{
if (!displayList || !displayList->buffer) {
return;
}
GX2CallDisplayList(displayList->buffer, size);
}
void
<API key>(GX2RBuffer *displayList,
uint32_t size)
{
if (!displayList || !displayList->buffer) {
return;
}
<API key>(displayList->buffer, size);
}
} // namespace gx2
|
<!DOCTYPE html>
<html xmlns="http:
<head>
<title>LamPI 433Mhz controller for RaspberryPI</title>
</head>
<body>
<h1>Weather Dials/Meters </h1>
<p>This part of the documentation describes the weather screen and what you can (and sometimes cannot) do with weather sensors. Since version 1.8 LamPI does support weather station sensors. At first only the UPM WT440H (outdoor) sensor is supported and it works fine. Other sensors can be added to the LamPI-receiver/sniffer program later, but it is good to know that the LamPI-daemon offers support for receiving Json messages from weather sensors.</p>
<p>If you like to know more about te various sensors, check out their "hardware" pages. </p>
<ul>
<li><a href="../HardwareGuide/433-Sensors/wt440h/wt440h.html">WT-440H</a> for information about the WT-440H temperature and humidity sensor (433MHz unit)</li>
</ul>
<p>Of course temperature sensors can be meaningful in weather context, but also be used in energy applications. In the application I make that distinction (for the moment) as I expect most temperature, humidity and pressure sensors to be used most in context of weather. However, users are free to choose differently. As soon as I have my smart-meter up and running I will have a look at the energy sensors and their application as well.</p>
<p>Below you see a screenshot of the weather screen...</p>
<p><img src="screenshots/weather_screen_1.JPG" width="966" height="637" /></p>
<p> </p>
<h1>Weather Charts</h1>
<p>When clicking in the weather screen on one of the dials, a separate screen will open that shows historical data for the weather sensors. This function is described separately in the section for rrd graphs.</p>
<p><img src="screenshots/rrd_screen_01.JPG" width="963" height="636"></p>
<h1>Json message format for sensors</h1>
<p>The Json message that is sent to the LamPI-daemon is as follows:</p>
<p><code>message = {<br>
tcnt : integer,<br>
type : 'json',<br>
action : 'weather',<br>
brand: wt440h # or other supported brand<br>
address: integer, # (house code)<br>
channel: integer,<br>
temperature: integer.integer<br>
humidity: integer,<br>
windspeed: integer,<br>
winddirection: integer, # in degrees<br>
rainfall : char(8) # (mm per hour)</code></p>
<p><code>}; </code><br>
</p>
<h1>Adding a new wireless Weather sensor</h1>
<p>Weather sensors that are wireless 433MHz can be added to the LamPI-receiver by making a sensor function in C and including it in the receiver.c file and in the Makefile. The LamPI-receiver program in the ~/exe directory is the ONLY receiver for 433HMz messages and will handle all forwarding of successful receptions to the LamPI-daemon.</p>
<p>Next to the program itself, the sensor needs to be declared in the database.cfg file so that the LamPI-deamon knows that the incoming message for this address/channel is a source that we trust and allow access to our application.</p>
<p> </p>
<h1>Adding new wired sensors</h1>
<p>Adding wired sensors can be one of the following:</p>
<ol>
<li>A wired sensor without a bus</li>
<li>The 1-wire Dallas bus</li>
<li>A sensor with I2C support</li>
</ol>
<p>For more info on wired weather sensors, read the <a href="../HardwareGuide/Wired-Sensors/<API key>.html">sensors.html</a> page </p>
<h1>Logging our Sensor data</h1>
<p>The LamPI-daemon will listen to all incoming json messages on its port 5000. Incoing messages from sensors will be matched against the configuration items in the database.cfg file for missing data such as names, location etc that are not sensor defined but defined by the user.</p>
<p>But in order to watch trends in data and analyze the collected data we need to add logging capabilities to the LamPI environment. There are several options:</p>
<ol>
<li>Make LamPI-daemon store all collected data in a logfile and use Excel to analyze the data</li>
<li>Make a logging process tat listens to port 5000 and be informed ot every json message that is processed by the daemon.</li>
<li>Use an external PAAS service provider, forward all messages received to the service provider and use its analyzing functions to make sense of your data.</li>
</ol>
<p>The third option is attractive, as it will use external storage, services etc. to look at our data and the trend graphs are accessible from anywhere on the internet. The PAAS provider carriots.com provides this service for free for small users with up to 10 data streams.</p>
<h3>re. Store in local logfile</h3>
<p>The easiest method for analysing sensor data is to store all data collected to a local logfile on the PI, and import this file into excel on regular intervals. This is simple solution, and this also how I started.</p>
<h3>re 2. Logging to rrdtool</h3>
<p>There is a tools based on a round robin database tool that can be used to store sensors data and display graphs. </p>
<h3>re 3. PAAS. Use a tool like Carriots</h3>
<p>The PAAS (Platform As A Service) provider carriots.com provides a free membership for data analysis of a limited set of sensors.</p>
<p> </p>
</body>
</html>
|
CKEDITOR.plugins.setLang( 'newpage', 'eo', {
toolbar: 'Nova Paĝo'
} );
|
// $Id: <API key>.java 41 2010-04-03 20:04:12Z marcusvnac $
// software and its documentation without fee, and without a written
// and this paragraph appear in all copies. This software program and
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.foundation.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.argouml.i18n.Translator;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.Model;
import org.argouml.uml.ui.<API key>;
/**
* An Action to add client dependencies to some modelelement.
*
* @author Michiel
*/
public class <API key> extends
<API key> {
/**
* The constructor.
*/
public <API key>() {
super();
setMultiSelect(true);
}
/*
* Constraint: This code only deals with 1 supplier per dependency!
* TODO: How to support more?
*
* @see org.argouml.uml.ui.<API key>#doIt(java.util.List)
*/
protected void doIt(Collection selected) {
Set oldSet = new HashSet(getSelected());
for (Object client : selected) {
if (oldSet.contains(client)) {
oldSet.remove(client); //to be able to remove dependencies later
} else {
Model.getCoreFactory().buildDependency(getTarget(), client);
}
}
Collection toBeDeleted = new ArrayList();
Collection dependencies = Model.getFacade().<API key>(
getTarget());
for (Object dependency : dependencies) {
if (oldSet.containsAll(Model.getFacade().getSuppliers(dependency))) {
toBeDeleted.add(dependency);
}
}
ProjectManager.getManager().getCurrentProject()
.moveToTrash(toBeDeleted);
}
/*
* @see org.argouml.uml.ui.<API key>#getChoices()
*/
protected List getChoices() {
List ret = new ArrayList();
Object model =
ProjectManager.getManager().getCurrentProject().getModel();
if (getTarget() != null) {
ret.addAll(Model.<API key>()
.<API key>(model,
"org.omg.uml.foundation.core.ModelElement"));
ret.remove(getTarget());
}
return ret;
}
/*
* @see org.argouml.uml.ui.<API key>#getDialogTitle()
*/
protected String getDialogTitle() {
return Translator.localize("dialog.title.<API key>");
}
/*
* @see org.argouml.uml.ui.<API key>#getSelected()
*/
protected List getSelected() {
List v = new ArrayList();
Collection c = Model.getFacade().<API key>(getTarget());
for (Object cd : c) {
v.addAll(Model.getFacade().getSuppliers(cd));
}
return v;
}
}
|
require 'spec_helper'
require 'rubybot/plugins/tweet'
require 'support/twitter_mock'
RSpec.describe Rubybot::Plugins::Tweet do
include Cinch::Test
describe '#commands' do
subject { described_class.new(make_bot).commands }
it('returns a single command') { is_expected.to have_exactly(1).items }
end
let(:bot) { make_bot described_class, <API key>(described_class) }
it 'doesn\'t match an unrelated url' do
expect(get_replies make_message(bot, 'asdf')).to have_exactly(0).items
end
it 'gives tweet data for a twitter url' do
replies = get_replies make_message(bot,
'https://twitter.com/AUser/status/43212344123',
channel: 'a')
expect(replies).to have_exactly(1).items
expect(replies.first.event).to eq :message
expect(replies.first.text).to eq '@AUser: asdf'
end
end
|
var searchData=
[
['transfer_20commands',['Transfer Commands',['../<API key>.html',1,'']]]
];
|
Public Class RotationTile
Inherits Entity
Public Enum RotationTypes
StartSpin
StopSpin
End Enum
Dim RotationType As RotationTypes
Dim RotateTo As Integer = 0
Public Overrides Sub Initialize()
MyBase.Initialize()
Select Case Me.ActionValue
Case 0
Me.RotationType = RotationTypes.StartSpin
Case 1
Me.RotationType = RotationTypes.StopSpin
End Select
Me.RotateTo = CInt(Me.AdditionalValue)
Me.NeedsUpdate = True
End Sub
Public Overrides Sub Update()
If Me.RotationType = RotationTypes.StartSpin Then
If Core.CurrentScreen.Identification = Screen.Identifications.OverworldScreen Then
If CType(Core.CurrentScreen, OverworldScreen).ActionScript.IsReady = True Then
If Me.Position.X = Screen.Camera.Position.X And CInt(Me.Position.Y) = CInt(Screen.Camera.Position.Y) And Me.Position.Z = Screen.Camera.Position.Z Then
Dim steps As Integer = GetSteps()
Dim s As String = "version=2" & vbNewLine &
"@player.move(0)" & vbNewLine &
"@player.turnto(" & Me.RotateTo.ToString() & ")" & vbNewLine &
"@player.move(" & steps & ")" & vbNewLine &
":end"
CType(Core.CurrentScreen, OverworldScreen).ActionScript.StartScript(s, 2)
End If
End If
End If
End If
End Sub
Private Function GetSteps() As Integer
Dim steps As Integer = 0
Dim direction As Vector2 = New Vector2(0)
Select Case Me.RotateTo
Case 0
direction.Y = -1
Case 1
direction.X = -1
Case 2
direction.Y = 1
Case 3
direction.X = 1
End Select
Dim stepY As Integer = CInt(direction.Y)
If stepY = 0 Then
stepY = 1
End If
For x = 0 To direction.X * 100 Step direction.X
For y = 0 To direction.Y * 100 Step stepY
Dim p As Vector3 = New Vector3(x, 0, y) + Me.Position
For Each e As Entity In Screen.Level.Entities
If e.Equals(Me) = False Then
If e.EntityID.ToLower() = "rotationtile" Then
If CInt(e.Position.X) = CInt(p.X) And CInt(e.Position.Y) = CInt(p.Y) And CInt(e.Position.Z) = CInt(p.Z) Then
GoTo theend
End If
End If
End If
Next
steps += 1
Next
Next
theend:
Return steps
End Function
Public Overrides Sub Render()
Me.Draw(Me.Model, Textures, False)
End Sub
Public Overrides Function LetPlayerMove() As Boolean
Return Me.RotationType = RotationTypes.StopSpin
End Function
Public Overrides Function WalkIntoFunction() As Boolean
If Me.RotationType = RotationTypes.StartSpin Then
CType(Screen.Camera, OverworldCamera).YawLocked = True
End If
Return False
End Function
End Class
|
#!/bin/bash
# Butterfly root
BUTTERFLY_ROOT=$(cd "$(dirname $0)/.." && pwd)
sources="$BUTTERFLY_ROOT/api/client/client.cc \
$BUTTERFLY_ROOT/api/client/client.h \
$BUTTERFLY_ROOT/api/client/nic.cc \
$BUTTERFLY_ROOT/api/client/request.cc \
$BUTTERFLY_ROOT/api/client/sg.cc \
$BUTTERFLY_ROOT/api/client/shutdown.cc \
$BUTTERFLY_ROOT/api/client/status.cc \
$BUTTERFLY_ROOT/api/client/dump.cc \
$BUTTERFLY_ROOT/api/server/app.cc \
$BUTTERFLY_ROOT/api/server/app.h \
$BUTTERFLY_ROOT/api/server/server.cc \
$BUTTERFLY_ROOT/api/server/server.h \
$BUTTERFLY_ROOT/api/server/model.cc \
$BUTTERFLY_ROOT/api/server/model.h \
$BUTTERFLY_ROOT/api/server/api.cc \
$BUTTERFLY_ROOT/api/server/api.h \
$BUTTERFLY_ROOT/api/server/api_0.cc \
$BUTTERFLY_ROOT/api/server/graph.cc \
$BUTTERFLY_ROOT/api/server/graph.h \
$BUTTERFLY_ROOT/api/common/crypto.cc \
$BUTTERFLY_ROOT/api/common/crypto.h"
$BUTTERFLY_ROOT/scripts/cpplint.py --filter=-build/c++11 --root=$BUTTERFLY_ROOT $sources
if [ $? != 0 ]; then
echo "${RED}API style test failed${NORMAL}"
exit 1
fi
cppcheck &> /dev/null
if [ $? != 0 ]; then
echo "cppcheck is not installed, some tests will be skipped"
else
cppcheck --check-config --error-exitcode=1 --enable=all -I $BUTTERFLY_ROOT $sources &> /tmp/cppcheck.log
if [ $? != 0 ]; then
cat /tmp/cppcheck.log
echo "${RED}API style test failed${NORMAL}"
rm /tmp/cppcheck.log
exit 1
fi
fi
rm /tmp/cppcheck.log
rm /tmp/has_tabs &> /dev/null || true
for f in api benchmarks doc scripts tests; do
find $BUTTERFLY_ROOT/$f -name *.sh | while read a; do
if [ "-$(cat $a | grep -P '\t')" != "-" ]; then
echo found tab in $a
touch /tmp/has_tabs
fi
done
done
if test -f /tmp/has_tabs; then
rm /tmp/has_tabs &> /dev/null || true
echo "-- tabs found in scripts"
exit 1
else
echo "-- no tab found in scripts"
fi
exit 0
|
"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in <API key>
<API key> = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def <API key>(referrals):
<API key> = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
<API key> = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
<API key> = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
<API key> = Referral.<API key>
return <API key>
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
<API key> = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.<API key>
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:<API key>',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
<API key> = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.<API key>.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text
|
//# MatrixInverse.cc: The inverse of an expression returning a Jones matrix.
//
//
//# ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
//
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite is free software: you can redistribute it and/or
//
//
//# (at your option) any later version.
//
//# The LOFAR software suite is distributed in the hope that it will be useful,
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//
//
//
//
//
//
#include <lofar_config.h>
#include <BBSKernel/Expr/MatrixInverse.h>
// Inverse of a 2x2 matrix:
// (a b) ( d -b)
// If A = ( ) then inverse(A) = ( ) / (ad - bc)
// (c d) (-c a)
namespace LOFAR
{
namespace BBS
{
MatrixInverse::MatrixInverse(const Expr<JonesMatrix>::ConstPtr &expr)
: BasicUnaryExpr<JonesMatrix, JonesMatrix>(expr)
{
}
const JonesMatrix::View MatrixInverse::evaluateImpl(const Grid&,
const JonesMatrix::View &arg0) const
{
JonesMatrix::View result;
Matrix invDet(1.0 / (arg0(0, 0) * arg0(1, 1) - arg0(0, 1) * arg0(1, 0)));
result.assign(0, 0, arg0(1, 1) * invDet);
result.assign(0, 1, arg0(0, 1) * -invDet);
result.assign(1, 0, arg0(1, 0) * -invDet);
result.assign(1, 1, arg0(0, 0) * invDet);
return result;
}
} // namespace BBS
} // namespace LOFAR
|
# This file is partially auto-generated by the DateTime::Locale generator
# tools (v0.10). This code generator comes with the DateTime::Locale
# distribution in the tools/ directory, and is called generate-modules.
# Do not edit this file directly unless you are sure the part you are editing
=pod
=encoding UTF-8
=head1 NAME
DateTime::Locale::rwk - Locale data examples for the Rwa (rwk) locale
=head1 DESCRIPTION
This pod file contains examples of the locale data available for the
Rwa locale.
=head2 Days
=head3 Wide (format)
Jumatatuu
Jumanne
Jumatanu
Alhamisi
Ijumaa
Jumamosi
Jumapilyi
=head3 Abbreviated (format)
Jtt
Jnn
Jtn
Alh
Iju
Jmo
Jpi
=head3 Narrow (format)
J
J
J
A
I
J
J
=head3 Wide (stand-alone)
Jumatatuu
Jumanne
Jumatanu
Alhamisi
Ijumaa
Jumamosi
Jumapilyi
=head3 Abbreviated (stand-alone)
Jtt
Jnn
Jtn
Alh
Iju
Jmo
Jpi
=head3 Narrow (stand-alone)
J
J
J
A
I
J
J
=head2 Months
=head3 Wide (format)
Januari
Februari
Machi
Aprilyi
Mei
Junyi
Julyai
Agusti
Septemba
Oktoba
Novemba
Desemba
=head3 Abbreviated (format)
Jan
Feb
Mac
Apr
Mei
Jun
Jul
Ago
Sep
Okt
Nov
Des
=head3 Narrow (format)
J
F
M
A
M
J
J
A
S
O
N
D
=head3 Wide (stand-alone)
Januari
Februari
Machi
Aprilyi
Mei
Junyi
Julyai
Agusti
Septemba
Oktoba
Novemba
Desemba
=head3 Abbreviated (stand-alone)
Jan
Feb
Mac
Apr
Mei
Jun
Jul
Ago
Sep
Okt
Nov
Des
=head3 Narrow (stand-alone)
J
F
M
A
M
J
J
A
S
O
N
D
=head2 Quarters
=head3 Wide (format)
Robo 1
Robo 2
Robo 3
Robo 4
=head3 Abbreviated (format)
R1
R2
R3
R4
=head3 Narrow (format)
1
2
3
4
=head3 Wide (stand-alone)
Robo 1
Robo 2
Robo 3
Robo 4
=head3 Abbreviated (stand-alone)
R1
R2
R3
R4
=head3 Narrow (stand-alone)
1
2
3
4
=head2 Eras
=head3 Wide (format)
Kabla ya Kristu
Baada ya Kristu
=head3 Abbreviated (format)
KK
BK
=head3 Narrow (format)
KK
BK
=head2 Date Formats
=head3 Full
2008-02-05T18:30:30 = Jumanne, 5 Februari 2008
1995-12-22T09:05:02 = Ijumaa, 22 Desemba 1995
-0010-09-15T04:44:23 = Jumamosi, 15 Septemba -10
=head3 Long
2008-02-05T18:30:30 = 5 Februari 2008
1995-12-22T09:05:02 = 22 Desemba 1995
-0010-09-15T04:44:23 = 15 Septemba -10
=head3 Medium
2008-02-05T18:30:30 = 5 Feb 2008
1995-12-22T09:05:02 = 22 Des 1995
-0010-09-15T04:44:23 = 15 Sep -10
=head3 Short
2008-02-05T18:30:30 = 05/02/2008
1995-12-22T09:05:02 = 22/12/1995
-0010-09-15T04:44:23 = 15/09/-10
=head2 Time Formats
=head3 Full
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Long
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Medium
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head3 Short
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 09:05
-0010-09-15T04:44:23 = 04:44
=head2 Datetime Formats
=head3 Full
2008-02-05T18:30:30 = Jumanne, 5 Februari 2008 18:30:30 UTC
1995-12-22T09:05:02 = Ijumaa, 22 Desemba 1995 09:05:02 UTC
-0010-09-15T04:44:23 = Jumamosi, 15 Septemba -10 04:44:23 UTC
=head3 Long
2008-02-05T18:30:30 = 5 Februari 2008 18:30:30 UTC
1995-12-22T09:05:02 = 22 Desemba 1995 09:05:02 UTC
-0010-09-15T04:44:23 = 15 Septemba -10 04:44:23 UTC
=head3 Medium
2008-02-05T18:30:30 = 5 Feb 2008 18:30:30
1995-12-22T09:05:02 = 22 Des 1995 09:05:02
-0010-09-15T04:44:23 = 15 Sep -10 04:44:23
=head3 Short
2008-02-05T18:30:30 = 05/02/2008 18:30
1995-12-22T09:05:02 = 22/12/1995 09:05
-0010-09-15T04:44:23 = 15/09/-10 04:44
=head2 Available Formats
=head3 Bh (h B)
2008-02-05T18:30:30 = 6 B
1995-12-22T09:05:02 = 9 B
-0010-09-15T04:44:23 = 4 B
=head3 Bhm (h:mm B)
2008-02-05T18:30:30 = 6:30 B
1995-12-22T09:05:02 = 9:05 B
-0010-09-15T04:44:23 = 4:44 B
=head3 Bhms (h:mm:ss B)
2008-02-05T18:30:30 = 6:30:30 B
1995-12-22T09:05:02 = 9:05:02 B
-0010-09-15T04:44:23 = 4:44:23 B
=head3 E (ccc)
2008-02-05T18:30:30 = Jnn
1995-12-22T09:05:02 = Iju
-0010-09-15T04:44:23 = Jmo
=head3 EBhm (E h:mm B)
2008-02-05T18:30:30 = Jnn 6:30 B
1995-12-22T09:05:02 = Iju 9:05 B
-0010-09-15T04:44:23 = Jmo 4:44 B
=head3 EBhms (E h:mm:ss B)
2008-02-05T18:30:30 = Jnn 6:30:30 B
1995-12-22T09:05:02 = Iju 9:05:02 B
-0010-09-15T04:44:23 = Jmo 4:44:23 B
=head3 EHm (E HH:mm)
2008-02-05T18:30:30 = Jnn 18:30
1995-12-22T09:05:02 = Iju 09:05
-0010-09-15T04:44:23 = Jmo 04:44
=head3 EHms (E HH:mm:ss)
2008-02-05T18:30:30 = Jnn 18:30:30
1995-12-22T09:05:02 = Iju 09:05:02
-0010-09-15T04:44:23 = Jmo 04:44:23
=head3 Ed (d, E)
2008-02-05T18:30:30 = 5, Jnn
1995-12-22T09:05:02 = 22, Iju
-0010-09-15T04:44:23 = 15, Jmo
=head3 Ehm (E h:mm a)
2008-02-05T18:30:30 = Jnn 6:30 kyiukonyi
1995-12-22T09:05:02 = Iju 9:05 utuko
-0010-09-15T04:44:23 = Jmo 4:44 utuko
=head3 Ehms (E h:mm:ss a)
2008-02-05T18:30:30 = Jnn 6:30:30 kyiukonyi
1995-12-22T09:05:02 = Iju 9:05:02 utuko
-0010-09-15T04:44:23 = Jmo 4:44:23 utuko
=head3 Gy (G y)
2008-02-05T18:30:30 = BK 2008
1995-12-22T09:05:02 = BK 1995
-0010-09-15T04:44:23 = KK -10
=head3 GyMMM (G y MMM)
2008-02-05T18:30:30 = BK 2008 Feb
1995-12-22T09:05:02 = BK 1995 Des
-0010-09-15T04:44:23 = KK -10 Sep
=head3 GyMMMEd (G y MMM d, E)
2008-02-05T18:30:30 = BK 2008 Feb 5, Jnn
1995-12-22T09:05:02 = BK 1995 Des 22, Iju
-0010-09-15T04:44:23 = KK -10 Sep 15, Jmo
=head3 GyMMMd (G y MMM d)
2008-02-05T18:30:30 = BK 2008 Feb 5
1995-12-22T09:05:02 = BK 1995 Des 22
-0010-09-15T04:44:23 = KK -10 Sep 15
=head3 H (HH)
2008-02-05T18:30:30 = 18
1995-12-22T09:05:02 = 09
-0010-09-15T04:44:23 = 04
=head3 Hm (HH:mm)
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 09:05
-0010-09-15T04:44:23 = 04:44
=head3 Hms (HH:mm:ss)
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head3 Hmsv (HH:mm:ss v)
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Hmv (HH:mm v)
2008-02-05T18:30:30 = 18:30 UTC
1995-12-22T09:05:02 = 09:05 UTC
-0010-09-15T04:44:23 = 04:44 UTC
=head3 M (L)
2008-02-05T18:30:30 = 2
1995-12-22T09:05:02 = 12
-0010-09-15T04:44:23 = 9
=head3 MEd (E, M/d)
2008-02-05T18:30:30 = Jnn, 2/5
1995-12-22T09:05:02 = Iju, 12/22
-0010-09-15T04:44:23 = Jmo, 9/15
=head3 MMM (LLL)
2008-02-05T18:30:30 = Feb
1995-12-22T09:05:02 = Des
-0010-09-15T04:44:23 = Sep
=head3 MMMEd (E, MMM d)
2008-02-05T18:30:30 = Jnn, Feb 5
1995-12-22T09:05:02 = Iju, Des 22
-0010-09-15T04:44:23 = Jmo, Sep 15
=head3 MMMMEd (E, MMMM d)
2008-02-05T18:30:30 = Jnn, Februari 5
1995-12-22T09:05:02 = Iju, Desemba 22
-0010-09-15T04:44:23 = Jmo, Septemba 15
=head3 MMMMW-count-other ('week' W 'of' MMMM)
2008-02-05T18:30:30 = week 1 of Februari
1995-12-22T09:05:02 = week 3 of Desemba
-0010-09-15T04:44:23 = week 2 of Septemba
=head3 MMMMd (MMMM d)
2008-02-05T18:30:30 = Februari 5
1995-12-22T09:05:02 = Desemba 22
-0010-09-15T04:44:23 = Septemba 15
=head3 MMMd (MMM d)
2008-02-05T18:30:30 = Feb 5
1995-12-22T09:05:02 = Des 22
-0010-09-15T04:44:23 = Sep 15
=head3 Md (M/d)
2008-02-05T18:30:30 = 2/5
1995-12-22T09:05:02 = 12/22
-0010-09-15T04:44:23 = 9/15
=head3 d (d)
2008-02-05T18:30:30 = 5
1995-12-22T09:05:02 = 22
-0010-09-15T04:44:23 = 15
=head3 h (h a)
2008-02-05T18:30:30 = 6 kyiukonyi
1995-12-22T09:05:02 = 9 utuko
-0010-09-15T04:44:23 = 4 utuko
=head3 hm (h:mm a)
2008-02-05T18:30:30 = 6:30 kyiukonyi
1995-12-22T09:05:02 = 9:05 utuko
-0010-09-15T04:44:23 = 4:44 utuko
=head3 hms (h:mm:ss a)
2008-02-05T18:30:30 = 6:30:30 kyiukonyi
1995-12-22T09:05:02 = 9:05:02 utuko
-0010-09-15T04:44:23 = 4:44:23 utuko
=head3 hmsv (h:mm:ss a v)
2008-02-05T18:30:30 = 6:30:30 kyiukonyi UTC
1995-12-22T09:05:02 = 9:05:02 utuko UTC
-0010-09-15T04:44:23 = 4:44:23 utuko UTC
=head3 hmv (h:mm a v)
2008-02-05T18:30:30 = 6:30 kyiukonyi UTC
1995-12-22T09:05:02 = 9:05 utuko UTC
-0010-09-15T04:44:23 = 4:44 utuko UTC
=head3 ms (mm:ss)
2008-02-05T18:30:30 = 30:30
1995-12-22T09:05:02 = 05:02
-0010-09-15T04:44:23 = 44:23
=head3 y (y)
2008-02-05T18:30:30 = 2008
1995-12-22T09:05:02 = 1995
-0010-09-15T04:44:23 = -10
=head3 yM (M/y)
2008-02-05T18:30:30 = 2/2008
1995-12-22T09:05:02 = 12/1995
-0010-09-15T04:44:23 = 9/-10
=head3 yMEd (E, M/d/y)
2008-02-05T18:30:30 = Jnn, 2/5/2008
1995-12-22T09:05:02 = Iju, 12/22/1995
-0010-09-15T04:44:23 = Jmo, 9/15/-10
=head3 yMMM (MMM y)
2008-02-05T18:30:30 = Feb 2008
1995-12-22T09:05:02 = Des 1995
-0010-09-15T04:44:23 = Sep -10
=head3 yMMMEd (E, MMM d, y)
2008-02-05T18:30:30 = Jnn, Feb 5, 2008
1995-12-22T09:05:02 = Iju, Des 22, 1995
-0010-09-15T04:44:23 = Jmo, Sep 15, -10
=head3 yMMMM (MMMM y)
2008-02-05T18:30:30 = Februari 2008
1995-12-22T09:05:02 = Desemba 1995
-0010-09-15T04:44:23 = Septemba -10
=head3 yMMMd (y MMM d)
2008-02-05T18:30:30 = 2008 Feb 5
1995-12-22T09:05:02 = 1995 Des 22
-0010-09-15T04:44:23 = -10 Sep 15
=head3 yMd (y-MM-dd)
2008-02-05T18:30:30 = 2008-02-05
1995-12-22T09:05:02 = 1995-12-22
-0010-09-15T04:44:23 = -10-09-15
=head3 yQQQ (QQQ y)
2008-02-05T18:30:30 = R1 2008
1995-12-22T09:05:02 = R4 1995
-0010-09-15T04:44:23 = R3 -10
=head3 yQQQQ (QQQQ y)
2008-02-05T18:30:30 = Robo 1 2008
1995-12-22T09:05:02 = Robo 4 1995
-0010-09-15T04:44:23 = Robo 3 -10
=head3 yw-count-other ('week' w 'of' Y)
2008-02-05T18:30:30 = week 6 of 2008
1995-12-22T09:05:02 = week 51 of 1995
-0010-09-15T04:44:23 = week 37 of -10
=head2 Miscellaneous
=head3 Prefers 24 hour time?
Yes
=head3 Local first day of the week
1 (Jumatatuu)
=head1 SUPPORT
See L<DateTime::Locale>.
=cut
|
// @flow
import React, { Component } from 'react'
import { withStyles } from 'material-ui/styles'
import Profile from 'models/Profile'
import IconButton from 'material-ui/IconButton'
import Typography from 'material-ui/Typography'
import FontAwesome from 'react-fontawesome'
import Avatar from 'components/common/Avatar'
import Pubkey from 'components/common/Pubkey'
import InsetText from 'components/common/InsetText'
class ShowProfile extends Component {
props: {
profile: Profile,
onEditClick: () => any
}
render() {
const { classes, profile } = this.props
return (
<div>
<div className={classes.header}>
<div className={classes.lateral} />
<Typography className={classes.identity}>{profile.identity}</Typography>
<IconButton className={classes.lateral} onClick={this.props.onEditClick}><FontAwesome name="pencil" /></IconButton>
</div>
{ profile.avatarUrl
? <Avatar person={profile} className={classes.avatar} />
: <div className={classes.noAvatar}><Typography>No avatar</Typography></div>
}
<InsetText text={profile.bio} placeholder='No biography' />
<Typography align="center" variant="body2">
Share your Arbore ID
</Typography>
<Pubkey pubkey={profile.pubkey} />
</div>
)
}
}
const style = theme => ({
header: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
margin: '10px 0 20px',
},
avatar: {
width: '200px !important',
height: '200px !important',
margin: 'auto',
userSelect: 'none',
pointerEvents: 'none',
},
noAvatar: {
width: 200,
height: 200,
borderRadius: '50%',
backgroundColor: theme.palette.background.dark,
margin: 'auto',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
identity: {
margin: '0 10px 0 !important',
fontSize: '2em !important',
textAlign: 'center',
flexGrow: 1,
},
lateral: {
width: '20px !important',
},
})
export default withStyles(style)(ShowProfile)
|
package fr.ybo.transportscommun.activity.commun;
import android.widget.ImageButton;
public interface ChangeIconActionBar {
public void changeIconActionBar(ImageButton imageButton);
}
|
#include "prefix.h"
#include "globdefs.h"
#include "png.h"
#include "filedefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "mcio.h"
#include "uidc.h"
#include "util.h"
#include "image.h"
#include "globals.h"
#include "imageloader.h"
#define NATIVE_ALPHA_BEFORE ((<API key> & <API key>) == <API key>)
#define NATIVE_ORDER_BGR ((<API key> & kMCGPixelOrderRGB) == 0)
#if NATIVE_ALPHA_BEFORE
#define <API key> PNG_FILLER_BEFORE
#else
#define <API key> PNG_FILLER_AFTER
#endif
extern "C" void fakeread(png_structp png_ptr, png_bytep data, png_size_t length)
{
uint8_t **t_data_ptr = (uint8_t**)png_get_io_ptr(png_ptr);
memcpy(data, *t_data_ptr, length);
*t_data_ptr += length;
}
extern "C" void fakeflush(png_structp png_ptr)
{}
bool MCImageValidatePng(const void *p_data, uint32_t p_length, uint16_t& r_width, uint16_t& r_height)
{
png_structp png_ptr;
png_ptr = <API key>((char *)<API key>, NULL, NULL, NULL);
png_infop info_ptr;
info_ptr = <API key>(png_ptr);
png_infop end_info_ptr;
end_info_ptr = <API key>(png_ptr);
// If we return to this point, its an error.
if (setjmp(png_jmpbuf(png_ptr)))
{
<API key>(&png_ptr, &info_ptr, &end_info_ptr);
return false;
}
png_set_read_fn(png_ptr, &p_data, fakeread);
png_read_info(png_ptr, info_ptr);
png_uint_32 width, height;
int interlace_type, compression_type, filter_type, bit_depth, color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type);
<API key>(&png_ptr, &info_ptr, &end_info_ptr);
r_width = (uint16_t)width;
r_height = (uint16_t)height;
return true;
}
extern "C" void stream_read(png_structp png_ptr, png_bytep data, png_size_t length)
{
IO_handle t_stream = (IO_handle)png_get_io_ptr(png_ptr);
uint4 t_length;
t_length = length;
if (IO_read(data, length, t_stream) != IO_NORMAL)
png_error(png_ptr, (char *)"pnglib read error");
}
static void <API key>(png_structp p_png)
{
#if NATIVE_ORDER_BGR
png_set_bgr(p_png);
#endif
#if NATIVE_ALPHA_BEFORE
png_set_swap_alpha(p_png);
#endif
}
class MCPNGImageLoader : public MCImageLoader
{
public:
MCPNGImageLoader(IO_handle p_stream);
virtual ~MCPNGImageLoader();
virtual MCImageLoaderFormat GetFormat() { return kMCImageFormatPNG; }
protected:
virtual bool LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata);
virtual bool LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count);
private:
png_structp m_png;
png_infop m_info;
png_infop m_end_info;
int m_bit_depth;
int m_color_type;
};
MCPNGImageLoader::MCPNGImageLoader(IO_handle p_stream) : MCImageLoader(p_stream)
{
m_png = nil;
m_info = nil;
m_end_info = nil;
}
MCPNGImageLoader::~MCPNGImageLoader()
{
if (m_png != nil)
<API key>(&m_png, &m_info, &m_end_info);
}
bool MCPNGImageLoader::LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata)
{
bool t_success = true;
t_success = nil != (m_png = <API key>(<API key>, NULL, NULL, NULL));
if (t_success)
t_success = nil != (m_info = <API key>(m_png));
if (t_success)
t_success = nil != (m_end_info = <API key>(m_png));
if (t_success)
{
if (setjmp(png_jmpbuf(m_png)))
{
t_success = false;
}
}
if (t_success)
{
png_set_read_fn(m_png, GetStream(), stream_read);
png_read_info(m_png, m_info);
}
png_uint_32 t_width, t_height;
int t_interlace_method, <API key>, t_filter_method;
if (t_success)
{
png_get_IHDR(m_png, m_info, &t_width, &t_height,
&m_bit_depth, &m_color_type,
&t_interlace_method, &<API key>, &t_filter_method);
}
// MERG-2014-09-12: [[ ImageMetadata ]] load image metatadata
if (t_success)
{
uint32_t t_X;
uint32_t t_Y;
int t_units;
if (png_get_pHYs(m_png, m_info, &t_X, &t_Y, &t_units) && t_units != <API key>)
{
MCImageMetadata t_metadata;
MCMemoryClear(&t_metadata, sizeof(t_metadata));
t_metadata.has_density = true;
t_metadata.density = floor(t_X * 0.0254 + 0.5);
r_metadata = t_metadata;
}
}
if (t_success)
{
r_width = t_width;
r_height = t_height;
r_xhot = r_yhot = 0;
r_name = MCValueRetain(kMCEmptyString);
r_frame_count = 1;
}
return t_success;
}
bool MCPNGImageLoader::LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count)
{
bool t_success = true;
MCBitmapFrame *t_frame;
t_frame = nil;
MCColorTransformRef t_color_xform;
t_color_xform = nil;
if (setjmp(png_jmpbuf(m_png)))
{
t_success = false;
}
int t_interlace_passes;
uint32_t t_width, t_height;
if (t_success)
t_success = GetGeometry(t_width, t_height);
if (t_success)
t_success = MCMemoryNew(t_frame);
if (t_success)
t_success = MCImageBitmapCreate(t_width, t_height, t_frame->image);
if (t_success)
{
bool t_need_alpha = false;
t_interlace_passes = <API key>(m_png);
if (m_color_type == <API key>)
<API key>(m_png);
if (m_color_type == PNG_COLOR_TYPE_GRAY || m_color_type == <API key>)
png_set_gray_to_rgb(m_png);
if (png_get_valid(m_png, m_info, PNG_INFO_tRNS))
{
<API key>(m_png);
t_need_alpha = true;
/* OVERHAUL - REVISIT - assume image has transparent pixels if tRNS is present */
t_frame->image->has_transparency = true;
}
if (m_color_type & <API key>)
{
t_need_alpha = true;
/* OVERHAUL - REVISIT - assume image has alpha if color type allows it */
t_frame->image->has_alpha = t_frame->image->has_transparency = true;
}
else if (!t_need_alpha)
png_set_add_alpha(m_png, 0xFF, <API key>);
if (m_bit_depth == 16)
png_set_strip_16(m_png);
<API key>(m_png);
}
// MW-2009-12-10: Support for color profiles
// Try to get an embedded ICC profile...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_iCCP))
{
png_charp t_ccp_name;
png_bytep t_ccp_profile;
int <API key>;
png_uint_32 <API key>;
png_get_iCCP(m_png, m_info, &t_ccp_name, &<API key>, &t_ccp_profile, &<API key>);
MCColorSpaceInfo t_csinfo;
t_csinfo . type = <API key>;
t_csinfo . embedded . data = t_ccp_profile;
t_csinfo . embedded . data_size = <API key>;
t_color_xform = MCscreen -> <API key>(t_csinfo);
}
// Next try an sRGB style profile...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_sRGB))
{
int t_intent;
png_get_sRGB(m_png, m_info, &t_intent);
MCColorSpaceInfo t_csinfo;
t_csinfo . type = <API key>;
t_csinfo . standard . intent = (MCColorSpaceIntent)t_intent;
t_color_xform = MCscreen -> <API key>(t_csinfo);
}
// Finally try for cHRM + gAMA...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_cHRM) &&
png_get_valid(m_png, m_info, PNG_INFO_gAMA))
{
MCColorSpaceInfo t_csinfo;
t_csinfo . type = <API key>;
png_get_cHRM(m_png, m_info,
&t_csinfo . calibrated . white_x, &t_csinfo . calibrated . white_y,
&t_csinfo . calibrated . red_x, &t_csinfo . calibrated . red_y,
&t_csinfo . calibrated . green_x, &t_csinfo . calibrated . green_y,
&t_csinfo . calibrated . blue_x, &t_csinfo . calibrated . blue_y);
png_get_gAMA(m_png, m_info, &t_csinfo . calibrated . gamma);
t_color_xform = MCscreen -> <API key>(t_csinfo);
}
// Could not create any kind, so fallback to gamma transform.
if (t_success && t_color_xform == nil)
{
double image_gamma;
if (png_get_gAMA(m_png, m_info, &image_gamma))
png_set_gamma(m_png, MCgamma, image_gamma);
else
png_set_gamma(m_png, MCgamma, 0.45);
}
if (t_success)
{
for (uindex_t t_pass = 0; t_pass < t_interlace_passes; t_pass++)
{
png_bytep t_data_ptr = (png_bytep)t_frame->image->data;
for (uindex_t i = 0; i < t_height; i++)
{
png_read_row(m_png, t_data_ptr, nil);
t_data_ptr += t_frame->image->stride;
}
}
}
if (t_success)
png_read_end(m_png, m_end_info);
// transform colours using extracted colour profile
if (t_success && t_color_xform != nil)
<API key>(t_frame->image, t_color_xform);
if (t_color_xform != nil)
MCscreen -> <API key>(t_color_xform);
if (t_success)
{
r_frames = t_frame;
r_count = 1;
}
else
MCImageFreeFrames(t_frame, 1);
return t_success;
}
bool <API key>(IO_handle p_stream, MCImageLoader *&r_loader)
{
MCPNGImageLoader *t_loader;
t_loader = new MCPNGImageLoader(p_stream);
if (t_loader == nil)
return false;
r_loader = t_loader;
return true;
}
// embed stream within wrapper struct containing byte count
// so we can update byte_count as we go
struct MCPNGWriteContext
{
IO_handle stream;
uindex_t byte_count;
};
extern "C" void fakewrite(png_structp png_ptr, png_bytep data, png_size_t length)
{
MCPNGWriteContext *t_context = (MCPNGWriteContext*)png_get_io_ptr(png_ptr);
if (IO_write(data, sizeof(uint1), length, t_context->stream) != IO_NORMAL)
png_error(png_ptr, (char *)"pnglib write error");
t_context->byte_count += length;
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
static void parsemetadata(png_structp png_ptr, png_infop info_ptr, MCImageMetadata *p_metadata)
{
if (p_metadata == nil)
return;
if (p_metadata -> has_density)
{
real64_t t_ppi = p_metadata -> density;
if (t_ppi > 0)
{
// Convert to pixels per metre from pixels per inch
png_set_pHYs(png_ptr, info_ptr, t_ppi / 0.0254, t_ppi / 0.0254, <API key>);
}
}
}
bool MCImageEncodePNG(<API key> *p_indexed, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written)
{
bool t_success = true;
MCPNGWriteContext t_context;
t_context.stream = p_stream;
t_context.byte_count = 0;
png_structp t_png_ptr = nil;
png_infop t_info_ptr = nil;
png_color *t_png_palette = nil;
png_byte *t_png_transparency = nil;
png_bytep t_data_ptr = nil;
uindex_t t_stride = 0;
/*init png stuff*/
if (t_success)
{
t_success = nil != (t_png_ptr = <API key>(<API key>,
(png_voidp)NULL, (png_error_ptr)NULL,
(png_error_ptr)NULL));
}
if (t_success)
t_success = nil != (t_info_ptr = <API key>(t_png_ptr));
/*in case of png error*/
if (setjmp(png_jmpbuf(t_png_ptr)))
t_success = false;
if (t_success)
png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush);
if (t_success)
{
png_set_IHDR(t_png_ptr, t_info_ptr, p_indexed->width, p_indexed->height, 8,
<API key>, PNG_INTERLACE_NONE,
<API key>, <API key>);
png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma);
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
if (t_success)
parsemetadata(t_png_ptr, t_info_ptr, p_metadata);
if (t_success)
t_success = MCMemoryNewArray(p_indexed->palette_size, t_png_palette);
/*create palette for 8 bit*/
if (t_success)
{
for (uindex_t i = 0; i < p_indexed->palette_size ; i++)
{
t_png_palette[i].red = p_indexed->palette[i].red >> 8;
t_png_palette[i].green = p_indexed->palette[i].green >> 8;
t_png_palette[i].blue = p_indexed->palette[i].blue >> 8;
}
png_set_PLTE(t_png_ptr, t_info_ptr, t_png_palette, p_indexed->palette_size);
}
if (<API key>(p_indexed))
{
if (t_success)
t_success = MCMemoryAllocate(p_indexed->palette_size, t_png_transparency);
if (t_success)
{
memset(t_png_transparency, 0xFF, p_indexed->palette_size);
t_png_transparency[p_indexed->transparent_index] = 0x00;
png_set_tRNS(t_png_ptr, t_info_ptr, t_png_transparency, p_indexed->palette_size, NULL);
}
}
if (t_success)
png_write_info(t_png_ptr, t_info_ptr);
if (t_success)
{
t_data_ptr = (png_bytep)p_indexed->data;
t_stride = p_indexed->stride;
}
if (t_success)
{
for (uindex_t i = 0; i < p_indexed->height; i++)
{
png_write_row(t_png_ptr, t_data_ptr);
t_data_ptr += t_stride;
}
}
if (t_success)
png_write_end(t_png_ptr, t_info_ptr);
if (t_png_ptr != nil)
<API key>(&t_png_ptr, &t_info_ptr);
if (t_png_palette != nil)
MCMemoryDeleteArray(t_png_palette);
if (t_png_transparency != nil)
MCMemoryDeallocate(t_png_transparency);
if (t_success)
r_bytes_written = t_context.byte_count;
return t_success;
}
bool MCImageEncodePNG(MCImageBitmap *p_bitmap, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written)
{
bool t_success = true;
MCPNGWriteContext t_context;
t_context.stream = p_stream;
t_context.byte_count = 0;
png_structp t_png_ptr = nil;
png_infop t_info_ptr = nil;
png_color *t_png_palette = nil;
png_byte *t_png_transparency = nil;
png_bytep t_data_ptr = nil;
uindex_t t_stride = 0;
<API key> *t_indexed = nil;
if (<API key>(p_bitmap, false, t_indexed))
{
t_success = MCImageEncodePNG(t_indexed, p_metadata, p_stream, r_bytes_written);
<API key>(t_indexed);
return t_success;
}
/*init png stuff*/
if (t_success)
{
t_success = nil != (t_png_ptr = <API key>(<API key>,
(png_voidp)NULL, (png_error_ptr)NULL,
(png_error_ptr)NULL));
}
if (t_success)
t_success = nil != (t_info_ptr = <API key>(t_png_ptr));
/*in case of png error*/
if (setjmp(png_jmpbuf(t_png_ptr)))
t_success = false;
if (t_success)
png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush);
bool t_fully_opaque = true;
if (t_success)
{
t_fully_opaque = !<API key>(p_bitmap);
png_set_IHDR(t_png_ptr, t_info_ptr, p_bitmap->width, p_bitmap->height, 8,
t_fully_opaque ? PNG_COLOR_TYPE_RGB : <API key>, PNG_INTERLACE_NONE,
<API key>, <API key>);
png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma);
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
if (t_success)
parsemetadata(t_png_ptr, t_info_ptr, p_metadata);
if (t_success)
{
png_write_info(t_png_ptr, t_info_ptr);
if (t_fully_opaque)
png_set_filler(t_png_ptr, 0, <API key>);
<API key>(t_png_ptr);
}
if (t_success)
{
t_data_ptr = (png_bytep)p_bitmap->data;
t_stride = p_bitmap->stride;
}
if (t_success)
{
for (uindex_t i = 0; i < p_bitmap->height; i++)
{
png_write_row(t_png_ptr, t_data_ptr);
t_data_ptr += t_stride;
}
}
if (t_success)
png_write_end(t_png_ptr, t_info_ptr);
if (t_png_ptr != nil)
<API key>(&t_png_ptr, &t_info_ptr);
if (t_png_palette != nil)
MCMemoryDeleteArray(t_png_palette);
if (t_png_transparency != nil)
MCMemoryDeallocate(t_png_transparency);
if (t_success)
r_bytes_written = t_context.byte_count;
return t_success;
}
|
<?php
ob_start();
session_start();
if (session_status() == PHP_SESSION_NONE) {
require_once('index.php');
header($uri . '/index.php');
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Creates a new University by a Super Admin">
<title>Create University</title>
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container form-sigin">
<?php
//HTML tags for error messages
$err = "<h4 class=\"form-signin-error\">";
$suc = "<h4 class=\"form-signin-success\">";
$end = "</h4>";
$success = $rso = "";
$rsoErr = "";
$missing_data = [];
$name = [];
//Populates dropdown
require_once('connect.php');
$queryDB = "SELECT * FROM rso";
$result = mysqli_query($database, $queryDB);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
array_push($name,$row['name']);
}
}
if (empty($_POST["rsoSel"]))
{
$missing_data[] = "RSO";
$rsoErr = $err."RSO is required".$end;
}
else {
$rso = trim_input($_POST["rsoSel"]);
}
// Check for each required input data that has been POSTed through Request Method
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($missing_data)) {
require_once('connect.php');
$query = "INSERT INTO member (student_id, rso) VALUES (?, ?)";
$stmt = mysqli_prepare($database, $query);
<API key>($stmt, "ss", $_SESSION['username'], $rso);
mysqli_stmt_execute($stmt);
$affected_rows = <API key>($stmt);
if ($affected_rows == 1) {
mysqli_stmt_close($stmt);
mysqli_close($database);
$success = $suc."You've join an RSO".$end;
}
else {
$success = $err."Please reselect a RSO".$end;
mysqli_stmt_close($stmt);
mysqli_close($database);
}
}
}
//process input data
function trim_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</div>
<div class="flex-container">
<header>
<h1> JOIN RSO </h1>
<span><b><?php echo "Welcome ". $_SESSION['username'] . "<br />";
if($_SESSION['user_type']=='s'){ echo "Student Account";}
elseif($_SESSION['user_type']=='a'){ echo "Admin Account";}
elseif($_SESSION['user_type']=='sa'){ echo "Super Admin Account";}?></b></span><br />
<a href="LOGOUT.php" target="_self"> Log Out</a><br />
</header>
<nav class="nav">
<ul>
<?php
if($_SESSION['user_type']== 's'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>";
}
elseif($_SESSION['user_type']== 'a'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createEvent.html\" target=\"_self\"> Create Event</a><br /></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>";
}
elseif($_SESSION['user_type']== 'sa'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createuniversity.php\" target=\"_self\"> Create University</a></b></li>";
}
?>
</ul>
</nav>
<article class="article">
<div class="container">
<form class="form-signin" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php echo $success; ?>
<?php echo $rsoErr ?>
<select class="form-control" name="rsoSel">
<?php
for($x = 0; $x <= count($name); $x++){
echo "<option value=" . $name[$x] . ">" . $name[$x] . "</option>";
}
?>
<input class = "btn btn-lg btn-primary btn-block" type="submit" value="Join"></input><br />
</form>
</div>
</article>
<div>
</body>
</html>
|
<?php
if (!defined('SZ_PLUGIN_GOOGLE') or !SZ_PLUGIN_GOOGLE) die();
// Before the definition of the class, check if there is a definition
// with the same name or the same as previously defined in other script
if (!class_exists('<API key>'))
{
class <API key> extends SZGoogleWidget
{
/**
* Definition the constructor function, which is called
* at the time of the creation of an instance of this class
*/
function __construct()
{
parent::__construct('<API key>',__('SZ-Google - Drive Save Button','szgoogleadmin'),array(
'classname' => 'sz-widget-google <API key> <API key>',
'description' => ucfirst(__('google drive save button.','szgoogleadmin'))
));
}
/**
* Generation of the HTML code of the widget
* for the full display in the sidebar associated
*/
function widget($args,$instance)
{
// Checking whether there are the variables that are used during the processing
$options = $this->common_empty(array(
'url' => '', // default value
'filename' => '', // default value
'sitename' => '', // default value
'text' => '', // default value
'img' => '', // default value
'position' => '', // default value
'align' => '', // default value
'margintop' => '', // default value
'marginright' => '', // default value
'marginbottom' => '', // default value
'marginleft' => '', // default value
'marginunit' => '', // default value
),$instance);
// do not affect the items of basic but affect some aspects
$controls = $this->common_empty(array(
'badge' => '', // default value
),$instance);
// If the widget I excluded from the badge button I reset
// the variables of the badge possibly set and saved
if ($controls['badge'] != '1') {
$options['img'] = '';
$options['text'] = '';
$options['position'] = '';
}
// Create the HTML code for the current widget recalling the basic
// function which is also invoked by the corresponding shortcode
$OBJC = new <API key>();
$HTML = $OBJC->getHTMLCode($options);
// Output HTML code linked to the widget to
// display call to the general standard for wrap
echo $this->common_widget($args,$instance,$HTML);
}
function update($new_instance,$old_instance)
{
// Performing additional operations on fields of the
// form widget before it is stored in the database
return $this->common_update(array(
'title' => '0', // strip_tags
'badge' => '1', // strip_tags
'url' => '0', // strip_tags
'text' => '0', // strip_tags
'img' => '1', // strip_tags
'align' => '1', // strip_tags
'position' => '1', // strip_tags
),$new_instance,$old_instance);
}
/**
* FORM display the widget in the management of
* sidebar in the administration panel of wordpress
*/
function form($instance)
{
// Creating arrays for list fields that must be
// present in the form before calling wp_parse_args()
$array = array(
'title' => '', // default value
'badge' => '', // default value
'url' => '', // default value
'text' => '', // default value
'img' => '', // default value
'align' => '', // default value
'position' => '', // default value
);
// Creating arrays for list of fields to be retrieved FORM
// and loading the file with the HTML template to display
extract(wp_parse_args($instance,$array),EXTR_OVERWRITE);
// Calling the template for displaying the part
// that concerns the administration panel (admin)
@include(dirname(<API key>).'/admin/widgets/SZGoogleWidget.php');
@include(dirname(<API key>).'/admin/widgets/' .__CLASS__.'.php');
}
}
}
|
// tutorial06.c
// A pedagogical video player that really works!
// and a tutorial by Martin Bohme (boehme@inb.<API key>.de)
// Tested on Gentoo, CVS version 5/01/07 compiled with GCC 4.1.1
// Use
// gcc -o tutorial02 tutorial02.c -lavutil -lavformat -lavcodec -lz -lm `sdl-config --cflags --libs`
// to build (assuming libavformat and libavcodec are correctly installed,
// and assuming you have sdl-config. Please refer to SDL docs for your installation.)
// Run using
// tutorial06 myvideofile.mpg
// to play the video.
#include <ffmpeg/avcodec.h>
#include <ffmpeg/avformat.h>
#include <SDL.h>
#include <SDL_thread.h>
#ifdef __MINGW32__
#undef main /* Prevents SDL from overriding main() */
#endif
#include <stdio.h>
#include <math.h>
#define <API key> 1024
#define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
#define AV_SYNC_THRESHOLD 0.01
#define AV_NOSYNC_THRESHOLD 10.0
#define <API key> 10
#define AUDIO_DIFF_AVG_NB 20
#define FF_ALLOC_EVENT (SDL_USEREVENT)
#define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
#define FF_QUIT_EVENT (SDL_USEREVENT + 2)
#define <API key> 1
#define <API key> <API key>
typedef struct PacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
SDL_mutex *mutex;
SDL_cond *cond;
} PacketQueue;
typedef struct VideoPicture {
SDL_Overlay *bmp;
int width, height; /* source height & width */
int allocated;
double pts;
} VideoPicture;
typedef struct VideoState {
AVFormatContext *pFormatCtx;
int videoStream, audioStream;
int av_sync_type;
double external_clock; /* external clock base */
int64_t external_clock_time;
double audio_clock;
AVStream *audio_st;
PacketQueue audioq;
uint8_t audio_buf[(<API key> * 3) / 2];
unsigned int audio_buf_size;
unsigned int audio_buf_index;
AVPacket audio_pkt;
uint8_t *audio_pkt_data;
int audio_pkt_size;
int audio_hw_buf_size;
double audio_diff_cum; /* used for AV difference average computation */
double audio_diff_avg_coef;
double <API key>;
int <API key>;
double frame_timer;
double frame_last_pts;
double frame_last_delay;
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used)
int64_t <API key>; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts
AVStream *video_st;
PacketQueue videoq;
VideoPicture pictq[<API key>];
int pictq_size, pictq_rindex, pictq_windex;
SDL_mutex *pictq_mutex;
SDL_cond *pictq_cond;
SDL_Thread *parse_tid;
SDL_Thread *video_tid;
char filename[1024];
int quit;
} VideoState;
enum {
<API key>,
<API key>,
<API key>,
};
SDL_Surface *screen;
/* Since we only have one decoding thread, the Big Struct
can be global in case we need it. */
VideoState *global_video_state;
void packet_queue_init(PacketQueue *q) {
memset(q, 0, sizeof(PacketQueue));
q->mutex = SDL_CreateMutex();
q->cond = SDL_CreateCond();
}
int packet_queue_put(PacketQueue *q, AVPacket *pkt) {
AVPacketList *pkt1;
if(av_dup_packet(pkt) < 0) {
return -1;
}
pkt1 = av_malloc(sizeof(AVPacketList));
if (!pkt1)
return -1;
pkt1->pkt = *pkt;
pkt1->next = NULL;
SDL_LockMutex(q->mutex);
if (!q->last_pkt)
q->first_pkt = pkt1;
else
q->last_pkt->next = pkt1;
q->last_pkt = pkt1;
q->nb_packets++;
q->size += pkt1->pkt.size;
SDL_CondSignal(q->cond);
SDL_UnlockMutex(q->mutex);
return 0;
}
static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
{
AVPacketList *pkt1;
int ret;
SDL_LockMutex(q->mutex);
for(;;) {
if(global_video_state->quit) {
ret = -1;
break;
}
pkt1 = q->first_pkt;
if (pkt1) {
q->first_pkt = pkt1->next;
if (!q->first_pkt)
q->last_pkt = NULL;
q->nb_packets
q->size -= pkt1->pkt.size;
*pkt = pkt1->pkt;
av_free(pkt1);
ret = 1;
break;
} else if (!block) {
ret = 0;
break;
} else {
SDL_CondWait(q->cond, q->mutex);
}
}
SDL_UnlockMutex(q->mutex);
return ret;
}
double get_audio_clock(VideoState *is) {
double pts;
int hw_buf_size, bytes_per_sec, n;
pts = is->audio_clock; /* maintained in the audio thread */
hw_buf_size = is->audio_buf_size - is->audio_buf_index;
bytes_per_sec = 0;
n = is->audio_st->codec->channels * 2;
if(is->audio_st) {
bytes_per_sec = is->audio_st->codec->sample_rate * n;
}
if(bytes_per_sec) {
pts -= (double)hw_buf_size / bytes_per_sec;
}
return pts;
}
double get_video_clock(VideoState *is) {
double delta;
delta = (av_gettime() - is-><API key>) / 1000000.0;
return is->video_current_pts + delta;
}
double get_external_clock(VideoState *is) {
return av_gettime() / 1000000.0;
}
double get_master_clock(VideoState *is) {
if(is->av_sync_type == <API key>) {
return get_video_clock(is);
} else if(is->av_sync_type == <API key>) {
return get_audio_clock(is);
} else {
return get_external_clock(is);
}
}
/* Add or subtract samples to get a better sync, return new
audio buffer size */
int synchronize_audio(VideoState *is, short *samples,
int samples_size, double pts) {
int n;
double ref_clock;
n = 2 * is->audio_st->codec->channels;
if(is->av_sync_type != <API key>) {
double diff, avg_diff;
int wanted_size, min_size, max_size, nb_samples;
ref_clock = get_master_clock(is);
diff = get_audio_clock(is) - ref_clock;
if(diff < AV_NOSYNC_THRESHOLD) {
// accumulate the diffs
is->audio_diff_cum = diff + is->audio_diff_avg_coef
* is->audio_diff_cum;
if(is-><API key> < AUDIO_DIFF_AVG_NB) {
is-><API key>++;
} else {
avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
if(fabs(avg_diff) >= is-><API key>) {
wanted_size = samples_size + ((int)(diff * is->audio_st->codec->sample_rate) * n);
min_size = samples_size * ((100 - <API key>) / 100);
max_size = samples_size * ((100 + <API key>) / 100);
if(wanted_size < min_size) {
wanted_size = min_size;
} else if (wanted_size > max_size) {
wanted_size = max_size;
}
if(wanted_size < samples_size) {
/* remove samples */
samples_size = wanted_size;
} else if(wanted_size > samples_size) {
uint8_t *samples_end, *q;
int nb;
/* add samples by copying final sample*/
nb = (samples_size - wanted_size);
samples_end = (uint8_t *)samples + samples_size - n;
q = samples_end + n;
while(nb > 0) {
memcpy(q, samples_end, n);
q += n;
nb -= n;
}
samples_size = wanted_size;
}
}
}
} else {
/* difference is TOO big; reset diff stuff */
is-><API key> = 0;
is->audio_diff_cum = 0;
}
}
return samples_size;
}
int audio_decode_frame(VideoState *is, uint8_t *audio_buf, int buf_size, double *pts_ptr) {
int len1, data_size, n;
AVPacket *pkt = &is->audio_pkt;
double pts;
for(;;) {
while(is->audio_pkt_size > 0) {
data_size = buf_size;
len1 = <API key>(is->audio_st->codec,
(int16_t *)audio_buf, &data_size,
is->audio_pkt_data, is->audio_pkt_size);
if(len1 < 0) {
/* if error, skip frame */
is->audio_pkt_size = 0;
break;
}
is->audio_pkt_data += len1;
is->audio_pkt_size -= len1;
if(data_size <= 0) {
/* No data yet, get more frames */
continue;
}
pts = is->audio_clock;
*pts_ptr = pts;
n = 2 * is->audio_st->codec->channels;
is->audio_clock += (double)data_size /
(double)(n * is->audio_st->codec->sample_rate);
/* We have data, return it and come back for more later */
return data_size;
}
if(pkt->data)
av_free_packet(pkt);
if(is->quit) {
return -1;
}
/* next packet */
if(packet_queue_get(&is->audioq, pkt, 1) < 0) {
return -1;
}
is->audio_pkt_data = pkt->data;
is->audio_pkt_size = pkt->size;
/* if update, update the audio clock w/pts */
if(pkt->pts != AV_NOPTS_VALUE) {
is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
}
}
}
void audio_callback(void *userdata, Uint8 *stream, int len) {
VideoState *is = (VideoState *)userdata;
int len1, audio_size;
double pts;
while(len > 0) {
if(is->audio_buf_index >= is->audio_buf_size) {
/* We have already sent all our data; get more */
audio_size = audio_decode_frame(is, is->audio_buf, sizeof(is->audio_buf), &pts);
if(audio_size < 0) {
/* If error, output silence */
is->audio_buf_size = 1024;
memset(is->audio_buf, 0, is->audio_buf_size);
} else {
audio_size = synchronize_audio(is, (int16_t *)is->audio_buf,
audio_size, pts);
is->audio_buf_size = audio_size;
}
is->audio_buf_index = 0;
}
len1 = is->audio_buf_size - is->audio_buf_index;
if(len1 > len)
len1 = len;
memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
len -= len1;
stream += len1;
is->audio_buf_index += len1;
}
}
static Uint32 <API key>(Uint32 interval, void *opaque) {
SDL_Event event;
event.type = FF_REFRESH_EVENT;
event.user.data1 = opaque;
SDL_PushEvent(&event);
return 0; /* 0 means stop timer */
}
/* schedule a video refresh in 'delay' ms */
static void schedule_refresh(VideoState *is, int delay) {
SDL_AddTimer(delay, <API key>, is);
}
void video_display(VideoState *is) {
SDL_Rect rect;
VideoPicture *vp;
AVPicture pict;
float aspect_ratio;
int w, h, x, y;
int i;
vp = &is->pictq[is->pictq_rindex];
if(vp->bmp) {
if(is->video_st->codec->sample_aspect_ratio.num == 0) {
aspect_ratio = 0;
} else {
aspect_ratio = av_q2d(is->video_st->codec->sample_aspect_ratio) *
is->video_st->codec->width / is->video_st->codec->height;
}
if(aspect_ratio <= 0.0) {
aspect_ratio = (float)is->video_st->codec->width /
(float)is->video_st->codec->height;
}
h = screen->h;
w = ((int)rint(h * aspect_ratio)) & -3;
if(w > screen->w) {
w = screen->w;
h = ((int)rint(w / aspect_ratio)) & -3;
}
x = (screen->w - w) / 2;
y = (screen->h - h) / 2;
rect.x = x;
rect.y = y;
rect.w = w;
rect.h = h;
<API key>(vp->bmp, &rect);
}
}
void video_refresh_timer(void *userdata) {
VideoState *is = (VideoState *)userdata;
VideoPicture *vp;
double actual_delay, delay, sync_threshold, ref_clock, diff;
if(is->video_st) {
if(is->pictq_size == 0) {
schedule_refresh(is, 1);
} else {
vp = &is->pictq[is->pictq_rindex];
is->video_current_pts = vp->pts;
is-><API key> = av_gettime();
delay = vp->pts - is->frame_last_pts; /* the pts from last time */
if(delay <= 0 || delay >= 1.0) {
/* if incorrect delay, use previous one */
delay = is->frame_last_delay;
}
/* save for next time */
is->frame_last_delay = delay;
is->frame_last_pts = vp->pts;
/* update delay to sync to audio if not master source */
if(is->av_sync_type != <API key>) {
ref_clock = get_master_clock(is);
diff = vp->pts - ref_clock;
/* Skip or repeat the frame. Take delay into account
FFPlay still doesn't "know if this is the best guess." */
sync_threshold = (delay > AV_SYNC_THRESHOLD) ? delay : AV_SYNC_THRESHOLD;
if(fabs(diff) < AV_NOSYNC_THRESHOLD) {
if(diff <= -sync_threshold) {
delay = 0;
} else if(diff >= sync_threshold) {
delay = 2 * delay;
}
}
}
is->frame_timer += delay;
/* computer the REAL delay */
actual_delay = is->frame_timer - (av_gettime() / 1000000.0);
if(actual_delay < 0.010) {
/* Really it should skip the picture instead */
actual_delay = 0.010;
}
schedule_refresh(is, (int)(actual_delay * 1000 + 0.5));
/* show the picture! */
video_display(is);
/* update queue for next picture! */
if(++is->pictq_rindex == <API key>) {
is->pictq_rindex = 0;
}
SDL_LockMutex(is->pictq_mutex);
is->pictq_size
SDL_CondSignal(is->pictq_cond);
SDL_UnlockMutex(is->pictq_mutex);
}
} else {
schedule_refresh(is, 100);
}
}
void alloc_picture(void *userdata) {
VideoState *is = (VideoState *)userdata;
VideoPicture *vp;
vp = &is->pictq[is->pictq_windex];
if(vp->bmp) {
// we already have one make another, bigger/smaller
SDL_FreeYUVOverlay(vp->bmp);
}
// Allocate a place to put our YUV image on that screen
vp->bmp = <API key>(is->video_st->codec->width,
is->video_st->codec->height,
SDL_YV12_OVERLAY,
screen);
vp->width = is->video_st->codec->width;
vp->height = is->video_st->codec->height;
SDL_LockMutex(is->pictq_mutex);
vp->allocated = 1;
SDL_CondSignal(is->pictq_cond);
SDL_UnlockMutex(is->pictq_mutex);
}
int queue_picture(VideoState *is, AVFrame *pFrame, double pts) {
VideoPicture *vp;
int dst_pix_fmt;
AVPicture pict;
/* wait until we have space for a new pic */
SDL_LockMutex(is->pictq_mutex);
while(is->pictq_size >= <API key> &&
!is->quit) {
SDL_CondWait(is->pictq_cond, is->pictq_mutex);
}
SDL_UnlockMutex(is->pictq_mutex);
if(is->quit)
return -1;
// windex is set to 0 initially
vp = &is->pictq[is->pictq_windex];
/* allocate or resize the buffer! */
if(!vp->bmp ||
vp->width != is->video_st->codec->width ||
vp->height != is->video_st->codec->height) {
SDL_Event event;
vp->allocated = 0;
/* we have to do it in the main thread */
event.type = FF_ALLOC_EVENT;
event.user.data1 = is;
SDL_PushEvent(&event);
/* wait until we have a picture allocated */
SDL_LockMutex(is->pictq_mutex);
while(!vp->allocated && !is->quit) {
SDL_CondWait(is->pictq_cond, is->pictq_mutex);
}
SDL_UnlockMutex(is->pictq_mutex);
if(is->quit) {
return -1;
}
}
/* We have a place to put our picture on the queue */
/* If we are skipping a frame, do we set this to null
but still return vp->allocated = 1? */
if(vp->bmp) {
SDL_LockYUVOverlay(vp->bmp);
dst_pix_fmt = PIX_FMT_YUV420P;
/* point pict at the queue */
pict.data[0] = vp->bmp->pixels[0];
pict.data[1] = vp->bmp->pixels[2];
pict.data[2] = vp->bmp->pixels[1];
pict.linesize[0] = vp->bmp->pitches[0];
pict.linesize[1] = vp->bmp->pitches[2];
pict.linesize[2] = vp->bmp->pitches[1];
// Convert the image into YUV format that SDL uses
img_convert(&pict, dst_pix_fmt,
(AVPicture *)pFrame, is->video_st->codec->pix_fmt,
is->video_st->codec->width, is->video_st->codec->height);
<API key>(vp->bmp);
vp->pts = pts;
/* now we inform our display thread that we have a pic ready */
if(++is->pictq_windex == <API key>) {
is->pictq_windex = 0;
}
SDL_LockMutex(is->pictq_mutex);
is->pictq_size++;
SDL_UnlockMutex(is->pictq_mutex);
}
return 0;
}
double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) {
double frame_delay;
if(pts != 0) {
/* if we have pts, set video clock to it */
is->video_clock = pts;
} else {
/* if we aren't given a pts, set it to the clock */
pts = is->video_clock;
}
/* update the video clock */
frame_delay = av_q2d(is->video_st->codec->time_base);
/* if we are repeating a frame, adjust clock accordingly */
frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
is->video_clock += frame_delay;
return pts;
}
uint64_t <API key> = AV_NOPTS_VALUE;
/* These are called whenever we allocate a frame
* buffer. We use this to store the global_pts in
* a frame at the time it is allocated.
*/
int our_get_buffer(struct AVCodecContext *c, AVFrame *pic) {
int ret = <API key>(c, pic);
uint64_t *pts = av_malloc(sizeof(uint64_t));
*pts = <API key>;
pic->opaque = pts;
return ret;
}
void our_release_buffer(struct AVCodecContext *c, AVFrame *pic) {
if(pic) av_freep(&pic->opaque);
<API key>(c, pic);
}
int video_thread(void *arg) {
VideoState *is = (VideoState *)arg;
AVPacket pkt1, *packet = &pkt1;
int len1, frameFinished;
AVFrame *pFrame;
double pts;
pFrame = avcodec_alloc_frame();
for(;;) {
if(packet_queue_get(&is->videoq, packet, 1) < 0) {
// means we quit getting packets
break;
}
pts = 0;
// Save global pts to be stored in pFrame in first call
<API key> = packet->pts;
// Decode video frame
len1 = <API key>(is->video_st->codec, pFrame, &frameFinished,
packet->data, packet->size);
if(packet->dts == AV_NOPTS_VALUE
&& pFrame->opaque && *(uint64_t*)pFrame->opaque != AV_NOPTS_VALUE) {
pts = *(uint64_t *)pFrame->opaque;
} else if(packet->dts != AV_NOPTS_VALUE) {
pts = packet->dts;
} else {
pts = 0;
}
pts *= av_q2d(is->video_st->time_base);
// Did we get a video frame?
if(frameFinished) {
pts = synchronize_video(is, pFrame, pts);
if(queue_picture(is, pFrame, pts) < 0) {
break;
}
}
av_free_packet(packet);
}
av_free(pFrame);
return 0;
}
int <API key>(VideoState *is, int stream_index) {
AVFormatContext *pFormatCtx = is->pFormatCtx;
AVCodecContext *codecCtx;
AVCodec *codec;
SDL_AudioSpec wanted_spec, spec;
if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) {
return -1;
}
// Get a pointer to the codec context for the video stream
codecCtx = pFormatCtx->streams[stream_index]->codec;
if(codecCtx->codec_type == CODEC_TYPE_AUDIO) {
// Set audio settings from codec info
wanted_spec.freq = codecCtx->sample_rate;
wanted_spec.format = AUDIO_S16SYS;
wanted_spec.channels = codecCtx->channels;
wanted_spec.silence = 0;
wanted_spec.samples = <API key>;
wanted_spec.callback = audio_callback;
wanted_spec.userdata = is;
if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
return -1;
}
is->audio_hw_buf_size = spec.size;
}
codec = <API key>(codecCtx->codec_id);
if(!codec || (avcodec_open(codecCtx, codec) < 0)) {
fprintf(stderr, "Unsupported codec!\n");
return -1;
}
switch(codecCtx->codec_type) {
case CODEC_TYPE_AUDIO:
is->audioStream = stream_index;
is->audio_st = pFormatCtx->streams[stream_index];
is->audio_buf_size = 0;
is->audio_buf_index = 0;
/* averaging filter for audio sync */
is->audio_diff_avg_coef = exp(log(0.01 / AUDIO_DIFF_AVG_NB));
is-><API key> = 0;
/* Correct audio only if larger error than this */
is-><API key> = 2.0 * <API key> / codecCtx->sample_rate;
memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
packet_queue_init(&is->audioq);
SDL_PauseAudio(0);
break;
case CODEC_TYPE_VIDEO:
is->videoStream = stream_index;
is->video_st = pFormatCtx->streams[stream_index];
is->frame_timer = (double)av_gettime() / 1000000.0;
is->frame_last_delay = 40e-3;
is-><API key> = av_gettime();
packet_queue_init(&is->videoq);
is->video_tid = SDL_CreateThread(video_thread, is);
codecCtx->get_buffer = our_get_buffer;
codecCtx->release_buffer = our_release_buffer;
break;
default:
break;
}
}
int decode_interrupt_cb(void) {
return (global_video_state && global_video_state->quit);
}
int decode_thread(void *arg) {
VideoState *is = (VideoState *)arg;
AVFormatContext *pFormatCtx;
AVPacket pkt1, *packet = &pkt1;
int video_index = -1;
int audio_index = -1;
int i;
is->videoStream=-1;
is->audioStream=-1;
global_video_state = is;
// will interrupt blocking functions if we quit!
<API key>(decode_interrupt_cb);
// Open video file
if(av_open_input_file(&pFormatCtx, is->filename, NULL, 0, NULL)!=0)
return -1; // Couldn't open file
is->pFormatCtx = pFormatCtx;
// Retrieve stream information
if(av_find_stream_info(pFormatCtx)<0)
return -1; // Couldn't find stream information
// Dump information about file onto standard error
dump_format(pFormatCtx, 0, is->filename, 0);
// Find the first video stream
for(i=0; i<pFormatCtx->nb_streams; i++) {
if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO &&
video_index < 0) {
video_index=i;
}
if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO &&
audio_index < 0) {
audio_index=i;
}
}
if(audio_index >= 0) {
<API key>(is, audio_index);
}
if(video_index >= 0) {
<API key>(is, video_index);
}
if(is->videoStream < 0 || is->audioStream < 0) {
fprintf(stderr, "%s: could not open codecs\n", is->filename);
goto fail;
}
// main decode loop
for(;;) {
if(is->quit) {
break;
}
// seek stuff goes here
if(is->audioq.size > MAX_AUDIOQ_SIZE ||
is->videoq.size > MAX_VIDEOQ_SIZE) {
SDL_Delay(10);
continue;
}
if(av_read_frame(is->pFormatCtx, packet) < 0) {
if(url_ferror(&pFormatCtx->pb) == 0) {
SDL_Delay(100); /* no error; wait for user input */
continue;
} else {
break;
}
}
// Is this a packet from the video stream?
if(packet->stream_index == is->videoStream) {
packet_queue_put(&is->videoq, packet);
} else if(packet->stream_index == is->audioStream) {
packet_queue_put(&is->audioq, packet);
} else {
av_free_packet(packet);
}
}
/* all done - wait for it */
while(!is->quit) {
SDL_Delay(100);
}
fail:
{
SDL_Event event;
event.type = FF_QUIT_EVENT;
event.user.data1 = is;
SDL_PushEvent(&event);
}
return 0;
}
int main(int argc, char *argv[]) {
SDL_Event event;
VideoState *is;
is = av_mallocz(sizeof(VideoState));
if(argc < 2) {
fprintf(stderr, "Usage: test <file>\n");
exit(1);
}
// Register all formats and codecs
av_register_all();
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
exit(1);
}
// Make a screen to put our video
#ifndef __DARWIN__
screen = SDL_SetVideoMode(640, 480, 0, 0);
#else
screen = SDL_SetVideoMode(640, 480, 24, 0);
#endif
if(!screen) {
fprintf(stderr, "SDL: could not set video mode - exiting\n");
exit(1);
}
pstrcpy(is->filename, sizeof(is->filename), argv[1]);
is->pictq_mutex = SDL_CreateMutex();
is->pictq_cond = SDL_CreateCond();
schedule_refresh(is, 40);
is->av_sync_type = <API key>;
is->parse_tid = SDL_CreateThread(decode_thread, is);
if(!is->parse_tid) {
av_free(is);
return -1;
}
for(;;) {
SDL_WaitEvent(&event);
switch(event.type) {
case FF_QUIT_EVENT:
case SDL_QUIT:
is->quit = 1;
SDL_Quit();
exit(0);
break;
case FF_ALLOC_EVENT:
alloc_picture(event.user.data1);
break;
case FF_REFRESH_EVENT:
video_refresh_timer(event.user.data1);
break;
default:
break;
}
}
return 0;
}
|
class CPlayerStats;
#pragma once
#include <vector>
using namespace std;
struct sStat
{
unsigned short id;
float value;
};
class CPlayerStats
{
public:
~CPlayerStats();
bool GetStat(unsigned short usID, float& fValue);
void SetStat(unsigned short usID, float fValue);
vector<sStat*>::const_iterator IterBegin() { return m_List.begin(); }
vector<sStat*>::const_iterator IterEnd() { return m_List.end(); }
unsigned short GetSize() { return static_cast<unsigned short>(m_List.size()); }
private:
vector<sStat*> m_List;
};
|
'''Test the analysis.signal module.'''
from __future__ import absolute_import, print_function, division
import pytest
import numpy as np
import gridcells.analysis.signal as asignal
from gridcells.analysis.signal import (local_extrema, local_maxima,
local_minima, ExtremumTypes,
LocalExtrema)
RTOL = 1e-10
def _data_generator(n_items, sz):
'''Generate pairs of test vectors.'''
it = 0
while it < n_items:
N1 = np.random.randint(sz) + 1
N2 = np.random.randint(sz) + 1
if N1 == 0 and N2 == 0:
continue
a1 = np.random.rand(N1)
a2 = np.random.rand(N2)
yield (a1, a2)
it += 1
class TestCorrelation(object):
'''
Test the analysis.signal.corr function (and effectively the core of the
autoCorrelation) function.
'''
maxN = 500
maxLoops = 1000
def test_onesided(self):
'''Test the one-sided version of ``corr``.'''
for a1, a2 in _data_generator(self.maxLoops, self.maxN):
c_cpp = asignal.corr(a1, a2, mode='onesided')
c_np = np.correlate(a1, a2, mode='full')[::-1][a1.size - 1:]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_twosided(self):
'''Test the two-sided version of ``corr``.'''
for a1, a2 in _data_generator(self.maxLoops, self.maxN):
c_cpp = asignal.corr(a1, a2, mode='twosided')
c_np = np.correlate(a1, a2, mode='full')[::-1]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_range(self):
'''Test the ranged version of ``corr``.'''
# Half the range of both signals
for a1, a2 in _data_generator(self.maxLoops, self.maxN):
if a1.size <= 1 or a2.size <= 1:
continue
lag_start = - (a1.size
lag_end = a2.size
c_np_centre = a1.size - 1
c_cpp = asignal.corr(a1, a2, mode='range', lag_start=lag_start,
lag_end=lag_end)
c_np = np.correlate(a1, a2, mode='full')[::-1]
np.testing.assert_allclose(
c_cpp,
c_np[c_np_centre + lag_start:c_np_centre + lag_end + 1],
rtol=RTOL)
def test_zero_len(self):
'''Test that an exception is raised when inputs have zero length.'''
a1 = np.array([])
a2 = np.arange(10)
# corr(a1, a2)
lag_start = 0
lag_end = 0
for mode in ("onesided", "twosided", "range"):
with pytest.raises(TypeError):
asignal.corr(a1, a2, mode, lag_start, lag_end)
with pytest.raises(TypeError):
asignal.corr(a2, a1, mode, lag_start, lag_end)
with pytest.raises(TypeError):
asignal.corr(a1, a1, mode, lag_start, lag_end)
def test_non_double(self):
'''Test the corr function when dtype is not double.'''
a1 = np.array([1, 2, 3], dtype=int)
asignal.corr(a1, a1, mode='twosided')
class TestAutoCorrelation(object):
'''Test the acorr function.'''
maxN = 500
maxLoops = 1000
def test_default_params(self):
'''Test default parameters.'''
a = np.arange(10)
c_cpp = asignal.acorr(a)
c_np = np.correlate(a, a, mode='full')[::-1][a.size - 1:]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_onesided(self):
'''Test the one-sided version of ``corr``.'''
a = np.arange(10)
c_cpp = asignal.acorr(a, mode='onesided', max_lag=5)
c_np = np.correlate(a, a, mode='full')[::-1][a.size - 1:a.size - 1 + 6]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_twosided(self):
'''Test the two-sided version of ``corr``.'''
a = np.arange(10)
c_cpp = asignal.acorr(a, mode='twosided', max_lag=5)
c_np = np.correlate(a, a, mode='full')[::-1][a.size - 6:a.size + 5]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_norm(self):
'''Test normalization.'''
# Simple array
a = np.arange(10)
c_cpp = asignal.acorr(a, mode='twosided', norm=True)
c_np = np.correlate(a, a, mode='full')[::-1]
np.testing.assert_allclose(c_cpp, c_np / np.max(c_np), rtol=RTOL)
# A zero array will return zero
zero_array = np.zeros(13)
c_cpp = asignal.acorr(zero_array, mode='twosided', norm=True)
assert np.all(c_cpp == 0.)
def generate_sin(n_half_cycles, resolution=100):
if n_half_cycles < 1:
raise ValueError()
if resolution < 1:
raise ValueError()
f = 1. / (2 * resolution)
t = np.arange(n_half_cycles * resolution, dtype=float)
sig = np.sin(2 * np.pi * f * t)
extrema_positions = np.array(np.arange(n_half_cycles) * resolution +
resolution / 2,
dtype=int)
extrema_types = []
current_type = ExtremumTypes.MAX
for _ in range(n_half_cycles):
extrema_types.append(current_type)
if current_type is ExtremumTypes.MAX:
current_type = ExtremumTypes.MIN
else:
current_type = ExtremumTypes.MAX
return (sig, extrema_positions, np.array(extrema_types))
class TestLocalExtrema(object):
'''Test computation of local extrema.'''
def test_local_extrema(self):
for n_extrema in [1, 2, 51]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
extrema = local_extrema(sig)
assert len(extrema) == n_extrema
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
extrema.get_type(ExtremumTypes.MIN))
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] ==
extrema.get_type(ExtremumTypes.MAX))
def test_zero_array(self):
for func in [local_extrema, local_maxima, local_minima]:
extrema = func(np.empty(0))
assert len(extrema) == 0
def test_single_item(self):
'''This should return a zero length array.'''
for func in [local_extrema, local_maxima, local_minima]:
extrema = func(np.array([1.]))
assert len(extrema) == 0
def test_maxima(self):
# One maximum only
for n_extrema in [1, 2]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
maxima = local_maxima(sig)
assert len(maxima) == 1
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] ==
maxima)
# 2 maxima
for n_extrema in [3, 4]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
maxima = local_maxima(sig)
assert len(maxima) == 2
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] ==
maxima)
def test_minima(self):
# Only one maximum so should return empty
n_extrema = 1
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
minima = local_minima(sig)
assert len(minima) == 0
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
minima)
# One maximum and minimum
n_extrema = 2
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
minima = local_minima(sig)
assert len(minima) == 1
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
minima)
# 2 minima
for n_extrema in [4, 5]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
minima = local_minima(sig)
assert len(minima) == 2
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
minima)
class <API key>(object):
'''Test the local extremum object.'''
def test_empty(self):
extrema = LocalExtrema([], [])
assert len(extrema) == 0
assert len(extrema.get_type(ExtremumTypes.MIN)) == 0 # FIXME
def <API key>(self):
with pytest.raises(IndexError):
extrema = LocalExtrema([], [1])
with pytest.raises(IndexError):
extrema = LocalExtrema(np.arange(10), [1])
def test_single_type(self):
N = 10
test_vector = np.arange(N)
for tested_type in ExtremumTypes:
extrema = LocalExtrema(test_vector, [tested_type] * N)
assert len(extrema) == N
for current_type in ExtremumTypes:
retrieved = extrema.get_type(current_type)
if current_type is tested_type:
assert len(retrieved) == N
assert np.all(retrieved == test_vector)
else:
assert len(retrieved) == 0
def test_mixed_types(self):
N = 10
test_vector = np.arange(10)
test_types = np.ones(N) * ExtremumTypes.MIN
test_types[0:10:2] = ExtremumTypes.MAX
extrema = LocalExtrema(test_vector, test_types)
assert len(extrema) == N
retrieved_min = extrema.get_type(ExtremumTypes.MIN)
assert np.all(retrieved_min == test_vector[1:10:2])
retrieved_max = extrema.get_type(ExtremumTypes.MAX)
assert np.all(retrieved_max == test_vector[0:10:2])
# Should not find any other types
for current_type in ExtremumTypes:
if (current_type is not ExtremumTypes.MIN and current_type is not
ExtremumTypes.MAX):
assert len(extrema.get_type(current_type)) == 0
|
<?php
//require_once 'PEAR.php';
// commented by yogatama for use in gtfw
//require_once 'oleread.inc';
//define('<API key>', function_exists('iconv'));
//define('<API key>', function_exists('mb_convert_encoding'));
define('<API key>', 0x600);
define('<API key>', 0x500);
define('<API key>', 0x5);
define('<API key>', 0x10);
define('<API key>', 0x809);
define('<API key>', 0x0a);
define('<API key>', 0x85);
define('<API key>', 0x200);
define('<API key>', 0x208);
define('<API key>', 0xd7);
define('<API key>', 0x2f);
define('<API key>', 0x1c);
define('<API key>', 0x1b6);
define('<API key>', 0x7e);
define('<API key>', 0x27e);
define('<API key>', 0xbd);
define('<API key>', 0xbe);
define('<API key>', 0x20b);
define('<API key>', 0xfc);
define('<API key>', 0xff);
define('<API key>', 0x3c);
define('<API key>', 0x204);
define('<API key>', 0xfd);
define('<API key>', 0x203);
define('<API key>', 0x18);
define('<API key>', 0x221);
define('<API key>', 0x207);
define('<API key>', 0x406);
define('<API key>', 0x6);
define('<API key>', 0x41e);
define('<API key>', 0xe0);
define('<API key>', 0x205);
define('<API key>', 0xffff);
define('<API key>', 0x22);
define('<API key>', 0xE5);
define('<API key>' , 25569);
define('<API key>', 24107);
define('<API key>', 24 * 60 * 60);
//define('<API key>', "%.2f");
define('<API key>', "%s");
// function file_get_contents for PHP < 4.3.0
// Thanks Marian Steinbach for this function
if (!function_exists('file_get_contents')) {
function file_get_contents($filename, $use_include_path = 0) {
$data = '';
$file = @fopen($filename, "rb", $use_include_path);
if ($file) {
while (!feof($file)) $data .= fread($file, 1024);
fclose($file);
} else {
// There was a problem opening the file
$data = FALSE;
}
return $data;
}
}
//class <API key> extends PEAR {
class <API key> {
var $boundsheets = array();
var $formatRecords = array();
var $sst = array();
var $sheets = array();
var $data;
var $pos;
var $_ole;
var $_defaultEncoding;
var $_defaultFormat = <API key>;
var $_columnsFormat = array();
var $_rowoffset = 1;
var $_coloffset = 1;
var $dateFormats = array (
0xe => "d/m/Y",
0xf => "d-M-Y",
0x10 => "d-M",
0x11 => "M-Y",
0x12 => "h:i a",
0x13 => "h:i:s a",
0x14 => "H:i",
0x15 => "H:i:s",
0x16 => "d/m/Y H:i",
0x2d => "i:s",
0x2e => "H:i:s",
0x2f => "i:s.S");
var $numberFormats = array(
0x1 => "%1.0f",
0x2 => "%1.2f", // "0.00",
0x3 => "%1.0f", //"
0x4 => "%1.2f", //"#,##0.00",
0x5 => "%1.0f",
0x6 => '$%1.0f',
0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x9 => '%1.0f%%',
0xa => '%1.2f%%', // "0.00%"
0xb => '%1.2f', // 0.00E00",
0x25 => '%1.0f', // "
0x26 => '%1.0f', //"
0x27 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x28 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x29 => '%1.0f', //"
0x2a => '$%1.0f', //"$
0x2b => '%1.2f', //"#,##0.00;(#,##0.00)",
0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x30 => '%1.0f'); //"##0.0E0";
function <API key>(){
$this->_ole =& new OLERead();
$this->setUTFEncoder('iconv');
}
function setOutputEncoding($Encoding){
$this->_defaultEncoding = $Encoding;
}
/**
* $encoder = 'iconv' or 'mb'
* set iconv if you would like use 'iconv' for encode UTF-16LE to your encoding
* set mb if you would like use 'mb_convert_encoding' for encode UTF-16LE to your encoding
*/
function setUTFEncoder($encoder = 'iconv'){
$this->_encoderFunction = '';
if ($encoder == 'iconv'){
$this->_encoderFunction = function_exists('iconv') ? 'iconv' : '';
}elseif ($encoder == 'mb') {
$this->_encoderFunction = function_exists('mb_convert_encoding') ? 'mb_convert_encoding' : '';
}
}
function setRowColOffset($iOffset){
$this->_rowoffset = $iOffset;
$this->_coloffset = $iOffset;
}
function setDefaultFormat($sFormat){
$this->_defaultFormat = $sFormat;
}
function setColumnFormat($column, $sFormat){
$this->_columnsFormat[$column] = $sFormat;
}
function read($sFileName) {
$errlevel = error_reporting();
//error_reporting($errlevel ^ E_NOTICE);
$res = $this->_ole->read($sFileName);
// oops, something goes wrong (Darko Miljanovic)
if($res === false) {
// check error code
if($this->_ole->error == 1) {
// bad file
die('The filename ' . $sFileName . ' is not readable');
}
// check other error codes here (eg bad fileformat, etc...)
}
$this->data = $this->_ole->getWorkBook();
//var_dump($this->data);
//echo "data =".$this->data;
$this->pos = 0;
//$this->readRecords();
$this->_parse();
error_reporting($errlevel);
}
function _parse(){
$pos = 0;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
$version = ord($this->data[$pos + 4]) | ord($this->data[$pos + 5])<<8;
$substreamType = ord($this->data[$pos + 6]) | ord($this->data[$pos + 7])<<8;
//echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
if (($version != <API key>) && ($version != <API key>)) {
return false;
}
if ($substreamType != <API key>){
return false;
}
//print_r($rec);
$pos += $length + 4;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
while ($code != <API key>){
switch ($code) {
case <API key>:
//echo "Type_SST\n";
$spos = $pos + 4;
$limitpos = $spos + $length;
$uniqueStrings = $this->_GetInt4d($this->data, $spos+4);
$spos += 8;
for ($i = 0; $i < $uniqueStrings; $i++) {
// Read in the number of characters
if ($spos == $limitpos) {
$opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ($opcode != 0x3c) {
return -1;
}
$spos += 4;
$limitpos = $spos + $conlength;
}
$numChars = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8);
//echo "i = $i pos = $pos numChars = $numChars ";
$spos += 2;
$optionFlags = ord($this->data[$spos]);
$spos++;
$asciiEncoding = (($optionFlags & 0x01) == 0) ;
$extendedString = ( ($optionFlags & 0x04) != 0);
// See if string contains formatting information
$richString = ( ($optionFlags & 0x08) != 0);
if ($richString) {
// Read in the crun
$formattingRuns = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8);
$spos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_GetInt4d($this->data, $spos);
$spos += 4;
}
$len = ($asciiEncoding)? $numChars : $numChars*2;
if ($spos + $len < $limitpos) {
$retstr = substr($this->data, $spos, $len);
$spos += $len;
}else{
// found countinue
$retstr = substr($this->data, $spos, $limitpos - $spos);
$bytesRead = $limitpos - $spos;
$charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2));
$spos = $limitpos;
while ($charsLeft > 0){
$opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ($opcode != 0x3c) {
return -1;
}
$spos += 4;
$limitpos = $spos + $conlength;
$option = ord($this->data[$spos]);
$spos += 1;
if ($asciiEncoding && ($option == 0)) {
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len;
$asciiEncoding = true;
}elseif (!$asciiEncoding && ($option != 0)){
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len/2;
$asciiEncoding = false;
}elseif (!$asciiEncoding && ($option == 0)) {
// Bummer - the string starts off as Unicode, but after the
// continuation it is in straightforward ASCII encoding
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
for ($j = 0; $j < $len; $j++) {
$retstr .= $this->data[$spos + $j].chr(0);
}
$charsLeft -= $len;
$asciiEncoding = false;
}else{
$newstr = '';
for ($j = 0; $j < strlen($retstr); $j++) {
$newstr = $retstr[$j].chr(0);
}
$retstr = $newstr;
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len/2;
$asciiEncoding = false;
//echo "Izavrat\n";
}
$spos += $len;
}
}
$retstr = ($asciiEncoding) ? $retstr : $this->_encodeUTF16($retstr);
// echo "Str $i = $retstr\n";
if ($richString){
$spos += 4 * $formattingRuns;
}
// For extended strings, skip over the extended string data
if ($extendedString) {
$spos += $extendedRunLength;
}
//if ($retstr == 'Derby'){
// echo "bb\n";
$this->sst[]=$retstr;
}
/*$continueRecords = array();
while ($this->getNextCode() == Type_CONTINUE) {
$continueRecords[] = &$this->nextRecord();
}
//echo " 1 Type_SST\n";
$this->shareStrings = new SSTRecord($r, $continueRecords);
//print_r($this->shareStrings->strings);
*/
// echo 'SST read: '.($time_end-$time_start)."\n";
break;
case <API key>:
return false;
break;
case <API key>:
//echo "Type_NAME\n";
break;
case <API key>:
$indexCode = ord($this->data[$pos+4]) | ord($this->data[$pos+5]) << 8;
if ($version == <API key>) {
$numchars = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8;
if (ord($this->data[$pos+8]) == 0){
$formatString = substr($this->data, $pos+9, $numchars);
} else {
$formatString = substr($this->data, $pos+9, $numchars*2);
}
} else {
$numchars = ord($this->data[$pos+6]);
$formatString = substr($this->data, $pos+7, $numchars*2);
}
$this->formatRecords[$indexCode] = $formatString;
// echo "Type.FORMAT\n";
break;
case <API key>:
//global $dateFormats, $numberFormats;
$indexCode = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8;
//echo "\nType.XF ".count($this->formatRecords['xfrecords'])." $indexCode ";
if (array_key_exists($indexCode, $this->dateFormats)) {
//echo "isdate ".$dateFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $this->dateFormats[$indexCode]
);
}elseif (array_key_exists($indexCode, $this->numberFormats)) {
//echo "isnumber ".$this->numberFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'number',
'format' => $this->numberFormats[$indexCode]
);
}else{
$isdate = FALSE;
if ($indexCode > 0){
if (isset($this->formatRecords[$indexCode]))
$formatstr = $this->formatRecords[$indexCode];
//echo '.other.';
//echo "\ndate-time=$formatstr=\n";
if ($formatstr)
if (preg_match("/[^hmsday\/\-:\s]/i", $formatstr) == 0) { // found day and time format
$isdate = TRUE;
$formatstr = str_replace('mm', 'i', $formatstr);
$formatstr = str_replace('h', 'H', $formatstr);
//echo "\ndate-time $formatstr \n";
}
}
if ($isdate){
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $formatstr,
);
}else{
$this->formatRecords['xfrecords'][] = array(
'type' => 'other',
'format' => '',
'code' => $indexCode
);
}
}
//echo "\n";
break;
case <API key>:
//echo "Type.NINETEENFOUR\n";
$this->nineteenFour = (ord($this->data[$pos+4]) == 1);
break;
case <API key>:
//echo "Type.BOUNDSHEET\n";
$rec_offset = $this->_GetInt4d($this->data, $pos+4);
$rec_typeFlag = ord($this->data[$pos+8]);
$rec_visibilityFlag = ord($this->data[$pos+9]);
$rec_length = ord($this->data[$pos+10]);
if ($version == <API key>){
$chartype = ord($this->data[$pos+11]);
if ($chartype == 0){
$rec_name = substr($this->data, $pos+12, $rec_length);
} else {
$rec_name = $this->_encodeUTF16(substr($this->data, $pos+12, $rec_length*2));
}
}elseif ($version == <API key>){
$rec_name = substr($this->data, $pos+11, $rec_length);
}
$this->boundsheets[] = array('name'=>$rec_name,
'offset'=>$rec_offset);
break;
}
//echo "Code = ".base_convert($r['code'],10,16)."\n";
$pos += $length + 4;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
//$r = &$this->nextRecord();
//echo "1 Code = ".base_convert($r['code'],10,16)."\n";
}
foreach ($this->boundsheets as $key=>$val){
$this->sn = $key;
$this->_parsesheet($val['offset']);
}
return true;
}
function _parsesheet($spos){
$cont = true;
// read BOF
$code = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$version = ord($this->data[$spos + 4]) | ord($this->data[$spos + 5])<<8;
$substreamType = ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8;
if (($version != <API key>) && ($version != <API key>)) {
return -1;
}
if ($substreamType != <API key>){
return -2;
}
//echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
$spos += $length + 4;
//var_dump($this->formatRecords);
//echo "code $code $length";
while($cont) {
//echo "mem= ".memory_get_usage()."\n";
// $r = &$this->file->nextRecord();
$lowcode = ord($this->data[$spos]);
if ($lowcode == <API key>) break;
$code = $lowcode | ord($this->data[$spos+1])<<8;
$length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$spos += 4;
$this->sheets[$this->sn]['maxrow'] = $this->_rowoffset - 1;
$this->sheets[$this->sn]['maxcol'] = $this->_coloffset - 1;
//echo "Code=".base_convert($code,10,16)." $code\n";
unset($this->rectype);
$this->multiplier = 1; // need for format with %
switch ($code) {
case <API key>:
//echo 'Type_DIMENSION ';
if (!isset($this->numRows)) {
if (($length == 10) || ($version == <API key>)){
$this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+2]) | ord($this->data[$spos+3]) << 8;
$this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+6]) | ord($this->data[$spos+7]) << 8;
} else {
$this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8;
$this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+10]) | ord($this->data[$spos+11]) << 8;
}
}
//echo 'numRows '.$this->numRows.' '.$this->numCols."\n";
break;
case <API key>:
$cellRanges = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
for ($i = 0; $i < $cellRanges; $i++) {
$fr = ord($this->data[$spos + 8*$i + 2]) | ord($this->data[$spos + 8*$i + 3])<<8;
$lr = ord($this->data[$spos + 8*$i + 4]) | ord($this->data[$spos + 8*$i + 5])<<8;
$fc = ord($this->data[$spos + 8*$i + 6]) | ord($this->data[$spos + 8*$i + 7])<<8;
$lc = ord($this->data[$spos + 8*$i + 8]) | ord($this->data[$spos + 8*$i + 9])<<8;
//$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1);
if ($lr - $fr > 0) {
$this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['rowspan'] = $lr - $fr + 1;
}
if ($lc - $fc > 0) {
$this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['colspan'] = $lc - $fc + 1;
}
}
//echo "Merged Cells $cellRanges $lr $fr $lc $fc\n";
break;
case <API key>:
case <API key>:
//echo '<API key>'."\n";
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$rknum = $this->_GetInt4d($this->data, $spos + 6);
$numValue = $this->_GetIEEE754($rknum);
//echo $numValue." ";
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($numValue);
}else{
$raw = $numValue;
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$string = sprintf($this->curformat, $numValue * $this->multiplier);
//$this->addcell(RKRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Type_RK $row $column $string $raw {$this->curformat}\n";
break;
case <API key>:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5])<<8;
$index = $this->_GetInt4d($this->data, $spos + 6);
//var_dump($this->sst);
$this->addcell($row, $column, $this->sst[$index]);
//echo "LabelSST $row $column $string\n";
break;
case <API key>:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$colFirst = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$colLast = ord($this->data[$spos + $length - 2]) | ord($this->data[$spos + $length - 1])<<8;
$columns = $colLast - $colFirst + 1;
$tmppos = $spos+4;
for ($i = 0; $i < $columns; $i++) {
$numValue = $this->_GetIEEE754($this->_GetInt4d($this->data, $tmppos + 2));
if ($this->isDate($tmppos-4)) {
list($string, $raw) = $this->createDate($numValue);
}else{
$raw = $numValue;
if (isset($this->_columnsFormat[$colFirst + $i + 1])){
$this->curformat = $this->_columnsFormat[$colFirst + $i + 1];
}
$string = sprintf($this->curformat, $numValue * $this->multiplier);
}
//$rec['rknumbers'][$i]['xfindex'] = ord($rec['data'][$pos]) | ord($rec['data'][$pos+1]) << 8;
$tmppos += 6;
$this->addcell($row, $colFirst + $i, $string, $raw);
//echo "MULRK $row ".($colFirst + $i)." $string\n";
}
//MulRKRecord($r);
// Get the individual cell records from the multiple record
//$num = ;
break;
case <API key>:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($tmp['double']);
// $this->addcell(DateRecord($r, 1));
}else{
//$raw = $tmp[''];
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$raw = $this->createNumber($spos);
$string = sprintf($this->curformat, $raw * $this->multiplier);
// $this->addcell(NumberRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Number $row $column $string\n";
break;
case <API key>:
case <API key>:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ((ord($this->data[$spos+6])==0) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//String formula. Result follows in a STRING record
//echo "FORMULA $row $column Formula with a string<br>\n";
} elseif ((ord($this->data[$spos+6])==1) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Boolean formula. Result is in +2; 0=false,1=true
} elseif ((ord($this->data[$spos+6])==2) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Error formula. Error code is in +2;
} elseif ((ord($this->data[$spos+6])==3) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Formula result is a null string.
} else {
// result is a number, so first 14 bytes are just like a _NUMBER record
$tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($tmp['double']);
// $this->addcell(DateRecord($r, 1));
}else{
//$raw = $tmp[''];
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$raw = $this->createNumber($spos);
$string = sprintf($this->curformat, $raw * $this->multiplier);
// $this->addcell(NumberRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Number $row $column $string\n";
}
break;
case <API key>:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$string = ord($this->data[$spos+6]);
$this->addcell($row, $column, $string);
//echo 'Type_BOOLERR '."\n";
break;
case <API key>:
case <API key>:
case <API key>:
break;
case <API key>:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$this->addcell($row, $column, substr($this->data, $spos + 8, ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8));
// $this->addcell(LabelRecord($r));
break;
case <API key>:
$cont = false;
break;
default:
//echo ' unknown :'.base_convert($r['code'],10,16)."\n";
break;
}
$spos += $length;
}
if (!isset($this->sheets[$this->sn]['numRows']))
$this->sheets[$this->sn]['numRows'] = $this->sheets[$this->sn]['maxrow'];
if (!isset($this->sheets[$this->sn]['numCols']))
$this->sheets[$this->sn]['numCols'] = $this->sheets[$this->sn]['maxcol'];
}
function isDate($spos){
//$xfindex = GetInt2d(, 4);
$xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8;
//echo 'check is date '.$xfindex.' '.$this->formatRecords['xfrecords'][$xfindex]['type']."\n";
//var_dump($this->formatRecords['xfrecords'][$xfindex]);
if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'date') {
$this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format'];
$this->rectype = 'date';
return true;
} else {
if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'number') {
$this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format'];
$this->rectype = 'number';
if (($xfindex == 0x9) || ($xfindex == 0xa)){
$this->multiplier = 100;
}
}else{
$this->curformat = $this->_defaultFormat;
$this->rectype = 'unknown';
}
return false;
}
}
function createDate($numValue){
if ($numValue > 1){
$utcDays = $numValue - ($this->nineteenFour ? <API key> : <API key>);
$utcValue = round($utcDays * <API key>);
$string = date ($this->curformat, $utcValue);
$raw = $utcValue;
}else{
$raw = $numValue;
$hours = floor($numValue * 24);
$mins = floor($numValue * 24 * 60) - $hours * 60;
$secs = floor($numValue * <API key>) - $hours * 60 * 60 - $mins * 60;
$string = date ($this->curformat, mktime($hours, $mins, $secs));
}
return array($string, $raw);
}
function createNumber($spos){
$rknumhigh = $this->_GetInt4d($this->data, $spos + 10);
$rknumlow = $this->_GetInt4d($this->data, $spos + 6);
//for ($i=0; $i<8; $i++) { echo ord($this->data[$i+$spos+6]) . " "; } echo "<br>";
$sign = ($rknumhigh & 0x80000000) >> 31;
$exp = ($rknumhigh & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknumhigh & 0x000fffff));
$mantissalow1 = ($rknumlow & 0x80000000) >> 31;
$mantissalow2 = ($rknumlow & 0x7fffffff);
$value = $mantissa / pow( 2 , (20- ($exp - 1023)));
if ($mantissalow1 != 0) $value += 1 / pow (2 , (21 - ($exp - 1023)));
$value += $mantissalow2 / pow (2 , (52 - ($exp - 1023)));
//echo "Sign = $sign, Exp = $exp, mantissahighx = $mantissa, mantissalow1 = $mantissalow1, mantissalow2 = $mantissalow2<br>\n";
if ($sign) {$value = -1 * $value;}
return $value;
}
function addcell($row, $col, $string, $raw = ''){
//echo "ADD cel $row-$col $string\n";
$this->sheets[$this->sn]['maxrow'] = max($this->sheets[$this->sn]['maxrow'], $row + $this->_rowoffset);
$this->sheets[$this->sn]['maxcol'] = max($this->sheets[$this->sn]['maxcol'], $col + $this->_coloffset);
$this->sheets[$this->sn]['cells'][$row + $this->_rowoffset][$col + $this->_coloffset] = $string;
if ($raw)
$this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['raw'] = $raw;
if (isset($this->rectype))
$this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['type'] = $this->rectype;
}
function _GetIEEE754($rknum){
if (($rknum & 0x02) != 0) {
$value = $rknum >> 2;
} else {
//mmp
// first comment out the previously existing 7 lines of code here
// $tmp = unpack("d", pack("VV", 0, ($rknum & 0xfffffffc)));
// //$value = $tmp[''];
// if (array_key_exists(1, $tmp)) {
// $value = $tmp[1];
// } else {
// $value = $tmp[''];
// I got my info on IEEE754 encoding from
// The RK format calls for using only the most significant 30 bits of the
// 64 bit floating point value. The other 34 bits are assumed to be 0
// So, we use the upper 30 bits of $rknum as follows...
$sign = ($rknum & 0x80000000) >> 31;
$exp = ($rknum & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknum & 0x000ffffc));
$value = $mantissa / pow( 2 , (20- ($exp - 1023)));
if ($sign) {$value = -1 * $value;}
//end of changes by mmp
}
if (($rknum & 0x01) != 0) {
$value /= 100;
}
return $value;
}
function _encodeUTF16($string){
$result = $string;
if ($this->_defaultEncoding){
switch ($this->_encoderFunction){
case 'iconv' : $result = iconv('UTF-16LE', $this->_defaultEncoding, $string);
break;
case 'mb_convert_encoding' : $result = mb_convert_encoding($string, $this->_defaultEncoding, 'UTF-16LE' );
break;
}
}
return $result;
}
function _GetInt4d($data, $pos) {
$value = ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24);
if ($value>=4294967294) {
$value=-2;
}
if ($value >= 4000000000 && $value < 4294967294) // Add these lines
{
$value = -2 - 4294967294 + $value;
} // End add lines
return $value;
}
}
?>
|
namespace MissionPlanner.GCSViews
{
partial class InitialSetup
{
<summary>
Required designer variable.
</summary>
private System.ComponentModel.IContainer components = null;
<summary>
Clean up any resources being used.
</summary>
<param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
<summary>
Required method for Designer support - do not modify
the contents of this method with the code editor.
</summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.<API key> resources = new System.ComponentModel.<API key>(typeof(InitialSetup));
this.backstageView = new MissionPlanner.Controls.BackstageView.BackstageView();
this.backstageViewPagefw = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.<API key> = new System.Windows.Forms.BindingSource(this.components);
this.configFirmware1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFirmware();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.<API key> = new MissionPlanner.GCSViews.ConfigurationView.<API key>();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configWizard1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigWizard();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configMandatory1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMandatory();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configTradHeli1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigTradHeli();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configFrameType1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFrameType();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.<API key> = new MissionPlanner.GCSViews.ConfigurationView.<API key>();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWCompass1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWCompass();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configRadioInput1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigRadioInput();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configESC1 = new MissionPlanner.GCSViews.ConfigurationView.<API key>();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configFlightModes1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFlightModes();
this.backstageViewPagefs = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configFailSafe1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFailSafe();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configOptional1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigOptional();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this._3DRradio1 = new MissionPlanner.Sikradio();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.<API key> = new MissionPlanner.GCSViews.ConfigurationView.<API key>();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.<API key> = new MissionPlanner.GCSViews.ConfigurationView.<API key>();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configCompassMot1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigCompassMot();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.<API key> = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWRangeFinder();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWAirspeed1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWAirspeed();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWOptFlow1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWOptFlow();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWOSD1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWOSD();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configMount1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMount();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.tracker1 = new MissionPlanner.Antenna.Tracker();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configMotor1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMotorTest();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWBT1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWBT();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWPa1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWParachute();
this.<API key> = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
((System.ComponentModel.ISupportInitialize)(this.<API key>)).BeginInit();
this.SuspendLayout();
// backstageView
resources.ApplyResources(this.backstageView, "backstageView");
this.backstageView.HighlightColor1 = System.Drawing.SystemColors.Highlight;
this.backstageView.HighlightColor2 = System.Drawing.SystemColors.MenuHighlight;
this.backstageView.Name = "backstageView";
this.backstageView.Pages.Add(this.backstageViewPagefw);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.backstageViewPagefs);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.Pages.Add(this.<API key>);
this.backstageView.WidthMenu = 172;
// backstageViewPagefw
this.backstageViewPagefw.Advanced = false;
this.backstageViewPagefw.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isDisConnected", true));
this.backstageViewPagefw.LinkText = "Install Firmware";
this.backstageViewPagefw.Page = this.configFirmware1;
this.backstageViewPagefw.Parent = null;
this.backstageViewPagefw.Show = true;
this.backstageViewPagefw.Spacing = 30;
resources.ApplyResources(this.backstageViewPagefw, "backstageViewPagefw");
// <API key>
this.<API key>.DataSource = typeof(MissionPlanner.GCSViews.InitialSetup);
// configFirmware1
resources.ApplyResources(this.configFirmware1, "configFirmware1");
this.configFirmware1.Name = "configFirmware1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Install Firmware";
this.<API key>.Page = this.<API key>;
this.<API key>.Parent = null;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// <API key>
resources.ApplyResources(this.<API key>, "<API key>");
this.<API key>.Name = "<API key>";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Wizard";
this.<API key>.Page = this.configWizard1;
this.<API key>.Parent = null;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configWizard1
resources.ApplyResources(this.configWizard1, "configWizard1");
this.configWizard1.Name = "configWizard1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Mandatory Hardware";
this.<API key>.Page = this.configMandatory1;
this.<API key>.Parent = null;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configMandatory1
resources.ApplyResources(this.configMandatory1, "configMandatory1");
this.configMandatory1.Name = "configMandatory1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isHeli", true));
this.<API key>.LinkText = "Heli Setup";
this.<API key>.Page = this.configTradHeli1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configTradHeli1
resources.ApplyResources(this.configTradHeli1, "configTradHeli1");
this.configTradHeli1.Name = "configTradHeli1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isCopter", true));
this.<API key>.LinkText = "Frame Type";
this.<API key>.Page = this.configFrameType1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configFrameType1
resources.ApplyResources(this.configFrameType1, "configFrameType1");
this.configFrameType1.Name = "configFrameType1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Accel Calibration";
this.<API key>.Page = this.<API key>;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// <API key>
resources.ApplyResources(this.<API key>, "<API key>");
this.<API key>.Name = "<API key>";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Compass";
this.<API key>.Page = this.configHWCompass1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configHWCompass1
resources.ApplyResources(this.configHWCompass1, "configHWCompass1");
this.configHWCompass1.Name = "configHWCompass1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Radio Calibration";
this.<API key>.Page = this.configRadioInput1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configRadioInput1
resources.ApplyResources(this.configRadioInput1, "configRadioInput1");
this.configRadioInput1.Name = "configRadioInput1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isCopter", true));
this.<API key>.LinkText = "ESC Calibration";
this.<API key>.Page = this.configESC1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = false;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configESC1
resources.ApplyResources(this.configESC1, "configESC1");
this.configESC1.Name = "configESC1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Flight Modes";
this.<API key>.Page = this.configFlightModes1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configFlightModes1
resources.ApplyResources(this.configFlightModes1, "configFlightModes1");
this.configFlightModes1.Name = "configFlightModes1";
// backstageViewPagefs
this.backstageViewPagefs.Advanced = false;
this.backstageViewPagefs.LinkText = "FailSafe";
this.backstageViewPagefs.Page = this.configFailSafe1;
this.backstageViewPagefs.Parent = this.<API key>;
this.backstageViewPagefs.Show = true;
this.backstageViewPagefs.Spacing = 30;
resources.ApplyResources(this.backstageViewPagefs, "backstageViewPagefs");
// configFailSafe1
resources.ApplyResources(this.configFailSafe1, "configFailSafe1");
this.configFailSafe1.Name = "configFailSafe1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Optional Hardware";
this.<API key>.Page = this.configOptional1;
this.<API key>.Parent = null;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configOptional1
resources.ApplyResources(this.configOptional1, "configOptional1");
this.configOptional1.Name = "configOptional1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Sik Radio";
this.<API key>.Page = this._3DRradio1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// _3DRradio1
resources.ApplyResources(this._3DRradio1, "_3DRradio1");
this._3DRradio1.Name = "_3DRradio1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Battery Monitor";
this.<API key>.Page = this.<API key>;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// <API key>
resources.ApplyResources(this.<API key>, "<API key>");
this.<API key>.Name = "<API key>";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Battery Monitor 2";
this.<API key>.Page = this.<API key>;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// <API key>
resources.ApplyResources(this.<API key>, "<API key>");
this.<API key>.Name = "<API key>";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isCopter", true));
this.<API key>.LinkText = "Compass/Motor Calib";
this.<API key>.Page = this.configCompassMot1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configCompassMot1
resources.ApplyResources(this.configCompassMot1, "configCompassMot1");
this.configCompassMot1.Name = "configCompassMot1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Sonar";
this.<API key>.Page = this.<API key>;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// <API key>
resources.ApplyResources(this.<API key>, "<API key>");
this.<API key>.Name = "<API key>";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Airspeed";
this.<API key>.Page = this.configHWAirspeed1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configHWAirspeed1
resources.ApplyResources(this.configHWAirspeed1, "configHWAirspeed1");
this.configHWAirspeed1.Name = "configHWAirspeed1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Optical Flow";
this.<API key>.Page = this.configHWOptFlow1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configHWOptFlow1
resources.ApplyResources(this.configHWOptFlow1, "configHWOptFlow1");
this.configHWOptFlow1.Name = "configHWOptFlow1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "OSD";
this.<API key>.Page = this.configHWOSD1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configHWOSD1
resources.ApplyResources(this.configHWOSD1, "configHWOSD1");
this.configHWOSD1.Name = "configHWOSD1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isConnected", true));
this.<API key>.LinkText = "Camera Gimbal";
this.<API key>.Page = this.configMount1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configMount1
resources.ApplyResources(this.configMount1, "configMount1");
this.configMount1.Name = "configMount1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Antenna tracker";
this.<API key>.Page = this.tracker1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// tracker1
this.tracker1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(38)))), ((int)(((byte)(39)))), ((int)(((byte)(40)))));
resources.ApplyResources(this.tracker1, "tracker1");
this.tracker1.ForeColor = System.Drawing.Color.White;
this.tracker1.Name = "tracker1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isCopter", true));
this.<API key>.LinkText = "Motor Test";
this.<API key>.Page = this.configMotor1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configMotor1
resources.ApplyResources(this.configMotor1, "configMotor1");
this.configMotor1.Name = "configMotor1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.LinkText = "Bluetooth Setup";
this.<API key>.Page = this.configHWBT1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configHWBT1
resources.ApplyResources(this.configHWBT1, "configHWBT1");
this.configHWBT1.Name = "configHWBT1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isCopter", true));
this.<API key>.LinkText = "Parachute";
this.<API key>.Page = this.configHWPa1;
this.<API key>.Parent = this.<API key>;
this.<API key>.Show = true;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// configHWPa1
resources.ApplyResources(this.configHWPa1, "configHWPa1");
this.configHWPa1.Name = "configHWPa1";
// <API key>
this.<API key>.Advanced = false;
this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.<API key>, "isDisConnected", true));
this.<API key>.LinkText = "Install Firmware";
this.<API key>.Page = this.configFirmware1;
this.<API key>.Parent = null;
this.<API key>.Show = false;
this.<API key>.Spacing = 30;
resources.ApplyResources(this.<API key>, "<API key>");
// InitialSetup
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.Controls.Add(this.backstageView);
this.Controls.Add(this.<API key>);
this.Controls.Add(this.configHWBT1);
this.Controls.Add(this.<API key>);
this.MinimumSize = new System.Drawing.Size(1000, 450);
this.Name = "InitialSetup";
resources.ApplyResources(this, "$this");
this.FormClosing += new System.Windows.Forms.<API key>(this.<API key>);
this.Load += new System.EventHandler(this.HardwareConfig_Load);
((System.ComponentModel.ISupportInitialize)(this.<API key>)).EndInit();
this.ResumeLayout(false);
}
#endregion
internal Controls.BackstageView.BackstageView backstageView;
private ConfigurationView.ConfigFirmware configFirmware1;
private ConfigurationView.<API key> <API key>;
private ConfigurationView.ConfigWizard configWizard1;
private ConfigurationView.ConfigMandatory configMandatory1;
private ConfigurationView.ConfigOptional configOptional1;
private ConfigurationView.ConfigTradHeli configTradHeli1;
private ConfigurationView.ConfigFrameType configFrameType1;
private ConfigurationView.ConfigHWCompass configHWCompass1;
private ConfigurationView.ConfigRadioInput configRadioInput1;
private ConfigurationView.ConfigFlightModes configFlightModes1;
private ConfigurationView.ConfigFailSafe configFailSafe1;
private Sikradio _3DRradio1;
private ConfigurationView.<API key> <API key>;
private ConfigurationView.ConfigHWRangeFinder <API key>;
private ConfigurationView.ConfigHWAirspeed configHWAirspeed1;
private ConfigurationView.ConfigHWOptFlow configHWOptFlow1;
private ConfigurationView.ConfigHWOSD configHWOSD1;
private ConfigurationView.ConfigMount configMount1;
private ConfigurationView.ConfigMotorTest configMotor1;
private Antenna.Tracker tracker1;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage backstageViewPagefs;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage backstageViewPagefw;
private System.Windows.Forms.BindingSource <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private ConfigurationView.ConfigCompassMot configCompassMot1;
private Controls.BackstageView.BackstageViewPage <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private ConfigurationView.<API key> <API key>;
private Controls.BackstageView.BackstageViewPage <API key>;
private ConfigurationView.ConfigHWBT configHWBT1;
private Controls.BackstageView.BackstageViewPage <API key>;
private ConfigurationView.ConfigHWParachute configHWPa1;
private Controls.BackstageView.BackstageViewPage <API key>;
private ConfigurationView.<API key> configESC1; private Controls.BackstageView.BackstageViewPage <API key>;
private ConfigurationView.<API key> <API key>;
}
}
|
/* SIXEL context. */
#ifdef HAVE_CONFIG_H
#include "../../config.h"
#endif
#include "../../configuration.h"
#include "../../dynamic.h"
#include "../../retroarch.h"
#include "../../verbosity.h"
#include "../../ui/ui_companion_driver.h"
#if defined(_WIN32) && !defined(_XBOX)
#include "../common/win32_common.h"
#endif
static enum gfx_ctx_api sixel_ctx_api = GFX_CTX_NONE;
static void <API key>(void *data, bool *quit,
bool *resize, unsigned *width, unsigned *height, bool is_shutdown)
{
}
static bool <API key>(void *data,
unsigned width, unsigned height)
{
(void)data;
(void)width;
(void)height;
return false;
}
static void <API key>(void *data, void *data2)
{
const settings_t *settings = config_get_ptr();
video_frame_info_t *video_info = (video_frame_info_t*)data2;
#if defined(_WIN32) && !defined(_XBOX)
const ui_window_t *window = <API key>();
char title[128];
title[0] = '\0';
if (settings->bools.video_memory_show)
{
uint64_t mem_bytes_used = <API key>();
uint64_t mem_bytes_total = <API key>();
char mem[128];
mem[0] = '\0';
snprintf(
mem, sizeof(mem), " || MEM: %.2f/%.2fMB", mem_bytes_used / (1024.0f * 1024.0f),
mem_bytes_total / (1024.0f * 1024.0f));
strlcat(video_info->fps_text, mem, sizeof(video_info->fps_text));
}
<API key>(title, sizeof(title));
if (window && title[0])
window->set_title(&main_window, title);
#endif
}
static void <API key>(void *data,
unsigned *width, unsigned *height)
{
(void)data;
}
static void *gfx_ctx_sixel_init(
video_frame_info_t *video_info, void *video_driver)
{
(void)video_driver;
return (void*)"sixel";
}
static void <API key>(void *data)
{
(void)data;
}
static bool <API key>(void *data,
video_frame_info_t *video_info,
unsigned width, unsigned height,
bool fullscreen)
{
return true;
}
static void <API key>(void *data,
const char *joypad_name,
input_driver_t **input, void **input_data)
{
(void)data;
#ifdef HAVE_UDEV
*input_data = input_udev.init(joypad_name);
if (*input_data)
{
*input = &input_udev;
return;
}
#endif
*input = NULL;
*input_data = NULL;
}
static bool <API key>(void *data)
{
return true;
}
static bool <API key>(void *data, bool enable)
{
return true;
}
static bool <API key>(void *data,
enum <API key> type, float *value)
{
return false;
}
static enum gfx_ctx_api <API key>(void *data)
{
return sixel_ctx_api;
}
static bool <API key>(void *data,
enum gfx_ctx_api api, unsigned major, unsigned minor)
{
(void)data;
return true;
}
static void <API key>(void *data, bool state)
{
(void)data;
}
static void <API key>(void *data, int interval)
{
(void)data;
(void)interval;
}
static void <API key>(void *data, uint32_t flags)
{
(void)data;
(void)flags;
}
static uint32_t <API key>(void *data)
{
uint32_t flags = 0;
return flags;
}
static void <API key>(void *data, void *data2)
{
(void)data;
}
const gfx_ctx_driver_t gfx_ctx_sixel = {
gfx_ctx_sixel_init,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
NULL, /* get_refresh_rate */
NULL, /* <API key> */
NULL, /* <API key> */
NULL, /* <API key> */
<API key>,
NULL,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
true, /* has_windowed */
<API key>,
<API key>,
NULL,
NULL,
NULL,
<API key>,
"sixel",
<API key>,
<API key>,
NULL,
NULL,
NULL
};
|
<!
title: "Install Netdata on FreeNAS"
custom_edit_url: https://github.com/netdata/netdata/edit/master/packaging/installer/methods/freenas.md
# Install Netdata on FreeNAS
On <API key> (>=10.0.3 and <11.3), Netdata is pre-installed.
To use Netdata, the service will need to be enabled and started from the FreeNAS [CLI](https://github.com/freenas/cli).
To enable the Netdata service:
sh
service netdata config set enable=true
To start the Netdata service:
sh
service netdata start
|
// Headers
#include "audio.h"
#include "system.h"
#include "baseui.h"
AudioInterface& Audio() {
static EmptyAudio default_;
return DisplayUi? DisplayUi->GetAudio() : default_;
}
|
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def upgrade():
# Break
op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='<API key>'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='<API key>'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),
sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND "
"room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.<API key>(['room_id'], ['roombooking.rooms.id']),
sa.<API key>(['venue_id'], ['roombooking.locations.id']),
sa.<API key>(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.<API key>('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('<API key>', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.<API key>(['break_id'], ['events.breaks.id']),
sa.<API key>(['contribution_id'], ['events.contributions.id']),
sa.<API key>(['event_id'], ['events.events.id']),
sa.<API key>(['parent_id'], ['events.timetable_entries.id']),
sa.<API key>(['session_block_id'], ['events.session_blocks.id']),
sa.<API key>('id'),
schema='events'
)
def downgrade():
op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events')
|
module ComboFieldTagHelper
def combo_field_tag(name, value, option_tags = nil, options = {})
select_placeholder = options[:select_placeholder] || "Select existing value"
input_placeholder = options[:input_placeholder] || "Enter new value"
id = options[:id]
klass = options[:class] || 'combo-field'
required = options[:required]
help = options[:help]
unless options[:label] == false
label_html = label_tag(options[:label] || name, nil, class: "#{'required' if required}")
end
select_options = {
prompt: '',
class: "#{klass} form-control #{'required' if required}",
data: { placeholder: select_placeholder }
}
select_options[:id] = "#{id}_select" if id.present?
select_html = select_tag name, option_tags, select_options
text_field_options = {
class: "form-control",
placeholder: input_placeholder
}
text_field_options[:id] = "#{id}_text" if id.present?
text_field_html = text_field_tag name, value, text_field_options
if help
select_html << content_tag(:small, help.html_safe, class: 'help-block')
end
<<-HTML.html_safe
<div class='combo-field-wrapper #{klass}-wrapper'>
#{label_html}
<div class='combo-field-select #{klass}-select'>#{select_html}</div>
<div class='<API key>'>or</div>
<div class='combo-field-input #{klass}-input'>
#{text_field_html}
<a href='#' class='clear-input hidden'>×</a>
</div>
</div>
HTML
end
end
|
{
"": {
"domain": "ckan",
"lang": "cs_CZ",
"plural-forms": "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"
},
"An Error Occurred": [
null,
"Nastala chyba"
],
"Are you sure you want to perform this action?": [
null,
"Jste si jistí, že chcete provést tuto akci?"
],
"Cancel": [
null,
"Zrušit"
],
"Confirm": [
null,
"Potvrdit"
],
"Edit": [
null,
"Upravit"
],
"Failed to load data API information": [
null,
"Pokus o získání informací pomocí API selhal"
],
"Follow": [
null,
"Sledovat"
],
"Hide": [
null,
"Skrýt"
],
"Image": [
null,
"Obrázek"
],
"Input is too short, must be at least one character": [
null,
"Zadaný vstup je příliš krátký, musíte zadat alespoň jeden znak"
],
"Link": [
null,
"Odkaz"
],
"Link to a URL on the internet (you can also link to an API)": [
null,
"Odkaz na internetovou URL adresu (můžete také zadat odkaz na API)"
],
"Loading...": [
null,
"Nahrávám ..."
],
"No matches found": [
null,
"Nenalezena žádná shoda"
],
"Please Confirm Action": [
null,
"Prosím potvrďte akci"
],
"Remove": [
null,
"Odstranit"
],
"Reorder resources": [
null,
"Změnit pořadí zdrojů"
],
"Reset this": [
null,
"Resetovat"
],
"Resource uploaded": [
null,
"Zdroj nahrán"
],
"Save order": [
null,
"Uložit pořadí"
],
"Saving...": [
null,
"Ukládám..."
],
"Show more": [
null,
"Ukázat více"
],
"Start typing…": [
null,
"Začněte psát..."
],
"There are unsaved modifications to this form": [
null,
"Tento formulář obsahuje neuložené změny"
],
"There is no API data to load for this resource": [
null,
"Tento zdroj neobsahuje žádná data, která lze poskytnou přes API"
],
"URL": [
null,
"URL"
],
"Unable to authenticate upload": [
null,
"Nastala chyba autentizace při nahrávání dat"
],
"Unable to get data for uploaded file": [
null,
"Nelze získat data z nahraného souboru"
],
"Unable to upload file": [
null,
"Nelze nahrát soubor"
],
"Unfollow": [
null,
"Přestat sledovat"
],
"Upload": [
null,
"Nahrát"
],
"Upload a file": [
null,
"Nahrát soubor"
],
"Upload a file on your computer": [
null,
"Nahrát soubor na Váš počítač"
],
"You are uploading a file. Are you sure you want to navigate away and stop this upload?": [
null,
"Právě nahráváte soubor. Jste si opravdu jistí, že chcete tuto stránku opustit a ukončit tak nahrávání?"
],
"show less": [
null,
"ukázat méně"
],
"show more": [
null,
"ukázat více"
]
}
|
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Spectra</title>
<meta name="author" content="CEERI">
<meta name="description" content="[No canvas support] spectra = [];
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="/spectra/atom.xml" rel="alternate" title="Spectra" type="application/atom+xml">
<link rel="canonical" href="">
<link href="/spectra/favicon.png" rel="shortcut icon">
<link href="/spectra/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script async="true" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<header id="header" class="inner"><h1><a href="/spectra/">Spectra</a></h1>
<nav id="main-nav"><ul class="main">
</ul>
</nav>
<nav id="mobile-nav">
<div class="alignleft menu">
<a class="button">Menu</a>
<div class="container"><ul class="main">
</ul>
</div>
</div>
<div class="alignright search">
<a class="button"></a>
<div class="container">
<form action="http://google.com/search" method="get">
<input type="text" name="q" results="0">
<input type="hidden" name="q" value="site:172.16.5.14/spectra">
</form>
</div>
</div>
</nav>
<nav id="sub-nav" class="alignright">
<div class="social">
<a class="github" href="https://github.com/debanjum/Spectroserver" title="GitHub">GitHub</a>
<a class="rss" href="/spectra/atom.xml" title="RSS">RSS</a>
</div>
<form class="search" action="http://google.com/search" method="get">
<input class="alignright" type="text" name="q" results="0">
<input type="hidden" name="q" value="site:172.16.5.14/spectra">
</form>
</nav>
<h2><a>Spectral Data Visualisation & Spectrophotometer Control</a></h2>
</header>
<div id="content" class="inner"> <head>
<script type="text/javascript" src="http://172.16.5.14:7000/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/spectra/javascripts/RGraph.line.js" ></script>
<script type="text/javascript" src="/spectra/javascripts/RGraph.common.core.js" ></script>
<canvas id="cvs" width="1000" height="450">[No canvas support]</canvas>
<script>
spectra = []; // Graph Data Array
l = 0; // The letter 'L' - NOT a one
var socket = io.connect('http://172.16.5.14:7000');
// Pre-pad the arrays with null values
for (var i=0; i<1000; ++i)
{ spectra.push(null); }
function getGraph(id, spectra)
{
// After creating the chart, store it on the global window object
if (!window.__rgraph_line__) {
window.__rgraph_line__ = new RGraph.Line(id, spectra);
window.__rgraph_line__.Set('chart.background.barcolor1', 'white');
window.__rgraph_line__.Set('chart.background.barcolor2', 'white');
window.__rgraph_line__.Set('chart.title.xaxis', 'Wavelength');
window.__rgraph_line__.Set('chart.title.yaxis', 'Voltage');
window.__rgraph_line__.Set('chart.title.vpos', 0.5);
window.__rgraph_line__.Set('chart.title', 'Spectral Profile');
window.__rgraph_line__.Set('chart.title.yaxis.pos', 0.5);
window.__rgraph_line__.Set('chart.title.xaxis.pos', 0.5);
window.__rgraph_line__.Set('chart.colors', ['black']);
window.__rgraph_line__.Set('chart.linewidth',1.5);
window.__rgraph_line__.Set('chart.yaxispos', 'right');
window.__rgraph_line__.Set('chart.ymax', 3.3);
window.__rgraph_line__.Set('chart.ymin', 0);
window.__rgraph_line__.Set('chart.yticks', 1);
window.__rgraph_line__.Set('chart.xticks', 5);
window.__rgraph_line__.Set('units.post', 'V');
}
return window.__rgraph_line__;
}
function drawGraph ()
{
// "cache" this in a local variable
var _RG = RGraph;
_RG.Clear(document.getElementById("cvs"));
var graph = getGraph('cvs', spectra);
graph.Draw();
socket.on ('connect', function () //Connects to Node Data Server
{
socket.on ('data', function (msg)
{
var VALUE = parseFloat(msg); // Convert message to float
spectra.push(VALUE); // Push to Graph Data Array
var SPAN = document.getElementById('sensorvalue');
var text = document.createTextNode(VALUE);
if(SPAN.childNodes.length == 0) { SPAN.appendChild(text) }
else { SPAN.firstChild.nodeValue = VALUE; }
if (spectra.length > 500) { spectra = _RG.array_shift(spectra); }
});
});
if (document.all && _RG.isIE8())
{ alert('[MSIE] Sorry, Internet Explorer 8 is not fast enough to support animated charts'); }
else
{
window.__rgraph_line__.original_data[0] = spectra;
setTimeout(drawGraph, 10); //Delay between Graph Updates
}
}
drawGraph();
socket.on( 'sff', function() { } );
function initspec(start,stop)
{ drawGraph();
socket.emit('initspec', start, stop );
}
function scanspec()
{ socket.emit('scanspec'); }
function resetspec()
{ socket.emit('resetspec'); }
function save(start,stop,spectra)
{ socket.emit('savespec', start, stop, spectra ); }
function openspec(openw)
{ drawGraph();
socket.emit('openspec', openw );
}
</script>
</head>
<body>
<div role="main">
Analog Out: <span id="sensorvalue"></span>
</div>
<form name="input" action="" method="post">
Start Wavelength: <input type="text" name="startwave" id="startw" ><br />
Stop Wavelength: <input type="text" name="stopwave" id="stopw" ><br />
Open Spectra <input type="value" name="openwave" id="openw" ><br />
<input type="button" value="reset" onClick=resetspec()>
<input type="button" value="intialise" onClick=initspec(startw.value,stopw.value)>
<input type="button" value="scan" onClick=scanspec()>
<input type="button" value="save" onClick=save(startw.value,stopw.value,spectra)>
<input type="button" value="open" onClick=openspec(openw.value)>
</form>
</body>
</div>
<footer id="footer" class="inner">Copyright © 2014
CEERI
<span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span>
</footer>
<script src="/spectra/javascripts/slash.js"></script>
<script src="/spectra/javascripts/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
(function($){
$('.fancybox').fancybox();
})(jQuery);
</script> <!-- Delete or comment this line to disable Fancybox -->
</body>
</html>
|
> **Note**: this project is hosted on a [public repository](https://github.com/hhkaos/awesome-arcgis) where anyone can contribute. Learn how to [contribute in less than a minute](https://github.com/hhkaos/awesome-arcgis/blob/master/CONTRIBUTING.md#contributions).
# Scene services
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of contents**
- [Training](#training)
- [Videos](#videos)
- [Resources](#resources)
- [Utils](#utils)
- [News](#news)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Training
Videos
|Event|Title|Length|
|
## Resources
Probably not all the resources are in this list, please use the [ArcGIS Search](https:
## Utils
## News
|
package net.einsteinsci.betterbeginnings.items;
import net.einsteinsci.betterbeginnings.register.IBBName;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.HashSet;
import java.util.Set;
public abstract class ItemKnife extends ItemTool implements IBBName
{
public static final float DAMAGE = 3.0f;
public ItemKnife(ToolMaterial material)
{
super(DAMAGE, material, getBreakable());
}
public static Set getBreakable()
{
Set<Block> s = new HashSet<>();
// s.add(Blocks.log);
// s.add(Blocks.log2);
// s.add(Blocks.planks);
s.add(Blocks.pumpkin);
s.add(Blocks.lit_pumpkin);
s.add(Blocks.melon_block);
s.add(Blocks.clay);
s.add(Blocks.grass);
s.add(Blocks.mycelium);
s.add(Blocks.leaves);
s.add(Blocks.leaves2);
s.add(Blocks.<API key>);
s.add(Blocks.red_mushroom_block);
s.add(Blocks.glass);
s.add(Blocks.glass_pane);
s.add(Blocks.soul_sand);
s.add(Blocks.stained_glass);
s.add(Blocks.stained_glass_pane);
s.add(Blocks.cactus);
return s;
}
@Override
public boolean <API key>()
{
return true;
}
@Override
public int getHarvestLevel(ItemStack stack, String toolClass)
{
return toolMaterial.getHarvestLevel();
}
@Override
public Set<String> getToolClasses(ItemStack stack)
{
Set<String> res = new HashSet<>();
res.add("knife");
return res;
}
// ...which also requires this...
@Override
public ItemStack getContainerItem(ItemStack itemStack)
{
ItemStack result = itemStack.copy();
result.setItemDamage(itemStack.getItemDamage() + 1);
return result;
}
// Allows durability-based crafting.
@Override
public boolean hasContainerItem(ItemStack stack)
{
return true;
}
@Override
public abstract String getName();
}
|
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdio.h>
#include "config.h"
#ifdef BUILTIN_TELNET
#include "screen.h"
extern Window *fore;
extern Layer *flayer;
extern int visual_bell;
extern char screenterm[];
extern int af;
static void TelReply(Window *, char *, int);
static void TelDocmd(Window *, int, int);
static void TelDosub(Window *);
// why TEL_DEFPORT has "
#define TEL_DEFPORT "23"
#define TEL_CONNECTING (-2)
#define TC_IAC 255
#define TC_DONT 254
#define TC_DO 253
#define TC_WONT 252
#define TC_WILL 251
#define TC_SB 250
#define TC_BREAK 243
#define TC_SE 240
#define TC_S "S b swWdDc"
#define TO_BINARY 0
#define TO_ECHO 1
#define TO_SGA 3
#define TO_TM 6
#define TO_TTYPE 24
#define TO_NAWS 31
#define TO_TSPEED 32
#define TO_LFLOW 33
#define TO_LINEMODE 34
#define TO_XDISPLOC 35
#define TO_NEWENV 39
#define TO_S "be c t wsf xE E"
static unsigned char tn_init[] = {
TC_IAC, TC_DO, TO_SGA,
TC_IAC, TC_WILL, TO_TTYPE,
TC_IAC, TC_WILL, TO_NAWS,
TC_IAC, TC_WILL, TO_LFLOW,
};
static void tel_connev_fn(Event *ev, char *data)
{
Window *p = (Window *)data;
if (connect(p->w_ptyfd, (struct sockaddr *)&p->w_telsa, sizeof(p->w_telsa)) && errno != EISCONN) {
char buf[1024];
buf[0] = ' ';
strncpy(buf + 1, strerror(errno), sizeof(buf) - 2);
buf[sizeof(buf) - 1] = 0;
WriteString(p, buf, strlen(buf));
WindowDied(p, 0, 0);
return;
}
WriteString(p, "connected.\r\n", 12);
evdeq(&p->w_telconnev);
p->w_telstate = 0;
}
int TelOpenAndConnect(Window *p)
{
int fd, on = 1;
char buf[256];
struct addrinfo hints, *res0, *res;
if (!(p->w_cmdargs[1])) {
Msg(0, "Usage: screen //telnet host [port]");
return -1;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = af;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(p->w_cmdargs[1], p->w_cmdargs[2] ? p->w_cmdargs[2] : TEL_DEFPORT, &hints, &res0)) {
Msg(0, "unknown host: %s", p->w_cmdargs[1]);
return -1;
}
for (res = res0; res; res = res->ai_next) {
if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) {
if (res->ai_next)
continue;
else {
Msg(errno, "TelOpenAndConnect: socket");
freeaddrinfo(res0);
return -1;
}
}
if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)))
Msg(errno, "TelOpenAndConnect: setsockopt SO_OOBINLINE");
if (p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT))
snprintf(buf, 256, "Trying %s %s...", p->w_cmdargs[1], p->w_cmdargs[2]);
else
snprintf(buf, 256, "Trying %s...", p->w_cmdargs[1]);
WriteString(p, buf, strlen(buf));
if (connect(fd, res->ai_addr, res->ai_addrlen)) {
if (errno == EINPROGRESS) {
p->w_telstate = TEL_CONNECTING;
p->w_telconnev.fd = fd;
p->w_telconnev.handler = tel_connev_fn;
p->w_telconnev.data = (char *)p;
p->w_telconnev.type = EV_WRITE;
p->w_telconnev.priority = 1;
evenq(&p->w_telconnev);
} else {
close(fd);
if (res->ai_next)
continue;
else {
Msg(errno, "TelOpenAndConnect: connect");
freeaddrinfo(res0);
return -1;
}
}
} else
WriteString(p, "connected.\r\n", 12);
if (!(p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT)))
TelReply(p, (char *)tn_init, sizeof(tn_init));
p->w_ptyfd = fd;
memcpy(&p->w_telsa, &res->ai_addr, sizeof(res->ai_addr));
freeaddrinfo(res0);
return 0;
}
return -1;
}
int TelIsline(Window *p)
{
return !fore->w_telropts[TO_SGA];
}
void TelProcessLine(char **bufpp, int *lenp)
{
int echo = !fore->w_telropts[TO_ECHO];
unsigned char c;
char *tb;
int tl;
char *buf = *bufpp;
int l = *lenp;
while (l
c = *(unsigned char *)buf++;
if (fore->w_telbufl + 2 >= IOSIZE) {
WBell(fore, visual_bell);
continue;
}
if (c == '\r') {
if (echo)
WriteString(fore, "\r\n", 2);
fore->w_telbuf[fore->w_telbufl++] = '\r';
fore->w_telbuf[fore->w_telbufl++] = '\n';
tb = fore->w_telbuf;
tl = fore->w_telbufl;
LayProcess(&tb, &tl);
fore->w_telbufl = 0;
continue;
}
if (c == '\b' && fore->w_telbufl > 0) {
if (echo) {
WriteString(fore, (char *)&c, 1);
WriteString(fore, " ", 1);
WriteString(fore, (char *)&c, 1);
}
fore->w_telbufl
}
if ((c >= 0x20 && c <= 0x7e) || c >= 0xa0) {
if (echo)
WriteString(fore, (char *)&c, 1);
fore->w_telbuf[fore->w_telbufl++] = c;
}
}
*lenp = 0;
}
int DoTelnet(char *buf, int *lenp, int f)
{
int echo = !fore->w_telropts[TO_ECHO];
int cmode = fore->w_telropts[TO_SGA];
int bin = fore->w_telropts[TO_BINARY];
char *p = buf, *sbuf;
int trunc = 0;
int c;
int l = *lenp;
sbuf = p;
while (l
c = *(unsigned char *)p++;
if (c == TC_IAC || (c == '\r' && (l == 0 || *p != '\n') && cmode && !bin)) {
if (cmode && echo) {
WriteString(fore, sbuf, p - sbuf);
sbuf = p;
}
if (f
trunc++;
l
}
if (l < 0) {
p--; /* drop char */
break;
}
if (l)
bcopy(p, p + 1, l);
if (c == TC_IAC)
*p++ = c;
else if (c == '\r')
*p++ = 0;
else if (c == '\n') {
p[-1] = '\r';
*p++ = '\n';
}
}
}
*lenp = p - buf;
return trunc;
}
/* modifies data in-place, returns new length */
int TelIn(Window *p, char *buf, int len, int free)
{
char *rp, *wp;
int c;
rp = wp = buf;
while (len
c = *(unsigned char *)rp++;
if (p->w_telstate >= TC_WILL && p->w_telstate <= TC_DONT) {
TelDocmd(p, p->w_telstate, c);
p->w_telstate = 0;
continue;
}
if (p->w_telstate == TC_SB || p->w_telstate == TC_SE) {
if (p->w_telstate == TC_SE && c == TC_IAC)
p->w_telsubidx
if (p->w_telstate == TC_SE && c == TC_SE) {
p->w_telsubidx
TelDosub(p);
p->w_telstate = 0;
continue;
}
if (p->w_telstate == TC_SB && c == TC_IAC)
p->w_telstate = TC_SE;
else
p->w_telstate = TC_SB;
p->w_telsubbuf[p->w_telsubidx] = c;
if (p->w_telsubidx < sizeof(p->w_telsubbuf) - 1)
p->w_telsubidx++;
continue;
}
if (p->w_telstate == TC_IAC) {
if ((c >= TC_WILL && c <= TC_DONT) || c == TC_SB) {
p->w_telsubidx = 0;
p->w_telstate = c;
continue;
}
p->w_telstate = 0;
if (c != TC_IAC)
continue;
} else if (c == TC_IAC) {
p->w_telstate = c;
continue;
}
if (p->w_telstate == '\r') {
p->w_telstate = 0;
if (c == 0)
continue; /* suppress trailing \0 */
} else if (c == '\n' && !p->w_telropts[TO_SGA]) {
/* oops... simulate terminal line mode: insert \r */
if (wp + 1 == rp) {
if (free
if (len)
bcopy(rp, rp + 1, len);
rp++;
*wp++ = '\r';
}
} else
*wp++ = '\r';
}
if (c == '\r')
p->w_telstate = c;
*wp++ = c;
}
return wp - buf;
}
static void TelReply(Window *p, char *str, int len)
{
if (len <= 0)
return;
if (p->w_inlen + len > IOSIZE) {
Msg(0, "Warning: telnet protocol overrun!");
return;
}
bcopy(str, p->w_inbuf + p->w_inlen, len);
p->w_inlen += len;
}
static void TelDocmd(Window *p, int cmd, int opt)
{
unsigned char b[3];
int repl = 0;
switch (cmd) {
case TC_WILL:
if (p->w_telropts[opt] || opt == TO_TM)
return;
repl = TC_DONT;
if (opt == TO_ECHO || opt == TO_SGA || opt == TO_BINARY) {
p->w_telropts[opt] = 1;
/* setcon(); */
repl = TC_DO;
}
break;
case TC_WONT:
if (!p->w_telropts[opt] || opt == TO_TM)
return;
repl = TC_DONT;
p->w_telropts[opt] = 0;
break;
case TC_DO:
if (p->w_telmopts[opt])
return;
repl = TC_WONT;
if (opt == TO_TTYPE || opt == TO_SGA || opt == TO_BINARY || opt == TO_NAWS || opt == TO_TM
|| opt == TO_LFLOW) {
repl = TC_WILL;
p->w_telmopts[opt] = 1;
}
p->w_telmopts[TO_TM] = 0;
break;
case TC_DONT:
if (!p->w_telmopts[opt])
return;
repl = TC_WONT;
p->w_telmopts[opt] = 0;
break;
}
b[0] = TC_IAC;
b[1] = repl;
b[2] = opt;
TelReply(p, (char *)b, 3);
if (cmd == TC_DO && opt == TO_NAWS)
TelWindowSize(p);
}
static void TelDosub(Window *p)
{
char trepl[20 + 6 + 1];
int l;
switch (p->w_telsubbuf[0]) {
case TO_TTYPE:
if (p->w_telsubidx != 2 || p->w_telsubbuf[1] != 1)
return;
l = strlen(screenterm);
if (l >= 20)
break;
sprintf(trepl, "%c%c%c%c%s%c%c", TC_IAC, TC_SB, TO_TTYPE, 0, screenterm, TC_IAC, TC_SE);
TelReply(p, trepl, l + 6);
break;
case TO_LFLOW:
if (p->w_telsubidx != 2)
return;
break;
default:
break;
}
}
void TelBreak(Window *p)
{
static unsigned char tel_break[] = { TC_IAC, TC_BREAK };
TelReply(p, (char *)tel_break, 2);
}
void TelWindowSize(Window *p)
{
char s[20], trepl[20], *t;
int i;
if (p->w_width == 0 || p->w_height == 0 || !p->w_telmopts[TO_NAWS])
return;
sprintf(s, "%c%c%c%c%c%c%c%c%c", TC_SB, TC_SB, TO_NAWS, p->w_width / 256, p->w_width & 255, p->w_height / 256,
p->w_height & 255, TC_SE, TC_SE);
t = trepl;
for (i = 0; i < 9; i++)
if ((unsigned char)(*t++ = s[i]) == TC_IAC)
*t++ = TC_IAC;
trepl[0] = TC_IAC;
t[-2] = TC_IAC;
TelReply(p, trepl, t - trepl);
}
static char tc_s[] = TC_S;
static char to_s[] = TO_S;
void TelStatus(Window *p, char *buf, int l)
{
int i;
*buf++ = '[';
for (i = 0; to_s[i]; i++) {
if (to_s[i] == ' ' || p->w_telmopts[i] == 0)
continue;
*buf++ = to_s[i];
}
*buf++ = ':';
for (i = 0; to_s[i]; i++) {
if (to_s[i] == ' ' || p->w_telropts[i] == 0)
continue;
*buf++ = to_s[i];
}
if (p->w_telstate == TEL_CONNECTING)
buf[-1] = 'C';
else if (p->w_telstate && p->w_telstate != '\r') {
*buf++ = ':';
*buf++ = tc_s[p->w_telstate - TC_SE];
}
*buf++ = ']';
*buf = 0;
return;
}
#endif /* BUILTIN_TELNET */
|
@file GUILaneSpeedTrigger.h
@author Daniel Krajzewicz
@author Jakob Erdmann
@author Michael Behrisch
@date Mon, 26.04.2004
@version $Id: GUILaneSpeedTrigger.h 13107 2012-12-02 13:57:34Z behrisch $
// Changes the speed allowed on a set of lanes (gui version)
// This file is part of SUMO.
// SUMO is free software: you can redistribute it and/or modify
// (at your option) any later version.
#ifndef <API key>
#define <API key>
// included modules
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <vector>
#include <string>
#include <microsim/trigger/MSLaneSpeedTrigger.h>
#include <utils/gui/globjects/<API key>.h>
#include <utils/gui/globjects/<API key>.h>
#include <utils/foxtools/FXRealSpinDial.h>
#include <gui/GUIManipulator.h>
// class definitions
/**
* @class GUILaneSpeedTrigger
* @brief Changes the speed allowed on a set of lanes (gui version)
*
* This is the gui-version of the <API key>
*/
class GUILaneSpeedTrigger
: public MSLaneSpeedTrigger,
public <API key> {
public:
/** @brief Constructor
* @param[in] idStorage The gl-id storage for giving this object an gl-id
* @param[in] id The id of the lane speed trigger
* @param[in] destLanes List of lanes affected by this speed trigger
* @param[in] file Name of the file to read the speeds to set from
*/
GUILaneSpeedTrigger(const std::string& id,
const std::vector<MSLane*>& destLanes,
const std::string& file);
/** destructor */
~GUILaneSpeedTrigger();
@name inherited from GUIGlObject
/** @brief Returns an own popup-menu
*
* @param[in] app The application needed to build the popup-menu
* @param[in] parent The parent window needed to build the popup-menu
* @return The built popup-menu
* @see GUIGlObject::getPopUpMenu
*/
<API key>* getPopUpMenu(GUIMainWindow& app,
GUISUMOAbstractView& parent);
/** @brief Returns an own parameter window
*
* @param[in] app The application needed to build the parameter window
* @param[in] parent The parent window needed to build the parameter window
* @return The built parameter window
* @see GUIGlObject::getParameterWindow
*/
<API key>* getParameterWindow(GUIMainWindow& app,
GUISUMOAbstractView& parent);
/** @brief Returns the boundary to which the view shall be centered in order to show the object
*
* @return The boundary the object is within
* @see GUIGlObject::<API key>
*/
Boundary <API key>() const;
/** @brief Draws the object
* @param[in] s The settings for the current view (may influence drawing)
* @see GUIGlObject::drawGL
*/
void drawGL(const <API key>& s) const;
GUIManipulator* openManipulator(GUIMainWindow& app,
GUISUMOAbstractView& parent);
public:
class <API key> : public <API key> {
FXDECLARE(<API key>)
public:
<API key>(GUIMainWindow& app,
GUISUMOAbstractView& parent, GUIGlObject& o);
~<API key>();
/** @brief Called if the object's manipulator shall be shown */
long onCmdOpenManip(FXObject*, FXSelector, void*);
protected:
<API key>() { }
};
class <API key> : public GUIManipulator {
FXDECLARE(<API key>)
public:
enum {
MID_USER_DEF = FXDialogBox::ID_LAST,
MID_PRE_DEF,
MID_OPTION,
MID_CLOSE,
ID_LAST
};
Constructor
<API key>(GUIMainWindow& app,
const std::string& name, GUILaneSpeedTrigger& o,
int xpos, int ypos);
Destructor
virtual ~<API key>();
long onCmdOverride(FXObject*, FXSelector, void*);
long onCmdClose(FXObject*, FXSelector, void*);
long onCmdUserDef(FXObject*, FXSelector, void*);
long onUpdUserDef(FXObject*, FXSelector, void*);
long onCmdPreDef(FXObject*, FXSelector, void*);
long onUpdPreDef(FXObject*, FXSelector, void*);
long onCmdChangeOption(FXObject*, FXSelector, void*);
private:
GUIMainWindow* myParent;
FXint myChosenValue;
FXDataTarget myChosenTarget;
SUMOReal mySpeed;
FXDataTarget mySpeedTarget;
FXRealSpinDial* myUserDefinedSpeed;
FXComboBox* myPredefinedValues;
GUILaneSpeedTrigger* myObject;
protected:
<API key>() { }
};
private:
Definition of a positions container
typedef std::vector<Position> PosCont;
Definition of a rotation container
typedef std::vector<SUMOReal> RotCont;
private:
The positions in full-geometry mode
PosCont myFGPositions;
The rotations in full-geometry mode
RotCont myFGRotations;
The boundary of this rerouter
Boundary myBoundary;
The information whether the speed shall be shown in m/s or km/h
bool myShowAsKMH;
Storage for last value to avoid string recomputation
mutable SUMOReal myLastValue;
Storage for speed string to avoid recomputation
mutable std::string myLastValueString;
};
#endif
|
@file MSEdge.cpp
@author Christian Roessel
@author Jakob Erdmann
@author Christoph Sommer
@author Daniel Krajzewicz
@author Laura Bieker
@author Michael Behrisch
@author Sascha Krieg
@date Tue, 06 Mar 2001
@version $Id: MSEdge.cpp 13107 2012-12-02 13:57:34Z behrisch $
// A road/street connecting two junctions
// This file is part of SUMO.
// SUMO is free software: you can redistribute it and/or modify
// (at your option) any later version.
// included modules
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <algorithm>
#include <iostream>
#include <cassert>
#include <utils/common/StringTokenizer.h>
#include <utils/options/OptionsCont.h>
#include "MSEdge.h"
#include "MSLane.h"
#include "MSLaneChanger.h"
#include "MSGlobals.h"
#include "MSVehicle.h"
#include "<API key>.h"
#ifdef HAVE_INTERNAL
#include <mesosim/MELoop.h>
#include <mesosim/MESegment.h>
#include <mesosim/MEVehicle.h>
#endif
#ifdef CHECK_MEMORY_LEAKS
#include <foreign/nvwa/debug_new.h>
#endif // CHECK_MEMORY_LEAKS
// static member definitions
MSEdge::DictType MSEdge::myDict;
std::vector<MSEdge*> MSEdge::myEdges;
// member method definitions
MSEdge::MSEdge(const std::string& id, int numericalID,
const EdgeBasicFunction function,
const std::string& streetName) :
Named(id), myNumericalID(numericalID), myLanes(0),
myLaneChanger(0), myFunction(function), <API key>(0),
<API key>(-1), myStreetName(streetName) {}
MSEdge::~MSEdge() {
delete myLaneChanger;
for (AllowedLanesCont::iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); i1++) {
delete(*i1).second;
}
for (<API key>::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) {
for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) {
delete(*i1).second;
}
}
delete myLanes;
// Note: Lanes are delete using MSLane::clear();
}
void
MSEdge::initialize(std::vector<MSLane*>* lanes) {
assert(myFunction == <API key> || lanes != 0);
myLanes = lanes;
if (myLanes && myLanes->size() > 1 && myFunction != <API key>) {
myLaneChanger = new MSLaneChanger(myLanes, OptionsCont::getOptions().getBool("lanechange.allow-swap"));
}
}
void
MSEdge::closeBuilding() {
myAllowed[0] = new std::vector<MSLane*>();
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
myAllowed[0]->push_back(*i);
const MSLinkCont& lc = (*i)->getLinkCont();
for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) {
MSLane* toL = (*j)->getLane();
if (toL != 0) {
MSEdge& to = toL->getEdge();
if (std::find(mySuccessors.begin(), mySuccessors.end(), &to) == mySuccessors.end()) {
mySuccessors.push_back(&to);
}
if (std::find(to.myPredeccesors.begin(), to.myPredeccesors.end(), this) == to.myPredeccesors.end()) {
to.myPredeccesors.push_back(this);
}
if (myAllowed.find(&to) == myAllowed.end()) {
myAllowed[&to] = new std::vector<MSLane*>();
}
myAllowed[&to]->push_back(*i);
}
#ifdef HAVE_INTERNAL_LANES
toL = (*j)->getViaLane();
if (toL != 0) {
MSEdge& to = toL->getEdge();
to.myPredeccesors.push_back(this);
}
#endif
}
}
std::sort(mySuccessors.begin(), mySuccessors.end(), by_id_sorter());
rebuildAllowedLanes();
}
void
MSEdge::rebuildAllowedLanes() {
// clear myClassedAllowed.
// it will be rebuilt on demand
for (<API key>::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) {
for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) {
delete(*i1).second;
}
}
myClassedAllowed.clear();
// rebuild <API key> and <API key>
<API key> = SVCFreeForAll;
<API key> = 0;
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
<API key> &= (*i)->getPermissions();
<API key> |= (*i)->getPermissions();
}
}
MSLane*
MSEdge::leftLane(const MSLane* const lane) const {
std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane);
if (laneIt == myLanes->end() || laneIt == myLanes->end() - 1) {
return 0;
}
return *(laneIt + 1);
}
MSLane*
MSEdge::rightLane(const MSLane* const lane) const {
std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane);
if (laneIt == myLanes->end() || laneIt == myLanes->begin()) {
return 0;
}
return *(laneIt - 1);
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(const MSEdge& destination, SUMOVehicleClass vclass) const {
return allowedLanes(&destination, vclass);
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(SUMOVehicleClass vclass) const {
return allowedLanes(0, vclass);
}
const std::vector<MSLane*>*
MSEdge::<API key>(const AllowedLanesCont& c, const MSEdge* dest) const {
AllowedLanesCont::const_iterator it = c.find(dest);
if (it == c.end()) {
return 0;
}
return it->second;
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(const MSEdge* destination, SUMOVehicleClass vclass) const {
if ((<API key> & vclass) == vclass) {
// all lanes allow vclass
return <API key>(myAllowed, destination);
}
// look up cached result in myClassedAllowed
<API key>::const_iterator i = myClassedAllowed.find(vclass);
if (i != myClassedAllowed.end()) {
// can use cached value
const AllowedLanesCont& c = (*i).second;
return <API key>(c, destination);
} else {
// this vclass is requested for the first time. rebuild all destinations
// go through connected edges
for (AllowedLanesCont::const_iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); ++i1) {
const MSEdge* edge = i1->first;
const std::vector<MSLane*>* lanes = i1->second;
myClassedAllowed[vclass][edge] = new std::vector<MSLane*>();
// go through lanes approaching current edge
for (std::vector<MSLane*>::const_iterator i2 = lanes->begin(); i2 != lanes->end(); ++i2) {
// allows the current vehicle class?
if ((*i2)->allowsVehicleClass(vclass)) {
// -> may be used
myClassedAllowed[vclass][edge]->push_back(*i2);
}
}
// assert that 0 is returned if no connection is allowed for a class
if (myClassedAllowed[vclass][edge]->size() == 0) {
delete myClassedAllowed[vclass][edge];
myClassedAllowed[vclass][edge] = 0;
}
}
return myClassedAllowed[vclass][destination];
}
}
SUMOTime
MSEdge::incVaporization(SUMOTime) {
++<API key>;
return 0;
}
SUMOTime
MSEdge::decVaporization(SUMOTime) {
--<API key>;
return 0;
}
MSLane*
MSEdge::getFreeLane(const std::vector<MSLane*>* allowed, const SUMOVehicleClass vclass) const {
if (allowed == 0) {
allowed = allowedLanes(vclass);
}
MSLane* res = 0;
if (allowed != 0) {
unsigned int noCars = INT_MAX;
for (std::vector<MSLane*>::const_iterator i = allowed->begin(); i != allowed->end(); ++i) {
if ((*i)->getVehicleNumber() < noCars) {
res = (*i);
noCars = (*i)->getVehicleNumber();
}
}
}
return res;
}
MSLane*
MSEdge::getDepartLane(const MSVehicle& veh) const {
switch (veh.getParameter().departLaneProcedure) {
case DEPART_LANE_GIVEN:
if ((int) myLanes->size() <= veh.getParameter().departLane || !(*myLanes)[veh.getParameter().departLane]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) {
return 0;
}
return (*myLanes)[veh.getParameter().departLane];
case DEPART_LANE_RANDOM:
return RandHelper::getRandomFrom(*allowedLanes(veh.getVehicleType().getVehicleClass()));
case DEPART_LANE_FREE:
return getFreeLane(0, veh.getVehicleType().getVehicleClass());
case <API key>:
if (veh.getRoute().size() == 1) {
return getFreeLane(0, veh.getVehicleType().getVehicleClass());
} else {
return getFreeLane(allowedLanes(**(veh.getRoute().begin() + 1)), veh.getVehicleType().getVehicleClass());
}
case <API key>: {
const std::vector<MSVehicle::LaneQ>& bl = veh.getBestLanes(false, (*myLanes)[0]);
SUMOReal bestLength = -1;
for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) {
if ((*i).length > bestLength) {
bestLength = (*i).length;
}
}
std::vector<MSLane*>* bestLanes = new std::vector<MSLane*>();
for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) {
if ((*i).length == bestLength) {
bestLanes->push_back((*i).lane);
}
}
MSLane* ret = getFreeLane(bestLanes, veh.getVehicleType().getVehicleClass());
delete bestLanes;
return ret;
}
case DEPART_LANE_DEFAULT:
default:
break;
}
if (!(*myLanes)[0]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) {
return 0;
}
return (*myLanes)[0];
}
bool
MSEdge::insertVehicle(SUMOVehicle& v, SUMOTime time) const {
// when vaporizing, no vehicles are inserted...
if (isVaporizing()) {
return false;
}
#ifdef HAVE_INTERNAL
if (MSGlobals::gUseMesoSim) {
const <API key>& pars = v.getParameter();
SUMOReal pos = 0.0;
switch (pars.departPosProcedure) {
case DEPART_POS_GIVEN:
if (pars.departPos >= 0.) {
pos = pars.departPos;
} else {
pos = pars.departPos + getLength();
}
if (pos < 0 || pos > getLength()) {
WRITE_WARNING("Invalid departPos " + toString(pos) + " given for vehicle '" +
v.getID() + "'. Inserting at lane end instead.");
pos = getLength();
}
break;
case DEPART_POS_RANDOM:
case <API key>:
pos = RandHelper::rand(getLength());
break;
default:
break;
}
bool result = false;
MESegment* segment = MSGlobals::gMesoNet->getSegmentForEdge(*this, pos);
MEVehicle* veh = static_cast<MEVehicle*>(&v);
if (pars.departPosProcedure == DEPART_POS_FREE) {
while (segment != 0 && !result) {
result = segment->initialise(veh, time);
segment = segment->getNextSegment();
}
} else {
result = segment->initialise(veh, time);
}
return result;
}
#else
UNUSED_PARAMETER(time);
#endif
MSLane* insertionLane = getDepartLane(static_cast<MSVehicle&>(v));
return insertionLane != 0 && insertionLane->insertVehicle(static_cast<MSVehicle&>(v));
}
void
MSEdge::changeLanes(SUMOTime t) {
if (myFunction == <API key>) {
return;
}
assert(myLaneChanger != 0);
myLaneChanger->laneChange(t);
}
#ifdef HAVE_INTERNAL_LANES
const MSEdge*
MSEdge::<API key>(MSEdge* <API key>) const {
//@todo to be optimized
for (std::vector<MSLane*>::const_iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
MSLane* l = *i;
const MSLinkCont& lc = l->getLinkCont();
for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) {
MSLink* link = *j;
if (&link->getLane()->getEdge() == <API key>) {
if (link->getViaLane() != 0) {
return &link->getViaLane()->getEdge();
} else {
return 0; // network without internal links
}
}
}
}
return 0;
}
#endif
SUMOReal
MSEdge::<API key>(SUMOReal minSpeed) const {
assert(minSpeed > 0);
SUMOReal v = 0;
#ifdef HAVE_INTERNAL
if (MSGlobals::gUseMesoSim) {
MESegment* first = MSGlobals::gMesoNet->getSegmentForEdge(*this);
unsigned segments = 0;
do {
v += first->getMeanSpeed();
first = first->getNextSegment();
segments++;
} while (first != 0);
v /= (SUMOReal) segments;
} else {
#endif
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
v += (*i)->getMeanSpeed();
}
v /= (SUMOReal) myLanes->size();
#ifdef HAVE_INTERNAL
}
#endif
v = MAX2(minSpeed, v);
return getLength() / v;
}
bool
MSEdge::dictionary(const std::string& id, MSEdge* ptr) {
DictType::iterator it = myDict.find(id);
if (it == myDict.end()) {
// id not in myDict.
myDict[id] = ptr;
if (ptr->getNumericalID() != -1) {
while ((int)myEdges.size() < ptr->getNumericalID() + 1) {
myEdges.push_back(0);
}
myEdges[ptr->getNumericalID()] = ptr;
}
return true;
}
return false;
}
MSEdge*
MSEdge::dictionary(const std::string& id) {
DictType::iterator it = myDict.find(id);
if (it == myDict.end()) {
// id not in myDict.
return 0;
}
return it->second;
}
MSEdge*
MSEdge::dictionary(size_t id) {
assert(myEdges.size() > id);
return myEdges[id];
}
size_t
MSEdge::dictSize() {
return myDict.size();
}
size_t
MSEdge::numericalDictSize() {
return myEdges.size();
}
void
MSEdge::clear() {
for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) {
delete(*i).second;
}
myDict.clear();
}
void
MSEdge::insertIDs(std::vector<std::string>& into) {
for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) {
into.push_back((*i).first);
}
}
void
MSEdge::parseEdgesList(const std::string& desc, std::vector<const MSEdge*>& into,
const std::string& rid) {
if (desc[0] == BinaryFormatter::BF_ROUTE) {
std::istringstream in(desc, std::ios::binary);
char c;
in >> c;
FileHelpers::readEdgeVector(in, into, rid);
} else {
StringTokenizer st(desc);
parseEdgesList(st.getVector(), into, rid);
}
}
void
MSEdge::parseEdgesList(const std::vector<std::string>& desc, std::vector<const MSEdge*>& into,
const std::string& rid) {
for (std::vector<std::string>::const_iterator i = desc.begin(); i != desc.end(); ++i) {
const MSEdge* edge = MSEdge::dictionary(*i);
// check whether the edge exists
if (edge == 0) {
throw ProcessError("The edge '" + *i + "' within the route " + rid + " is not known."
+ "\n The route can not be build.");
}
into.push_back(edge);
}
}
SUMOReal
MSEdge::getDistanceTo(const MSEdge* other) const {
if (getLanes().size() > 0 && other->getLanes().size() > 0) {
return getLanes()[0]->getShape()[-1].distanceTo2D(other->getLanes()[0]->getShape()[0]);
} else {
return 0; // optimism is just right for astar
}
}
SUMOReal
MSEdge::getLength() const {
return getLanes()[0]->getLength();
}
SUMOReal
MSEdge::getSpeedLimit() const {
// @note lanes might have different maximum speeds in theory
return getLanes()[0]->getSpeedLimit();
}
SUMOReal
MSEdge::getVehicleMaxSpeed(const SUMOVehicle* const veh) const {
// @note lanes might have different maximum speeds in theory
return getLanes()[0]->getVehicleMaxSpeed(veh);
}
|
/**
* Contains base volume collider class.
* \file OPC_VolumeCollider.h
* \author Pierre Terdiman
* \date June, 2, 2001
*/
// Include Guard
#ifndef <API key>
#define <API key>
struct VolumeCache
{
VolumeCache() : Model(null) {}
~VolumeCache() {}
IceCore::Container TouchedPrimitives; //!< Indices of touched primitives
const BaseModel* Model; //!< Owner
};
class VolumeCollider : public Collider
{
public:
// Constructor / Destructor
VolumeCollider();
virtual ~VolumeCollider() = 0;
// Collision report
/**
* Gets the number of touched primitives after a collision query.
* \see GetContactStatus()
* \see <API key>()
* \return the number of touched primitives
*/
inline_ udword <API key>() const { return mTouchedPrimitives ? mTouchedPrimitives->GetNbEntries() : 0; }
/**
* Gets the list of touched primitives after a collision query.
* \see GetContactStatus()
* \see <API key>()
* \return the list of touched primitives (primitive indices)
*/
inline_ const udword* <API key>() const { return mTouchedPrimitives ? mTouchedPrimitives->GetEntries() : null; }
// Stats
/**
* Stats: gets the number of Volume-BV overlap tests after a collision query.
* \see <API key>()
* \return the number of Volume-BV tests performed during last query
*/
inline_ udword GetNbVolumeBVTests() const { return mNbVolumeBVTests; }
/**
* Stats: gets the number of Volume-Triangle overlap tests after a collision query.
* \see GetNbVolumeBVTests()
* \return the number of Volume-Triangle tests performed during last query
*/
inline_ udword <API key>() const { return mNbVolumePrimTests; }
// Settings
/**
* Validates current settings. You should call this method after all the settings / callbacks have been defined for a collider.
* \return null if everything is ok, else a string describing the problem
*/
override(Collider) const char* ValidateSettings();
protected:
// Touched primitives
IceCore::Container* mTouchedPrimitives; //!< List of touched primitives
// Precompured scale cache
IceMaths::Point mLocalScale; //!< Collision model's local scale (stripped off from its matrix)
// Dequantization coeffs
IceMaths::Point mCenterCoeff;
IceMaths::Point mExtentsCoeff;
// Stats
udword mNbVolumeBVTests; //!< Number of Volume-BV tests
udword mNbVolumePrimTests; //!< Number of Volume-Primitive tests
// Internal methods
void _Dump(const AABBCollisionNode* node);
void _Dump(const AABBNoLeafNode* node);
void _Dump(const AABBQuantizedNode* node);
void _Dump(const <API key>* node);
/**
* Initializes a query
*/
override(Collider) inline_ void InitQuery()
{
// Reset stats & contact status
mNbVolumeBVTests = 0;
mNbVolumePrimTests = 0;
Collider::InitQuery();
}
inline_ BOOL IsCacheValid(VolumeCache& cache)
{
// We're going to do a volume-vs-model query.
if(cache.Model!=mCurrentModel)
{
// Cached list was for another model so we can't keep it
// Keep track of new owner and reset cache
cache.Model = mCurrentModel;
return FALSE;
}
else
{
// Same models, no problem
return TRUE;
}
}
};
#endif // <API key>
|
<!DOCTYPE html>
<!
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 4.7.1
Author: KeenThemes
Website: http:
Contact: support@keenthemes.com
Follow: www.twitter.com/keenthemes
Dribbble: www.dribbble.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/<API key>/4021469?ref=keenthemes
Renew Support: http://themeforest.net/item/<API key>/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title>Metronic Admin Theme #3 | Fixed Top Bar</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="Preview page of Metronic Admin Theme #3 for " name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="../assets/global/css/components-rounded.min.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="../assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<link href="../assets/layouts/layout3/css/layout.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/layouts/layout3/css/themes/default.min.css" rel="stylesheet" type="text/css" id="style_color" />
<link href="../assets/layouts/layout3/css/custom.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME LAYOUT STYLES -->
<link rel="shortcut icon" href="favicon.ico" /> </head>
<!-- END HEAD -->
<body class="<API key> <API key>">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<div class="page-header">
<!-- BEGIN HEADER TOP -->
<div class="page-header-top">
<div class="container">
<!-- BEGIN LOGO -->
<div class="page-logo">
<a href="index.html">
<img src="../assets/layouts/layout3/img/logo-default.jpg" alt="logo" class="logo-default">
</a>
</div>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="menu-toggler"></a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="top-menu">
<ul class="nav navbar-nav pull-right">
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- DOC: Apply "dropdown-hoverable" class after "dropdown" and remove data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to enable hover dropdown mode -->
<!-- DOC: Remove "dropdown-hoverable" and add data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to the below A element with dropdown-toggle class -->
<li class="dropdown dropdown-extended <API key> dropdown-dark" id="<API key>">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell"></i>
<span class="badge badge-default">7</span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have
<strong>12 pending</strong> tasks</h3>
<a href="app_todo.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus"></i>
</span> New user registered. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 mins</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Server #12 overloaded. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">10 mins</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span> Server #2 not responding. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">14 hrs</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span> Application error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">2 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Database overloaded 68%. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> A user IP blocked. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">4 days</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span> Storage Server #4 not responding dfdfdfd. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">5 days</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span> System Error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">9 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Storage server failed. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END NOTIFICATION DROPDOWN -->
<!-- BEGIN TODO DROPDOWN -->
<li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-calendar"></i>
<span class="badge badge-default">3</span>
</a>
<ul class="dropdown-menu extended tasks">
<li class="external">
<h3>You have
<strong>12 pending</strong> tasks</h3>
<a href="app_todo_2.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New release v1.2 </span>
<span class="percent">30%</span>
</span>
<span class="progress">
<span style="width: 40%;" class="progress-bar <API key>" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Application deployment</span>
<span class="percent">65%</span>
</span>
<span class="progress">
<span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">65% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile app release</span>
<span class="percent">98%</span>
</span>
<span class="progress">
<span style="width: 98%;" class="progress-bar <API key>" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">98% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Database migration</span>
<span class="percent">10%</span>
</span>
<span class="progress">
<span style="width: 10%;" class="progress-bar <API key>" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">10% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Web server upgrade</span>
<span class="percent">58%</span>
</span>
<span class="progress">
<span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">58% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile development</span>
<span class="percent">85%</span>
</span>
<span class="progress">
<span style="width: 85%;" class="progress-bar <API key>" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">85% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New UI release</span>
<span class="percent">38%</span>
</span>
<span class="progress progress-striped">
<span style="width: 38%;" class="progress-bar <API key>" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">38% Complete</span>
</span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<li class="droddown dropdown-separator">
<span class="separator"></span>
</li>
<!-- BEGIN INBOX DROPDOWN -->
<li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="circle">3</span>
<span class="corner"></span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have
<strong>7 New</strong> Messages</h3>
<a href="app_inbox.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Lisa Wong </span>
<span class="time">Just Now </span>
</span>
<span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Richard Doe </span>
<span class="time">16 mins </span>
</span>
<span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Bob Nilson </span>
<span class="time">2 hrs </span>
</span>
<span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Lisa Wong </span>
<span class="time">40 mins </span>
</span>
<span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span>
</a>
</li>
<li>
<a href="
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Richard Doe </span>
<span class="time">46 mins </span>
</span>
<span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END INBOX DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<li class="dropdown dropdown-user dropdown-dark">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<img alt="" class="img-circle" src="../assets/layouts/layout3/img/avatar9.jpg">
<span class="username <API key>">Nick</span>
</a>
<ul class="dropdown-menu <API key>">
<li>
<a href="page_user_profile_1.html">
<i class="icon-user"></i> My Profile </a>
</li>
<li>
<a href="app_calendar.html">
<i class="icon-calendar"></i> My Calendar </a>
</li>
<li>
<a href="app_inbox.html">
<i class="icon-envelope-open"></i> My Inbox
<span class="badge badge-danger"> 3 </span>
</a>
</li>
<li>
<a href="app_todo_2.html">
<i class="icon-rocket"></i> My Tasks
<span class="badge badge-success"> 7 </span>
</a>
</li>
<li class="divider"> </li>
<li>
<a href="page_user_lock_1.html">
<i class="icon-lock"></i> Lock Screen </a>
</li>
<li>
<a href="page_user_login_1.html">
<i class="icon-key"></i> Log Out </a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
<!-- BEGIN QUICK SIDEBAR TOGGLER -->
<li class="dropdown dropdown-extended <API key>">
<span class="sr-only">Toggle Quick Sidebar</span>
<i class="icon-logout"></i>
</li>
<!-- END QUICK SIDEBAR TOGGLER -->
</ul>
</div>
<!-- END TOP NAVIGATION MENU -->
</div>
</div>
<!-- END HEADER TOP -->
<!-- BEGIN HEADER MENU -->
<div class="page-header-menu">
<div class="container">
<!-- BEGIN HEADER SEARCH BOX -->
<form class="search-form" action="page_general_search.html" method="GET">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="query">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit">
<i class="icon-magnifier"></i>
</a>
</span>
</div>
</form>
<!-- END HEADER SEARCH BOX -->
<!-- BEGIN MEGA MENU -->
<!-- DOC: Apply "hor-menu-light" class after the "hor-menu" class below to have a horizontal menu with white background -->
<!-- DOC: Remove data-hover="dropdown" and data-close-others="true" attributes below to disable the dropdown opening on mouse hover -->
<div class="hor-menu ">
<ul class="nav navbar-nav">
<li aria-haspopup="true" class="menu-dropdown <API key> ">
<a href="javascript:;"> Dashboard
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class=" ">
<a href="index.html" class="nav-link ">
<i class="icon-bar-chart"></i> Default Dashboard
<span class="badge badge-success">1</span>
</a>
</li>
<li aria-haspopup="true" class=" ">
<a href="dashboard_2.html" class="nav-link ">
<i class="icon-bulb"></i> Dashboard 2 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="dashboard_3.html" class="nav-link ">
<i class="icon-graph"></i> Dashboard 3
<span class="badge badge-danger">3</span>
</a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown ">
<a href="javascript:;"> UI Features
<span class="arrow"></span>
</a>
<ul class="dropdown-menu" style="min-width: 710px">
<li>
<div class="mega-menu-content">
<div class="row">
<div class="col-md-4">
<ul class="mega-menu-submenu">
<li>
<a href="ui_colors.html"> Color Library </a>
</li>
<li>
<a href="ui_metronic_grid.html"> Metronic Grid System </a>
</li>
<li>
<a href="ui_general.html"> General Components </a>
</li>
<li>
<a href="ui_buttons.html"> Buttons </a>
</li>
<li>
<a href="ui_buttons_spinner.html"> Spinner Buttons </a>
</li>
<li>
<a href="ui_confirmations.html"> Popover Confirmations </a>
</li>
<li>
<a href="ui_sweetalert.html"> Bootstrap Sweet Alerts </a>
</li>
<li>
<a href="ui_icons.html"> Font Icons </a>
</li>
<li>
<a href="ui_socicons.html"> Social Icons </a>
</li>
<li>
<a href="ui_typography.html"> Typography </a>
</li>
<li>
<a href="<API key>.html"> Tabs, Accordions & Navs </a>
</li>
<li>
<a href="ui_tree.html"> Tree View </a>
</li>
<li>
<a href="maps_google.html"> Google Maps </a>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="mega-menu-submenu">
<li>
<a href="maps_vector.html"> Vector Maps </a>
</li>
<li>
<a href="ui_timeline.html"> Timeline 1 </a>
</li>
<li>
<a href="ui_timeline_2.html"> Timeline 2 </a>
</li>
<li>
<a href="<API key>.html"> Horizontal Timeline </a>
</li>
<li>
<a href="<API key>.html"> Page Progress Bar - Flash </a>
</li>
<li>
<a href="<API key>.html"> Page Progress Bar - Big Counter </a>
</li>
<li>
<a href="ui_blockui.html"> Block UI </a>
</li>
<li>
<a href="ui_bootstrap_growl.html"> Bootstrap Growl Notifications </a>
</li>
<li>
<a href="ui_notific8.html"> Notific8 Notifications </a>
</li>
<li>
<a href="ui_toastr.html"> Toastr Notifications </a>
</li>
<li>
<a href="ui_bootbox.html"> Bootbox Dialogs </a>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="mega-menu-submenu">
<li>
<a href="ui_alerts_api.html"> Metronic Alerts API </a>
</li>
<li>
<a href="ui_session_timeout.html"> Session Timeout </a>
</li>
<li>
<a href="ui_idle_timeout.html"> User Idle Timeout </a>
</li>
<li>
<a href="ui_modals.html"> Modals </a>
</li>
<li>
<a href="ui_extended_modals.html"> Extended Modals </a>
</li>
<li>
<a href="ui_tiles.html"> Tiles </a>
</li>
<li>
<a href="ui_datepaginator.html"> Date Paginator </a>
</li>
<li>
<a href="ui_nestable.html"> Nestable List </a>
</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown <API key> active">
<a href="javascript:;"> Layouts
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link "> Light Mega Menu </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link "> Light Top Bar Dropdowns </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="layout_fluid_page.html" class="nav-link "> Fluid Page </a>
</li>
<li aria-haspopup="true" class=" active">
<a href="<API key>.html" class="nav-link active"> Fixed Top Bar </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link "> Fixed Mega Menu </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link "> Disabled Menu Links </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="layout_blank_page.html" class="nav-link "> Blank Page </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown mega-menu-full">
<a href="javascript:;"> Components
<span class="arrow"></span>
</a>
<ul class="dropdown-menu" style="min-width: ">
<li>
<div class="mega-menu-content">
<div class="row">
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 1</h3>
</li>
<li>
<a href="<API key>.html"> Date & Time Pickers </a>
</li>
<li>
<a href="<API key>.html"> Color Pickers </a>
</li>
<li>
<a href="components_select2.html"> Select2 Dropdowns </a>
</li>
<li>
<a href="<API key>.html"> Bootstrap Multiselect Dropdowns </a>
</li>
<li>
<a href="<API key>.html"> Bootstrap Select </a>
</li>
<li>
<a href="<API key>.html"> Bootstrap Multiple Select </a>
</li>
</ul>
</div>
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 2</h3>
</li>
<li>
<a href="<API key>.html"> Select Splitter </a>
</li>
<li>
<a href="<API key>.html"> Clipboard </a>
</li>
<li>
<a href="<API key>.html"> Typeahead Autocomplete </a>
</li>
<li>
<a href="<API key>.html"> Bootstrap Tagsinput </a>
</li>
<li>
<a href="<API key>.html"> Bootstrap Switch </a>
</li>
<li>
<a href="<API key>.html"> Bootstrap Maxlength </a>
</li>
</ul>
</div>
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 3</h3>
</li>
<li>
<a href="<API key>.html"> Bootstrap File Input </a>
</li>
<li>
<a href="<API key>.html"> Bootstrap Touchspin </a>
</li>
<li>
<a href="<API key>.html"> Form Widgets & Tools </a>
</li>
<li>
<a href="<API key>.html"> Context Menu </a>
</li>
<li>
<a href="components_editors.html"> Markdown & WYSIWYG Editors </a>
</li>
</ul>
</div>
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 4</h3>
</li>
<li>
<a href="<API key>.html"> Code Editors </a>
</li>
<li>
<a href="<API key>.html"> Ion Range Sliders </a>
</li>
<li>
<a href="<API key>.html"> NoUI Range Sliders </a>
</li>
<li>
<a href="<API key>.html"> Knob Circle Dials </a>
</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown <API key> ">
<a href="javascript:;"> More
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-settings"></i> Form Stuff
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="form_controls.html" class="nav-link "> Bootstrap Form
<br>Controls </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_controls_md.html" class="nav-link "> Material Design
<br>Form Controls </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_validation.html" class="nav-link "> Form Validation </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link "> Material Design
<br>Form Validation States </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_validation_md.html" class="nav-link "> Material Design
<br>Form Validation </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_layouts.html" class="nav-link "> Form Layouts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_repeater.html" class="nav-link "> Form Repeater </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_input_mask.html" class="nav-link "> Form Input Mask </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_editable.html" class="nav-link "> Form X-editable </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_wizard.html" class="nav-link "> Form Wizard </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_icheck.html" class="nav-link "> iCheck Controls </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_image_crop.html" class="nav-link "> Image Cropping </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_fileupload.html" class="nav-link "> Multiple File Upload </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_dropzone.html" class="nav-link "> Dropzone File Upload </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-briefcase"></i> Tables
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="table_static_basic.html" class="nav-link "> Basic Tables </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link "> Responsive Tables </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="table_bootstrap.html" class="nav-link "> Bootstrap Tables </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle"> Datatables
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="<API key>.html" class="nav-link "> Managed Datatables </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Buttons Extension </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Colreorder Extension </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Rowreorder Extension </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Scroller Extension </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> FixedHeader Extension </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Responsive Extension </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Editable Datatables </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Ajax Datatables </a>
</li>
</ul>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="?p=" class="nav-link nav-toggle ">
<i class="icon-wallet"></i> Portlets
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="portlet_boxed.html" class="nav-link "> Boxed Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_light.html" class="nav-link "> Light Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_solid.html" class="nav-link "> Solid Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_ajax.html" class="nav-link "> Ajax Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_draggable.html" class="nav-link "> Draggable Portlets </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="?p=" class="nav-link nav-toggle ">
<i class="icon-settings"></i> Elements
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="elements_steps.html" class="nav-link "> Steps </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_lists.html" class="nav-link "> Lists </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_ribbons.html" class="nav-link "> Ribbons </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_overlay.html" class="nav-link "> Overlays </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_cards.html" class="nav-link "> User Cards </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-bar-chart"></i> Charts
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="charts_amcharts.html" class="nav-link "> amChart </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_flotcharts.html" class="nav-link "> Flot Charts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_flowchart.html" class="nav-link "> Flow Charts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_google.html" class="nav-link "> Google Charts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_echarts.html" class="nav-link "> eCharts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_morris.html" class="nav-link "> Morris Charts </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle"> HighCharts
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="charts_highcharts.html" class="nav-link " target="_blank"> HighCharts </a>
</li>
<li class="">
<a href="charts_highstock.html" class="nav-link " target="_blank"> HighStock </a>
</li>
<li class="">
<a href="charts_highmaps.html" class="nav-link " target="_blank"> HighMaps </a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown <API key> ">
<a href="javascript:;">
<i class="icon-briefcase"></i> Pages
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-basket"></i> eCommerce
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="ecommerce_index.html" class="nav-link ">
<i class="icon-home"></i> Dashboard </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="ecommerce_orders.html" class="nav-link ">
<i class="icon-basket"></i> Orders </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-tag"></i> Order View </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="ecommerce_products.html" class="nav-link ">
<i class="icon-graph"></i> Products </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-graph"></i> Product Edit </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-docs"></i> Apps
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="app_todo.html" class="nav-link ">
<i class="icon-clock"></i> Todo 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_todo_2.html" class="nav-link ">
<i class="icon-check"></i> Todo 2 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_inbox.html" class="nav-link ">
<i class="icon-envelope"></i> Inbox </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_calendar.html" class="nav-link ">
<i class="icon-calendar"></i> Calendar </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_ticket.html" class="nav-link ">
<i class="icon-notebook"></i> Support </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-user"></i> User
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="page_user_profile_1.html" class="nav-link ">
<i class="icon-user"></i> Profile 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-user-female"></i> Profile 1 Account </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-user-following"></i> Profile 1 Help </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_profile_2.html" class="nav-link ">
<i class="icon-users"></i> Profile 2 </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-notebook"></i> Login
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="page_user_login_1.html" class="nav-link " target="_blank"> Login Page 1 </a>
</li>
<li class="">
<a href="page_user_login_2.html" class="nav-link " target="_blank"> Login Page 2 </a>
</li>
<li class="">
<a href="page_user_login_3.html" class="nav-link " target="_blank"> Login Page 3 </a>
</li>
<li class="">
<a href="page_user_login_4.html" class="nav-link " target="_blank"> Login Page 4 </a>
</li>
<li class="">
<a href="page_user_login_5.html" class="nav-link " target="_blank"> Login Page 5 </a>
</li>
<li class="">
<a href="page_user_login_6.html" class="nav-link " target="_blank"> Login Page 6 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_lock_1.html" class="nav-link " target="_blank">
<i class="icon-lock"></i> Lock Screen 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_lock_2.html" class="nav-link " target="_blank">
<i class="icon-lock-open"></i> Lock Screen 2 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="<API key>"></i> General
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="page_general_about.html" class="nav-link ">
<i class="icon-info"></i> About </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-call-end"></i> Contact </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-notebook"></i> Portfolio
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="<API key>.html" class="nav-link "> Portfolio 1 </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Portfolio 2 </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Portfolio 3 </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Portfolio 4 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-magnifier"></i> Search
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="page_general_search.html" class="nav-link "> Search 1 </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Search 2 </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Search 3 </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Search 4 </a>
</li>
<li class="">
<a href="<API key>.html" class="nav-link "> Search 5 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-tag"></i> Pricing </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_faq.html" class="nav-link ">
<i class="icon-wrench"></i> FAQ </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_blog.html" class="nav-link ">
<i class="icon-pencil"></i> Blog </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-note"></i> Blog Post </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-envelope"></i> Invoice </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link ">
<i class="icon-envelope"></i> Invoice 2 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-settings"></i> System
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="<API key>.html" class="nav-link " target="_blank"> Coming Soon </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_404_1.html" class="nav-link "> 404 Page 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_404_2.html" class="nav-link " target="_blank"> 404 Page 2 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_404_3.html" class="nav-link " target="_blank"> 404 Page 3 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_500_1.html" class="nav-link "> 500 Page 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_500_2.html" class="nav-link " target="_blank"> 500 Page 2 </a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- END MEGA MENU -->
</div>
</div>
<!-- END HEADER MENU -->
</div>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="<API key>">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Fixed Top Bar </h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
<!-- BEGIN THEME PANEL -->
<div class="btn-group btn-theme-panel">
<a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown">
<i class="icon-settings"></i>
</a>
<div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<h3>THEME COLORS</h3>
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<ul class="theme-colors">
<li class="theme-color theme-color-default" data-theme="default">
<span class="theme-color-view"></span>
<span class="theme-color-name">Default</span>
</li>
<li class="theme-color <API key>" data-theme="blue-hoki">
<span class="theme-color-view"></span>
<span class="theme-color-name">Blue Hoki</span>
</li>
<li class="theme-color <API key>" data-theme="blue-steel">
<span class="theme-color-view"></span>
<span class="theme-color-name">Blue Steel</span>
</li>
<li class="theme-color <API key>" data-theme="yellow-orange">
<span class="theme-color-view"></span>
<span class="theme-color-name">Orange</span>
</li>
<li class="theme-color <API key>" data-theme="yellow-crusta">
<span class="theme-color-view"></span>
<span class="theme-color-name">Yellow Crusta</span>
</li>
</ul>
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
<ul class="theme-colors">
<li class="theme-color <API key>" data-theme="green-haze">
<span class="theme-color-view"></span>
<span class="theme-color-name">Green Haze</span>
</li>
<li class="theme-color <API key>" data-theme="red-sunglo">
<span class="theme-color-view"></span>
<span class="theme-color-name">Red Sunglo</span>
</li>
<li class="theme-color <API key>" data-theme="red-intense">
<span class="theme-color-view"></span>
<span class="theme-color-name">Red Intense</span>
</li>
<li class="theme-color <API key>" data-theme="purple-plum">
<span class="theme-color-view"></span>
<span class="theme-color-name">Purple Plum</span>
</li>
<li class="theme-color <API key>" data-theme="purple-studio">
<span class="theme-color-view"></span>
<span class="theme-color-name">Purple Studio</span>
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 seperator">
<h3>LAYOUT</h3>
<ul class="theme-settings">
<li> Theme Style
<select class="theme-setting theme-setting-style form-control input-sm input-small input-inline tooltips" data-original-title="Change theme style" data-container="body" data-placement="left">
<option value="boxed" selected="selected">Square corners</option>
<option value="rounded">Rounded corners</option>
</select>
</li>
<li> Layout
<select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Change layout type" data-container="body" data-placement="left">
<option value="boxed" selected="selected">Boxed</option>
<option value="fluid">Fluid</option>
</select>
</li>
<li> Top Menu Style
<select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Change top menu dropdowns style" data-container="body"
data-placement="left">
<option value="dark" selected="selected">Dark</option>
<option value="light">Light</option>
</select>
</li>
<li> Top Menu Mode
<select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) top menu" data-container="body"
data-placement="left">
<option value="fixed">Fixed</option>
<option value="not-fixed" selected="selected">Not Fixed</option>
</select>
</li>
<li> Mega Menu Style
<select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Change mega menu dropdowns style" data-container="body"
data-placement="left">
<option value="dark" selected="selected">Dark</option>
<option value="light">Light</option>
</select>
</li>
<li> Mega Menu Mode
<select class="theme-setting <API key> form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) mega menu" data-container="body"
data-placement="left">
<option value="fixed" selected="selected">Fixed</option>
<option value="not-fixed">Not Fixed</option>
</select>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- END THEME PANEL -->
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Layouts</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<div class="note note-info">
<p> To set fixed top bar apply <code><API key></code> to the body element. </p>
</div>
<div class="portlet light portlet-fit ">
<div class="portlet-title">
<div class="caption">
<i class=" icon-layers font-green"></i>
<span class="caption-subject font-green bold uppercase">Basic Portlet</span>
</div>
<div class="actions">
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-cloud-upload"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-wrench"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-trash"></i>
</a>
</div>
</div>
<div class="portlet-body">
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? </p>
<p> Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any
code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in
app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which
is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering
if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d
love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. </p> Thanks a ton!height of the window and adjusts the height of an element that I could re-purpose
or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing
UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that
I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi!
This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. </p>
<p> I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend
for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI!
Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element
that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks
a ton! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any
code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in
app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which
is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering
if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d
love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. </p> Thanks a ton!height of the window and adjusts the height of an element that I could re-purpose
or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing
UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that
I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi!
This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. </p>
<p> I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend
for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI!
Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element
that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks
a ton! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="<API key>">
<i class="icon-login"></i>
</a>
<div class="<API key>" <API key>="false">
<div class="page-quick-sidebar">
<ul class="nav nav-tabs">
<li class="active">
<a href="javascript:;" data-target="#quick_sidebar_tab_1" data-toggle="tab"> Users
<span class="badge badge-danger">2</span>
</a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_2" data-toggle="tab"> Alerts
<span class="badge badge-success">7</span>
</a>
</li>
<li class="dropdown">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> More
<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-bell"></i> Alerts </a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-info"></i> Notifications </a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-speech"></i> Activities </a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-settings"></i> Settings </a>
</li>
</ul>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active <API key>" id="quick_sidebar_tab_1">
<div class="<API key>" data-rail-color="#ddd" data-wrapper-class="<API key>">
<h3 class="list-heading">Staff</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-success">8</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar3.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Bob Nilson</h4>
<div class="media-heading-sub"> Project Manager </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar1.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Nick Larson</h4>
<div class="media-heading-sub"> Art Director </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">3</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar4.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Hubert</h4>
<div class="media-heading-sub"> CTO </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar2.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ella Wong</h4>
<div class="media-heading-sub"> CEO </div>
</div>
</li>
</ul>
<h3 class="list-heading">Customers</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-warning">2</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar6.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lara Kunis</h4>
<div class="media-heading-sub"> CEO, Loop Inc </div>
<div class="media-heading-small"> Last seen 03:10 AM </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="label label-sm label-success">new</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar7.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ernie Kyllonen</h4>
<div class="media-heading-sub"> Project Manager,
<br> SmartBizz PTL </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar8.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lisa Stone</h4>
<div class="media-heading-sub"> CTO, Keort Inc </div>
<div class="media-heading-small"> Last seen 13:10 PM </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-success">7</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar9.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Portalatin</h4>
<div class="media-heading-sub"> CFO, H&D LTD </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar10.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Irina Savikova</h4>
<div class="media-heading-sub"> CEO, Tizda Motors Inc </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">4</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar11.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Maria Gomez</h4>
<div class="media-heading-sub"> Manager, Infomatic Inc </div>
<div class="media-heading-small"> Last seen 03:10 AM </div>
</div>
</li>
</ul>
</div>
<div class="<API key>">
<div class="<API key>">
<div class="<API key>">
<a href="javascript:;" class="<API key>">
<i class="icon-arrow-left"></i>Back</a>
</div>
<div class="<API key>">
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body"> When could you send me the report ? </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:15</span>
<span class="body"> Its almost done. I will be sending it shortly </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body"> Alright. Thanks! :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:16</span>
<span class="body"> You are most welcome. Sorry for the delay. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> No probs. Just take your time :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body"> Alright. I just emailed it to you. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> Great! Thanks. Will check it right away. </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body"> Please let me know if you have any comment. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> Sure. I will check and buzz you if anything needs to be corrected. </span>
</div>
</div>
</div>
<div class="<API key>">
<div class="input-group">
<input type="text" class="form-control" placeholder="Type a message here...">
<div class="input-group-btn">
<button type="button" class="btn green">
<i class="icon-paper-clip"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane <API key>" id="quick_sidebar_tab_2">
<div class="<API key>">
<h3 class="list-heading">General</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 4 pending tasks.
<span class="label label-sm label-warning "> Take action
<i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> Just now </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Finance Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> New order received with
<span class="label label-sm label-success"> Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 30 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Web server hardware needs to be upgraded.
<span class="label label-sm label-warning"> Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 2 hours </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> IPO Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
</ul>
<h3 class="list-heading">System</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 4 pending tasks.
<span class="label label-sm label-warning "> Take action
<i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> Just now </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Finance Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> New order received with
<span class="label label-sm label-success"> Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 30 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-warning">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Web server hardware needs to be upgraded.
<span class="label label-sm label-default "> Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 2 hours </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> IPO Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane <API key>" id="quick_sidebar_tab_3">
<div class="<API key>">
<h3 class="list-heading">General Settings</h3>
<ul class="list-items borderless">
<li> Enable Notifications
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Allow Tracking
<input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Log Errors
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Auto Sumbit Issues
<input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Enable SMS Alerts
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
</ul>
<h3 class="list-heading">System Settings</h3>
<ul class="list-items borderless">
<li> Security Level
<select class="form-control input-inline input-sm input-small">
<option value="1">Normal</option>
<option value="2" selected>Medium</option>
<option value="e">High</option>
</select>
</li>
<li> Failed Email Attempts
<input class="form-control input-inline input-sm input-small" value="5" /> </li>
<li> Secondary SMTP Port
<input class="form-control input-inline input-sm input-small" value="3560" /> </li>
<li> Notify On System Error
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Notify On SMTP Error
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
</ul>
<div class="inner-content">
<button class="btn btn-success">
<i class="icon-settings"></i> Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<!-- BEGIN PRE-FOOTER -->
<div class="page-prefooter">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12 footer-block">
<h2>About</h2>
<p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam dolore. </p>
</div>
<div class="col-md-3 col-sm-6 col-xs12 footer-block">
<h2>Subscribe Email</h2>
<div class="subscribe-form">
<form action="javascript:;">
<div class="input-group">
<input type="text" placeholder="mail@email.com" class="form-control">
<span class="input-group-btn">
<button class="btn" type="submit">Submit</button>
</span>
</div>
</form>
</div>
</div>
<div class="col-md-3 col-sm-6 col-xs-12 footer-block">
<h2>Follow Us On</h2>
<ul class="social-icons">
<li>
<a href="javascript:;" data-original-title="rss" class="rss"></a>
</li>
<li>
<a href="javascript:;" data-original-title="facebook" class="facebook"></a>
</li>
<li>
<a href="javascript:;" data-original-title="twitter" class="twitter"></a>
</li>
<li>
<a href="javascript:;" data-original-title="googleplus" class="googleplus"></a>
</li>
<li>
<a href="javascript:;" data-original-title="linkedin" class="linkedin"></a>
</li>
<li>
<a href="javascript:;" data-original-title="youtube" class="youtube"></a>
</li>
<li>
<a href="javascript:;" data-original-title="vimeo" class="vimeo"></a>
</li>
</ul>
</div>
<div class="col-md-3 col-sm-6 col-xs-12 footer-block">
<h2>Contacts</h2>
<address class="margin-bottom-40"> Phone: 800 123 3456
<br> Email:
<a href="mailto:info@metronic.com">info@metronic.com</a>
</address>
</div>
</div>
</div>
</div>
<!-- END PRE-FOOTER -->
<!-- BEGIN INNER FOOTER -->
<div class="page-footer">
<div class="container"> 2016 © Metronic Theme By
<a target="_blank" href="http://keenthemes.com">Keenthemes</a> |
<a href="http://themeforest.net/item/<API key>/4021469?ref=keenthemes" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Metronic!</a>
</div>
</div>
<div class="scroll-to-top">
<i class="icon-arrow-up"></i>
</div>
<!-- END INNER FOOTER -->
<!-- END FOOTER -->
</div>
</div>
</div>
<!-- BEGIN QUICK NAV -->
<nav class="quick-nav">
<a class="quick-nav-trigger" href="
<span aria-hidden="true"></span>
</a>
<ul>
<li>
<a href="https://themeforest.net/item/<API key>/4021469?ref=keenthemes" target="_blank" class="active">
<span>Purchase Metronic</span>
<i class="icon-basket"></i>
</a>
</li>
<li>
<a href="https://themeforest.net/item/<API key>/reviews/4021469?ref=keenthemes" target="_blank">
<span>Customer Reviews</span>
<i class="icon-users"></i>
</a>
</li>
<li>
<a href="http://keenthemes.com/showcast/" target="_blank">
<span>Showcase</span>
<i class="icon-user"></i>
</a>
</li>
<li>
<a href="http://keenthemes.com/metronic-theme/changelog/" target="_blank">
<span>Changelog</span>
<i class="icon-graph"></i>
</a>
</li>
</ul>
<span aria-hidden="true" class="quick-nav-bg"></span>
</nav>
<div class="quick-nav-overlay"></div>
<!-- END QUICK NAV -->
<!--[if lt IE 9]>
<script src="../assets/global/plugins/respond.min.js"></script>
<script src="../assets/global/plugins/excanvas.min.js"></script>
<script src="../assets/global/plugins/ie8.fix.min.js"></script>
<![endif]
<!-- BEGIN CORE PLUGINS -->
<script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN THEME GLOBAL SCRIPTS -->
<script src="../assets/global/scripts/app.min.js" type="text/javascript"></script>
<!-- END THEME GLOBAL SCRIPTS -->
<!-- BEGIN THEME LAYOUT SCRIPTS -->
<script src="../assets/layouts/layout3/scripts/layout.min.js" type="text/javascript"></script>
<script src="../assets/layouts/layout3/scripts/demo.min.js" type="text/javascript"></script>
<script src="../assets/layouts/global/scripts/quick-sidebar.min.js" type="text/javascript"></script>
<script src="../assets/layouts/global/scripts/quick-nav.min.js" type="text/javascript"></script>
<!-- END THEME LAYOUT SCRIPTS -->
</body>
</html>
|
package es.ucm.fdi.emf.model.ed2.diagram.sheet;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.<API key>;
import org.eclipse.swt.graphics.Image;
import es.ucm.fdi.emf.model.ed2.diagram.navigator.Ed2NavigatorGroup;
import es.ucm.fdi.emf.model.ed2.diagram.part.Ed2VisualIDRegistry;
import es.ucm.fdi.emf.model.ed2.diagram.providers.Ed2ElementTypes;
/**
* @generated
*/
public class <API key> extends BaseLabelProvider implements
ILabelProvider {
/**
* @generated
*/
public String getText(Object element) {
element = unwrap(element);
if (element instanceof Ed2NavigatorGroup) {
return ((Ed2NavigatorGroup) element).getGroupName();
}
IElementType etype = getElementType(getView(element));
return etype == null ? "" : etype.getDisplayName();
}
/**
* @generated
*/
public Image getImage(Object element) {
IElementType etype = getElementType(getView(unwrap(element)));
return etype == null ? null : Ed2ElementTypes.getImage(etype);
}
/**
* @generated
*/
private Object unwrap(Object element) {
if (element instanceof <API key>) {
return ((<API key>) element).getFirstElement();
}
return element;
}
/**
* @generated
*/
private View getView(Object element) {
if (element instanceof View) {
return (View) element;
}
if (element instanceof IAdaptable) {
return (View) ((IAdaptable) element).getAdapter(View.class);
}
return null;
}
/**
* @generated
*/
private IElementType getElementType(View view) {
// For intermediate views climb up the containment hierarchy to find the one associated with an element type.
while (view != null) {
int vid = Ed2VisualIDRegistry.getVisualID(view);
IElementType etype = Ed2ElementTypes.getElementType(vid);
if (etype != null) {
return etype;
}
view = view.eContainer() instanceof View ? (View) view.eContainer()
: null;
}
return null;
}
}
|
# The Original Code is Mozilla Universal charset detector code.
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# This library is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# You should have received a copy of the GNU Lesser General Public
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import <API key>
from langcyrillicmodel import <API key>, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import <API key>, <API key>
from langhungarianmodel import <API key>, <API key>
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
def __init__(self):
CharSetGroupProber.__init__(self)
self._mProbers = [ \
<API key>(<API key>),
<API key>(Koi8rModel),
<API key>(Latin5CyrillicModel),
<API key>(MacCyrillicModel),
<API key>(Ibm866Model),
<API key>(Ibm855Model),
<API key>(Latin7GreekModel),
<API key>(Win1253GreekModel),
<API key>(<API key>),
<API key>(<API key>),
<API key>(<API key>),
<API key>(<API key>),
<API key>(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = <API key>(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = <API key>(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset()
|
# <API key>: true
module Minitest
def self.<API key>(_options)
if defined?(SimpleCov)
SimpleCov.external_at_exit = true
Minitest.after_run do
SimpleCov.at_exit_behavior
end
end
end
end
|
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
// $hash=<SHA1-like>$
#ifndef <API key>
#define <API key>
#pragma once
#if !defined(WRAPPING_CEF_SHARED)
#error This file can be included wrapper-side only
#endif
#include "include/capi/cef_dom_capi.h"
#include "include/cef_dom.h"
#include "libcef_dll/ctocpp/ctocpp_ref_counted.h"
// Wrap a C structure with a C++ class.
// This class may be instantiated and accessed wrapper-side only.
class CefDOMNodeCToCpp
: public CefCToCppRefCounted<CefDOMNodeCToCpp, CefDOMNode, cef_domnode_t> {
public:
CefDOMNodeCToCpp();
// CefDOMNode methods.
Type GetType() OVERRIDE;
bool IsText() OVERRIDE;
bool IsElement() OVERRIDE;
bool IsEditable() OVERRIDE;
bool <API key>() OVERRIDE;
CefString <API key>() OVERRIDE;
bool IsSame(CefRefPtr<CefDOMNode> that) OVERRIDE;
CefString GetName() OVERRIDE;
CefString GetValue() OVERRIDE;
bool SetValue(const CefString& value) OVERRIDE;
CefString GetAsMarkup() OVERRIDE;
CefRefPtr<CefDOMDocument> GetDocument() OVERRIDE;
CefRefPtr<CefDOMNode> GetParent() OVERRIDE;
CefRefPtr<CefDOMNode> GetPreviousSibling() OVERRIDE;
CefRefPtr<CefDOMNode> GetNextSibling() OVERRIDE;
bool HasChildren() OVERRIDE;
CefRefPtr<CefDOMNode> GetFirstChild() OVERRIDE;
CefRefPtr<CefDOMNode> GetLastChild() OVERRIDE;
CefString GetElementTagName() OVERRIDE;
bool <API key>() OVERRIDE;
bool HasElementAttribute(const CefString& attrName) OVERRIDE;
CefString GetElementAttribute(const CefString& attrName) OVERRIDE;
void <API key>(AttributeMap& attrMap) OVERRIDE;
bool SetElementAttribute(const CefString& attrName,
const CefString& value) OVERRIDE;
CefString GetElementInnerText() OVERRIDE;
CefRect GetElementBounds() OVERRIDE;
};
#endif // <API key>
|
local pi = math.pi
local player_in_bed = 0
local is_sp = minetest.is_singleplayer()
local enable_respawn = minetest.setting_getbool("enable_bed_respawn")
if enable_respawn == nil then
enable_respawn = true
end
-- Helper functions
local function get_look_yaw(pos)
local n = minetest.get_node(pos)
if n.param2 == 1 then
return pi / 2, n.param2
elseif n.param2 == 3 then
return -pi / 2, n.param2
elseif n.param2 == 0 then
return pi, n.param2
else
return 0, n.param2
end
end
local function <API key>()
local enable_night_skip = minetest.setting_getbool("<API key>")
if enable_night_skip == nil then
enable_night_skip = true
end
return enable_night_skip
end
local function check_in_beds(players)
local in_bed = beds.player
if not players then
players = minetest.<API key>()
end
for n, player in ipairs(players) do
local name = player:get_player_name()
if not in_bed[name] then
return false
end
end
return #players > 0
end
local function lay_down(player, pos, bed_pos, state, skip)
local name = player:get_player_name()
local hud_flags = player:hud_get_flags()
if not player or not name then
return
end
-- stand up
if state ~= nil and not state then
local p = beds.pos[name] or nil
if beds.player[name] ~= nil then
beds.player[name] = nil
player_in_bed = player_in_bed - 1
end
-- skip here to prevent sending player specific changes (used for leaving players)
if skip then
return
end
if p then
player:setpos(p)
end
-- physics, eye_offset, etc
player:set_eye_offset({x = 0, y = 0, z = 0}, {x = 0, y = 0, z = 0})
player:set_look_yaw(math.random(1, 180) / 100)
default.player_attached[name] = false
player:<API key>(1, 1, 1)
hud_flags.wielditem = true
default.<API key>(player, "stand" , 30)
-- lay down
else
beds.player[name] = 1
beds.pos[name] = pos
player_in_bed = player_in_bed + 1
-- physics, eye_offset, etc
player:set_eye_offset({x = 0, y = -13, z = 0}, {x = 0, y = 0, z = 0})
local yaw, param2 = get_look_yaw(bed_pos)
player:set_look_yaw(yaw)
local dir = minetest.facedir_to_dir(param2)
local p = {x = bed_pos.x + dir.x / 2, y = bed_pos.y, z = bed_pos.z + dir.z / 2}
player:<API key>(0, 0, 0)
player:setpos(p)
default.player_attached[name] = true
hud_flags.wielditem = false
default.<API key>(player, "lay" , 0)
end
player:hud_set_flags(hud_flags)
end
local function update_formspecs(finished)
local ges = #minetest.<API key>()
local form_n = ""
local is_majority = (ges / 2) < player_in_bed
if finished then
form_n = beds.formspec .. "label[2.7,11; Good morning.]"
else
form_n = beds.formspec .. "label[2.2,11;" .. tostring(player_in_bed) ..
" of " .. tostring(ges) .. " players are in bed]"
if is_majority and <API key>() then
form_n = form_n .. "button_exit[2,8;4,0.75;force;Force night skip]"
end
end
for name,_ in pairs(beds.player) do
minetest.show_formspec(name, "beds_form", form_n)
end
end
-- Public functions
function beds.kick_players()
for name, _ in pairs(beds.player) do
local player = minetest.get_player_by_name(name)
lay_down(player, nil, nil, false)
end
end
function beds.skip_night()
minetest.set_timeofday(0.23)
beds.set_spawns()
end
function beds.on_rightclick(pos, player)
local name = player:get_player_name()
local ppos = player:getpos()
local tod = minetest.get_timeofday()
if tod > 0.2 and tod < 0.805 then
if beds.player[name] then
lay_down(player, nil, nil, false)
end
minetest.chat_send_player(name, "You can only sleep at night.")
return
end
-- move to bed
if not beds.player[name] then
lay_down(player, ppos, pos)
else
lay_down(player, nil, nil, false)
end
if not is_sp then
update_formspecs(false)
end
-- skip the night and let all players stand up
if check_in_beds() then
minetest.after(2, function()
if not is_sp then
update_formspecs(<API key>())
end
if <API key>() then
beds.skip_night()
beds.kick_players()
end
end)
end
end
-- Callbacks
minetest.<API key>(function(player)
beds.read_spawns()
end)
-- respawn player at bed if enabled and valid position is found
minetest.<API key>(function(player)
if not enable_respawn then
return false
end
local name = player:get_player_name()
local pos = beds.spawn[name] or nil
if pos then
player:setpos(pos)
return true
end
end)
minetest.<API key>(function(player)
local name = player:get_player_name()
lay_down(player, nil, nil, false, true)
beds.player[name] = nil
if check_in_beds() then
minetest.after(2, function()
update_formspecs(<API key>())
if <API key>() then
beds.skip_night()
beds.kick_players()
end
end)
end
end)
minetest.<API key>(function(player, formname, fields)
if formname ~= "beds_form" then
return
end
if fields.quit or fields.leave then
lay_down(player, nil, nil, false)
update_formspecs(false)
end
if fields.force then
update_formspecs(<API key>())
if <API key>() then
beds.skip_night()
beds.kick_players()
end
end
end)
|
.color-picker {
-moz-box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3);
box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3);
-moz-border-radius: 0 0 5px 5px;
-<API key>: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
}
.<API key>,
.color-picker-closer {
position: absolute;
top: -22px;
color: white;
padding: 5px 15px 3px;
-moz-border-radius: 5px 5px 0 0;
-<API key>: 5px 5px 0 0;
border-radius: 5px 5px 0 0;
}
.<API key> {
left: 0;
width: 245px;
height: 15px;
}
.color-picker-value {
position: absolute;
top: -22px;
}
.color-picker-color {
position: absolute;
top: -17px;
left: 15px;
width: 12px;
height: 12px;
border: 1px solid #ccc;
}
.color-picker-hex {
position: absolute;
top: -16px;
left: 33px;
color: white;
font-size: 10px;
}
.color-picker-closer {
right: 0px;
cursor: pointer;
}
.color-picker img {
display: block;
margin: 0;
padding: 0;
border: 0;
}
.color-picker div {
float: left;
}
.color-picker-sv {
position: relative;
background-repeat: none;
margin-right: 20px;
width: 200px;
height: 200px;
}
.color-picker-h {
position: relative;
background-repeat: none;
width: 25px;
height: 200px;
}
.<API key> {
position: absolute;
left: -14px;
top: -5px;
width: 44px;
height: 12px;
}
.<API key> {
position: absolute;
left: -8px;
top: -8px;
width: 17px;
height: 17px;
}
|
#include "esl_config.h"
#include <string.h>
#include <ctype.h>
#include "easel.h"
/* Function: esl_mem_strtoi32()
* Synopsis: Convert a chunk of text memory to an int32_t.
*
* Purpose: Convert the text starting at <p> to an <int32_t>, converting
* no more than <n> characters (the valid length of non-<NUL>
* terminated memory buffer <p>). Interpret the text as
* base <base> (2 or 10, for example). <base> must be 2..36,
* or 0. 0 is treated specially as base 8, 10, or 16, autodetected
* according to the leading characters of the number format.
*
* Any leading whitespace is skipped. The next letter may
* be a '-' for a negative number. If <base> is 0 or 16,
* the next two characters may be "0x", in which case hex base
* 16 is assumed. Else if <base> is 0 and the next
* character is '0', octal base 8 is assumed. All subsequent
* characters are converted to a number, until an invalid
* character is reached. Upper or lower case letters are
* accepted, starting at A or a, for bases over 10. For
* example, In base 16, characters A-F or a-f are accepted.
* The base of the representation is limited to 36 because
* 'Z' or 'z' represents 35.
*
* The converted value is optionally returned in <*opt_val>.
* The number of characters parsed (up to the first invalid
* character, or <n>, whichever comes first) is optionally
* returned in <*opt_nc>. The caller can reposition a parser
* to <p + *opt_nc> to exactly skip past the parsed number.
*
* If no valid digit is found (including pathological cases
* of leader-only, such as "0x" or "-"), then return <eslEINVAL>,
* and <*opt_nc> and <*opt_val> are both 0.
*
* This syntax is essentially identical to <strtol()>,
* except that we can operate on a non-NUL-terminated
* memory buffer of maximum length <n>, rather than on a
* NUL-terminated string.
*
* Args: p - pointer to text buffer to convert to int32_t
* n - maximum number of chars to parse in <p>: p[0..n-1] are valid.
* base - integer base. Often 10, 2, 8, or 16. Must be
* <2..36>, or 0. 0 means base 8, 10, or 16 depending on
* autodetected format.
* *opt_nc - optRETURN: number of valid chars parsed from p.
* First invalid char is p[*opt_nc].
* *opt_val - optRETURN: parsed value.
*
* Returns: <eslOK> on success.
*
* <eslEFORMAT> if no valid integer digits are found. Now
* <*opt_val> and <*opt_nc> are 0.
*
* <eslERANGE> on an overflow error. In this case
* <*opt_val> is <INT32_MAX> or <INT32_MIN> for an
* overflow or underflow, respectively. <*opt_nc> is
* set to the number of characters parsed INCLUDING
* the digit that caused the overflow.
*
* Throws: <eslEINVAL> if <base> isn't in range <0..36>. Now
* <*opt_nc> and <*opt_val> are 0.
*
* Note: An example of why you need this instead of
* strtol(): suppose you've mmap()'ed a file to memory,
* and it ends in ... "12345". You can't strtol the
* end of the mmap'ed memory buffer because it is not
* a NUL-terminated string. (Same goes anywhere in the file,
* though elsewhere in the file you could overwrite
* a NUL where you need it. At EOF of an mmap'ed() buffer,
* you can't even do that.)
*
* sscanf() doesn't work either - I don't see a way to
* limit it to a buffer of at most <n> chars.
*
* I could copy <p> to a temporary allocated string that I
* NUL-terminate, then use strtol() or suchlike, but that's
* just as awful as what I've done here (rewriting
* strtol()). Plus, here I get complete control of the integer
* type (<int32_t>) whereas strtol() gives me the less satisfying
* <long>.
*/
int
esl_mem_strtoi32(char *p, esl_pos_t n, int base, int *opt_nc, int32_t *opt_val)
{
esl_pos_t i = 0;
int32_t sign = 1;
int32_t currval = 0;
int32_t digit = 0;
int ndigits = 0;
if (base < 0 || base == 1 || base > 36) ESL_EXCEPTION(eslEINVAL, "base must be 2..36 or 0");
while (i < n && isspace(p[i])) i++; /* skip leading whitespace */
if (i < n && p[i] == '-') { sign = -1; i++; }
if ((base == 0 || base == 16) && i < n-1 && p[i] == '0' && p[i+1] == 'x')
{ i += 2; base = 16; }
else if (base == 0 && i < n && p[i] == '0')
{ i += 1; base = 8; }
else if (base == 0)
{ base = 10; }
for (ndigits = 0; i < n; i++, ndigits++)
{
if (isdigit(p[i])) digit = p[i] - '0';
else if (isupper(p[i])) digit = 10 + (p[i] - 'A');
else if (islower(p[i])) digit = 10 + (p[i] - 'a');
else break;
if (digit >= base) break;
if (sign == 1)
{
if (currval > (INT32_MAX - digit) / base)
{
if (opt_val) *opt_val = INT32_MAX;
if (opt_nc) *opt_nc = i+1;
return eslERANGE;
}
currval = currval * base + digit;
}
else
{
if (currval < (INT32_MIN + digit) / base)
{
if (opt_val) *opt_val = INT32_MIN;
if (opt_nc) *opt_nc = i+1;
return eslERANGE;
}
currval = currval * base - digit;
}
}
if (opt_nc) { *opt_nc = (ndigits ? i : 0); }
if (opt_val) { *opt_val = currval; }
return (ndigits ? eslOK : eslEFORMAT);
}
int
esl_memnewline(const char *m, esl_pos_t n, esl_pos_t *ret_nline, int *ret_nterm)
{
char *ptr = memchr(m, '\n', n);
if (ptr == NULL) { *ret_nline = n; *ret_nterm = 0; }
else if (ptr > m && *(ptr-1) == '\r') { *ret_nline = ptr-m-1; *ret_nterm = 2; }
else { *ret_nline = ptr-m; *ret_nterm = 1; }
return eslOK;
}
/* Function: esl_memtok()
* Synopsis: Get next delimited token from a line.
*
* Purpose: Given references to a line and its length, <*p> and <*n>,
* find the next token delimited by any of the characters
* in the string <delim>. Set <*ret_tok> to point at the
* start of the token, and <*ret_toklen> to its length.
* Increment <*p> to point to the next non-delim character
* that follows, and decrement <*n> by the same,
* so that <*p> and <*n> are ready for another
* call to <esl_memtok()>.
*
* Three differences between <esl_strtok()> and <esl_memtok()>:
* first, <esl_strtok()> expects a NUL-terminated string,
* whereas <esl_memtok()>'s line does not need to be
* NUL-terminated; second, <esl_memtok()> does not modify
* the string, whereas <esl_strtok()> writes NUL bytes
* to delimit tokens; third, <esl_memtok()> skips trailing
* <delim> characters as well as leading ones.
*
* Args: *p - pointer to line;
* will be incremented to next byte after token.
* *n - pointer to line length, in bytes;
* will be decremented
* delim - delimiter chars (example: " \t\r\n")
* *ret_tok - RETURN: ptr to token found in <*p>
* *ret_toklen - RETURN: length of token
*
* Returns: <eslOK> if a delimited token is found.
* <eslEOL> if not; now <*ret_tok> is <NULL> and <*ret_toklen> is <0>.
*
*/
int
esl_memtok(char **p, esl_pos_t *n, const char *delim, char **ret_tok, esl_pos_t *ret_toklen)
{
char *s = *p;
esl_pos_t so, xo, eo;
for (so = 0; so < *n; so++) if (strchr(delim, s[so]) == NULL) break;
for (xo = so; xo < *n; xo++) if (strchr(delim, s[xo]) != NULL) break;
for (eo = xo; eo < *n; eo++) if (strchr(delim, s[eo]) == NULL) break;
if (so == *n) { *ret_tok = NULL; *ret_toklen = 0; return eslEOL; }
else { *p += eo; *n -= eo; *ret_tok = s + so; *ret_toklen = xo - so; return eslOK; }
}
/* Function: esl_memspn()
* Synopsis: Finds length of prefix consisting only of given chars
*
* Purpose: For line <p> of length <n>, return the length of
* a prefix that consists only of characters in the
* string <allow>.
*
* A commonly used idiom for "buffer is all whitespace"
* is <esl_memspn(p, n, " \t\r\n") == n>.
*/
esl_pos_t
esl_memspn(char *p, esl_pos_t n, const char *allow)
{
esl_pos_t so;
for (so = 0; so < n; so++) if (strchr(allow, p[so]) == NULL) break;
return so;
}
/* Function: esl_memcspn()
* Synopsis: Finds length of prefix consisting of anything other than given chars
*
* Purpose: For line <p> of length <n>, return the length of
* a prefix that consists only of characters NOT in the
* string <disallow>.
*/
esl_pos_t
esl_memcspn(char *p, esl_pos_t n, const char *disallow)
{
esl_pos_t so;
for (so = 0; so < n; so++) if (strchr(disallow, p[so]) != NULL) break;
return so;
}
/* Function: esl_memstrcmp()
* Synopsis: Compare a memory line and string for equality.
*
* Purpose: Compare line <p> of length <n> to a NUL-terminated
* string <s>, and return TRUE if they are exactly
* equal: <strlen(s) == n> and <p[0..n-1] == s[0..n-1]>.
* Else, return FALSE.
*/
int
esl_memstrcmp(const char *p, esl_pos_t n, const char *s)
{
esl_pos_t pos;
if (p == NULL && n == 0 && (s == NULL || s[0] == '\0')) return TRUE;
if (!p || !s) return FALSE;
for (pos = 0; pos < n && s[pos] != '\0'; pos++)
if (p[pos] != s[pos]) return FALSE;
if (pos != n) return FALSE;
if (s[pos] != '\0') return FALSE;
return TRUE;
}
/* Function: esl_memstrpfx()
* Synopsis: Return TRUE if memory line starts with string.
*
* Purpose: Compare line <p> of length <n> to a NUL-terminated
* string <s>. Return TRUE if the prefix of <p> exactly
* matches <s> up to its NUL sentinel byte. Else,
* return FALSE.
*/
int
esl_memstrpfx(const char *p, esl_pos_t n, const char *s)
{
esl_pos_t pos;
if (!p || !s) return FALSE;
for (pos = 0; pos < n && s[pos] != '\0'; pos++)
if (p[pos] != s[pos]) return FALSE;
if (s[pos] != '\0') return FALSE;
return TRUE;
}
/* Function: esl_memstrcontains()
* Synopsis: Return TRUE if memory line matches a string.
*
* Purpose: Compare line <p> of length <n> to NUL-terminated
* string <s>. Return <TRUE> if <p> contains an exact
* match to <s> at any position.
*/
int
esl_memstrcontains(const char *p, esl_pos_t n, const char *s)
{
esl_pos_t s0, pos;
if (! p || ! s) return FALSE;
for (s0 = 0; s0 < n; s0++)
{
for (pos = 0; s0+pos < n && s[pos] != '\0'; pos++)
if (p[s0+pos] != s[pos]) break;
if (s[pos] == '\0') return TRUE;
}
return FALSE;
}
/* Function: esl_memstrdup()
* Synopsis: Duplicate a memory line as a NUL-terminated string.
*
* Purpose: Given memory line <p> of length <n>, duplicate it
* as a NUL-terminated string; return the new string
* in <*ret_s>.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation failure; now <*ret_s> is <NULL>.
*/
int
esl_memstrdup(const char *p, esl_pos_t n, char **ret_s)
{
char *s = NULL;
int status;
if (! p) { *ret_s = NULL; return eslOK; }
ESL_ALLOC(s, sizeof(char) * (n+1));
memcpy(s, p, n);
s[n] = '\0';
*ret_s = s;
return eslOK;
ERROR:
*ret_s = NULL;
return status;
}
/* Function: esl_memstrcpy()
* Synopsis: Copy a memory line as a string.
*
* Purpose: Given memory line <p> of length <n>, copy
* it to <dest> and NUL-terminate it. Caller must
* be sure that <s> is already allocated for
* at least <n+1> bytes.
*
* Returns: <eslOK> on success.
*/
int
esl_memstrcpy(const char *p, esl_pos_t n, char *dest)
{
memcpy(dest, p, n);
dest[n] = '\0';
return eslOK;
}
/* Function: esl_memtod()
* Synopsis: esl_mem equivalent to strtod().
*
* Purpose: Given a buffer <p> of length <n>, convert it to a
* double-precision floating point value, just as
* <strtod()> would do for a NUL-terminated string.
*
* Returns: <eslOK> on success, and <*ret_val> contains the
* converted value.
*
* Throws: <eslEMEM> on allocation error, and <*ret_val> is 0.
*/
int
esl_memtod(const char *p, esl_pos_t n, double *ret_val)
{
char fixedbuf[128];
char *bigbuf = NULL;
int status;
if (n < 128)
{
memcpy(fixedbuf, p, sizeof(char) * n);
fixedbuf[n] = '\0';
*ret_val = strtod(fixedbuf, NULL);
return eslOK;
}
else
{
ESL_ALLOC(bigbuf, sizeof(char) * (n+1));
memcpy(bigbuf, p, sizeof(char) * n);
bigbuf[n] = '\0';
*ret_val = strtod(fixedbuf, NULL);
free(bigbuf);
return eslOK;
}
ERROR:
*ret_val = 0.;
return status;
}
/* Function: esl_memtof()
* Synopsis: esl_mem equivalent to strtod(), for a float
*
* Purpose: Given a buffer <p> of length <n>, convert it to a
* single-precision floating point value, just as
* <strtod()> would do for a NUL-terminated string.
*
* Returns: <eslOK> on success, and <*ret_val> contains the
* converted value.
*
* Throws: <eslEMEM> on allocation error, and <*ret_val> is 0.
*/
int
esl_memtof(const char *p, esl_pos_t n, float *ret_val)
{
char fixedbuf[128];
char *bigbuf = NULL;
int status;
if (n < 128)
{
memcpy(fixedbuf, p, sizeof(char) * n);
fixedbuf[n] = '\0';
*ret_val = (float) strtod(fixedbuf, NULL);
return eslOK;
}
else
{
ESL_ALLOC(bigbuf, sizeof(char) * (n+1));
memcpy(bigbuf, p, sizeof(char) * n);
bigbuf[n] = '\0';
*ret_val = (float) strtod(fixedbuf, NULL);
free(bigbuf);
return eslOK;
}
ERROR:
*ret_val = 0.;
return status;
}
/* Function: esl_mem_IsReal()
* Synopsis: Return TRUE if <p> is a real number; else FALSE.
*
* Purpose: If the memory <p> of <n> bytes is convertible
* to a floating point real number by the rules of
* atof(), return TRUE; else return FALSE.
*
* Xref: easel.c::esl_str_IsReal() for string version.
*/
int
esl_mem_IsReal(const char *p, esl_pos_t n)
{
int gotdecimal = 0;
int gotexp = 0;
int gotreal = 0;
if (!p || !n) return FALSE;
while (n && isspace((int) *p)) { p++; n--; } /* skip leading whitespace */
if (n && (*p == '-' || *p == '+')) { p++; n--; } /* skip leading sign */
/* Examine remainder for garbage. Allowed one '.' and
* one 'e' or 'E'; if both '.' and e/E occur, '.'
* must be first.
*/
while (n)
{
if (isdigit((int) (*p))) gotreal++;
else if (*p == '.')
{
if (gotdecimal) return FALSE; /* can't have two */
if (gotexp) return FALSE; /* e/E preceded . */
else gotdecimal++;
}
else if (*p == 'e' || *p == 'E')
{
if (gotexp) return FALSE; /* can't have two */
else gotexp++;
}
else if (isspace((int) (*p))) break;
p++;
n
}
while (n && isspace((int) *p)) { p++; n--; } /* skip trailing whitespace */
return ( (n == 0 && gotreal) ? TRUE : FALSE);
}
#ifdef eslMEM_BENCHMARK
#include "esl_config.h"
#include <stdio.h>
#include "easel.h"
#include "esl_buffer.h"
#include "esl_getopts.h"
#include "esl_stopwatch.h"
static ESL_OPTIONS options[] = {
/* name type default env range togs reqs incomp help docgrp */
{"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
{ 0,0,0,0,0,0,0,0,0,0},
};
static char usage[] = "[-options] <infile>";
static char banner[] = "benchmark driver for mem module";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = <API key>(options, 1, argc, argv, banner, usage);
ESL_STOPWATCH *w = <API key>();
char *infile = esl_opt_GetArg(go, 1);
ESL_BUFFER *bf = NULL;
int64_t nlines = 0;
int64_t ntokens = 0;
int64_t nchar = 0;
char *p, *tok;
esl_pos_t n, toklen;
int status;
esl_stopwatch_Start(w);
if ( esl_buffer_Open(infile, NULL, &bf) != eslOK) esl_fatal("open failed");
while ( (status = esl_buffer_GetLine(bf, &p, &n)) == eslOK)
{
nlines++;
while ( (status = esl_memtok(&p, &n, " \t", &tok, &toklen)) == eslOK)
{
ntokens++;
nchar += toklen;
}
if (status != eslEOL) esl_fatal("memtok failure");
}
if (status != eslEOF) esl_fatal("GetLine failure");
esl_stopwatch_Stop(w);
<API key>(stdout, w, NULL);
printf("lines = %" PRId64 "\n", nlines);
printf("tokens = %" PRId64 "\n", ntokens);
printf("chars = %" PRId64 "\n", nchar);
esl_buffer_Close(bf);
<API key>(w);
esl_getopts_Destroy(go);
return 0;
}
#endif /*eslMEM_BENCHMARK*/
#ifdef eslMEM_TESTDRIVE
static void
utest_mem_strtoi32(void)
{
char msg[] = "esl_mem_strtoi32() unit test failed";
int nc;
int32_t val;
int status;
if ( (status = esl_mem_strtoi32("-1234", 5, 10, &nc, &val)) != eslOK || nc != 5 || val != -1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("\t -1234", 8, 10, &nc, &val)) != eslOK || nc != 8 || val != -1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("1234", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("12345", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 0xff", 5, 0, &nc, &val)) != eslOK || nc != 5 || val != 255) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 0777", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 63) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("FFGG", 4, 16, &nc, &val)) != eslOK || nc != 2 || val != 255) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("0xffff", 6, 0, &nc, &val)) != eslOK || nc != 6 || val != 65535) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("0xffffff", 8, 0, &nc, &val)) != eslOK || nc != 8 || val != 16777215) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 2147483647", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MAX) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("-2147483648", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MIN) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 2147483648", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("-2147483649", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 214748364800", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("-214748364900", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 0x1234", 3, 16, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("09999999", 7, 0, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg);
return;
}
static void
utest_memtok(void)
{
char msg[] = "esl_memtok() unit test failed";
char *teststring;
esl_pos_t n;
char *s;
char *tok;
esl_pos_t toklen;
if (esl_strdup("This is\t a sentence.", -1, &teststring) != eslOK) esl_fatal(msg);
s = teststring;
n = strlen(teststring);
if (esl_memtok(&s, &n, " ", &tok, &toklen) != eslOK) esl_fatal(msg);
if (toklen != 4) esl_fatal(msg);
if (memcmp(tok, "This", toklen) != 0) esl_fatal(msg);
if (*s != 'i') esl_fatal(msg);
if (esl_memtok(&s, &n, " \t", &tok, &toklen) != eslOK) esl_fatal(msg);
if (toklen != 2) esl_fatal(msg);
if (memcmp(tok, "is", toklen) != 0) esl_fatal(msg);
if (*s != 'a') esl_fatal(msg);
if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslOK) esl_fatal(msg);
if (toklen != 11) esl_fatal(msg);
if (memcmp(tok, "a sentence.", toklen) != 0) esl_fatal(msg);
if (*s != '\0') esl_fatal(msg);
if (n != 0) esl_fatal(msg);
if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslEOL) esl_fatal(msg);
if (toklen != 0) esl_fatal(msg);
if (tok != NULL) esl_fatal(msg);
free(teststring);
return;
}
/* memspn, memcspn() */
static void
<API key>(void)
{
char msg[] = "memspn/memcspn unit test failed";
char test1[] = " this is a test";
char *p;
esl_pos_t n;
p = test1;
n = 13; /* so the memory is " this is a t" */
if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg);
p = test1+2;
n = 11; /* "this is a t" */
if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg);
p = test1;
n = 2;
if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg);
p = test1+2;
n = 4;
if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg);
}
/* memstrcmp/memstrpfx */
static void
<API key>(void)
{
char msg[] = "memstrcmp/memstrpfx unit test failed";
char test[] = "this is a test";
char *p;
esl_pos_t n;
p = test;
n = strlen(p);
if (! esl_memstrcmp(p, n, test)) esl_fatal(msg);
if ( esl_memstrcmp(p, n, "this")) esl_fatal(msg);
if (! esl_memstrpfx(p, n, "this")) esl_fatal(msg);
if ( esl_memstrpfx(p, n, "that")) esl_fatal(msg);
p = test;
n = 2; /* now p is just "th" */
if (! esl_memstrcmp(p, n, "th")) esl_fatal(msg);
if ( esl_memstrcmp(p, n, test)) esl_fatal(msg);
if (! esl_memstrpfx(p, n, "th")) esl_fatal(msg);
if ( esl_memstrpfx(p, n, "this")) esl_fatal(msg);
/* special cases involving NULLs */
p = test;
n = strlen(p);
if (! esl_memstrcmp(NULL, 0, NULL)) esl_fatal(msg);
if ( esl_memstrcmp(NULL, 0, test)) esl_fatal(msg);
if ( esl_memstrcmp(p, n, NULL)) esl_fatal(msg);
if ( esl_memstrpfx(NULL, 0, NULL)) esl_fatal(msg);
if ( esl_memstrpfx(NULL, 0, "this")) esl_fatal(msg);
if ( esl_memstrpfx(p, n, NULL)) esl_fatal(msg);
}
static void
<API key>(void)
{
char msg[] = "memstrcontains unit test failed";
char test[] = "CLUSTAL W (1.83) multiple sequence alignment";
char *p;
esl_pos_t n;
p = test;
n = strlen(p);
if (! esl_memstrcontains(p, n, "multiple sequence alignment")) esl_fatal(msg);
if (! esl_memstrcontains(p, n, "CLUSTAL")) esl_fatal(msg);
if ( esl_memstrcontains(p, n, "alignmentx")) esl_fatal(msg);
}
#endif /*eslMEM_TESTDRIVE*/
#ifdef eslMEM_TESTDRIVE
#include "esl_config.h"
#include <stdio.h>
#include "easel.h"
#include "esl_mem.h"
#include "esl_getopts.h"
static ESL_OPTIONS options[] = {
/* name type default env range togs reqs incomp help docgrp */
{"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
{ 0,0,0,0,0,0,0,0,0,0},
};
static char usage[] = "[-options]";
static char banner[] = "test driver for mem module";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = <API key>(options, 0, argc, argv, banner, usage);
utest_mem_strtoi32();
utest_memtok();
<API key>();
<API key>();
<API key>();
esl_getopts_Destroy(go);
return 0;
}
#endif /* eslMEM_TESTDRIVE */
|
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/<API key>/www/device.js",
"id": "<API key>.device",
"pluginId": "<API key>",
"clobbers": [
"device"
]
},
{
"file": "plugins/<API key>/src/browser/DeviceProxy.js",
"id": "<API key>.DeviceProxy",
"pluginId": "<API key>",
"runs": true
},
{
"file": "plugins/<API key>/www/CompassError.js",
"id": "<API key>.CompassError",
"pluginId": "<API key>",
"clobbers": [
"CompassError"
]
},
{
"file": "plugins/<API key>/www/CompassHeading.js",
"id": "<API key>.CompassHeading",
"pluginId": "<API key>",
"clobbers": [
"CompassHeading"
]
},
{
"file": "plugins/<API key>/www/compass.js",
"id": "<API key>.compass",
"pluginId": "<API key>",
"clobbers": [
"navigator.compass"
]
},
{
"file": "plugins/<API key>/src/browser/CompassProxy.js",
"id": "<API key>.CompassProxy",
"pluginId": "<API key>",
"runs": true
},
{
"file": "plugins/<API key>/www/notification.js",
"id": "<API key>.notification",
"pluginId": "<API key>",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/<API key>/www/browser/notification.js",
"id": "<API key>.<API key>",
"pluginId": "<API key>",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/<API key>/www/network.js",
"id": "<API key>.network",
"pluginId": "<API key>",
"clobbers": [
"navigator.connection",
"navigator.network.connection"
]
},
{
"file": "plugins/<API key>/www/Connection.js",
"id": "<API key>.Connection",
"pluginId": "<API key>",
"clobbers": [
"Connection"
]
},
{
"file": "plugins/<API key>/src/browser/network.js",
"id": "<API key>.NetworkInfoProxy",
"pluginId": "<API key>",
"runs": true
},
{
"file": "plugins/<API key>/www/splashscreen.js",
"id": "<API key>.SplashScreen",
"pluginId": "<API key>",
"clobbers": [
"navigator.splashscreen"
]
},
{
"file": "plugins/<API key>/src/browser/SplashScreenProxy.js",
"id": "<API key>.SplashScreenProxy",
"pluginId": "<API key>",
"runs": true
},
{
"file": "plugins/<API key>/www/statusbar.js",
"id": "<API key>.statusbar",
"pluginId": "<API key>",
"clobbers": [
"window.StatusBar"
]
},
{
"file": "plugins/<API key>/src/browser/statusbar.js",
"id": "<API key>.statusbar.Browser",
"pluginId": "<API key>",
"merges": [
"window.StatusBar"
]
},
{
"file": "plugins/<API key>/www/<API key>.js",
"id": "<API key>.<API key>",
"pluginId": "<API key>",
"clobbers": [
"window.MobileAccessibility"
]
},
{
"file": "plugins/<API key>/www/<API key>.js",
"id": "<API key>.<API key>",
"pluginId": "<API key>",
"clobbers": [
"<API key>"
]
},
{
"file": "plugins/<API key>/www/Acceleration.js",
"id": "<API key>.Acceleration",
"pluginId": "<API key>",
"clobbers": [
"Acceleration"
]
},
{
"file": "plugins/<API key>/www/accelerometer.js",
"id": "<API key>.accelerometer",
"pluginId": "<API key>",
"clobbers": [
"navigator.accelerometer"
]
},
{
"file": "plugins/<API key>/src/browser/AccelerometerProxy.js",
"id": "<API key>.AccelerometerProxy",
"pluginId": "<API key>",
"runs": true
},
{
"file": "plugins/<API key>/www/GlobalizationError.js",
"id": "<API key>.GlobalizationError",
"pluginId": "<API key>",
"clobbers": [
"window.GlobalizationError"
]
},
{
"file": "plugins/<API key>/www/globalization.js",
"id": "<API key>.globalization",
"pluginId": "<API key>",
"clobbers": [
"navigator.globalization"
]
},
{
"file": "plugins/<API key>/www/browser/moment.js",
"id": "<API key>.moment",
"pluginId": "<API key>",
"runs": true
},
{
"file": "plugins/<API key>/src/browser/GlobalizationProxy.js",
"id": "<API key>.GlobalizationProxy",
"pluginId": "<API key>",
"runs": true
},
{
"file": "plugins/<API key>/www/inappbrowser.js",
"id": "<API key>.inappbrowser",
"pluginId": "<API key>",
"clobbers": [
"cordova.InAppBrowser.open",
"window.open"
]
},
{
"file": "plugins/<API key>/src/browser/InAppBrowserProxy.js",
"id": "<API key>.InAppBrowserProxy",
"pluginId": "<API key>",
"merges": [
""
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"id": "cordova-plugin-file.DirectoryEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"id": "cordova-plugin-file.DirectoryReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/Entry.js",
"id": "cordova-plugin-file.Entry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"file": "plugins/cordova-plugin-file/www/File.js",
"id": "cordova-plugin-file.File",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"id": "cordova-plugin-file.FileEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileError.js",
"id": "cordova-plugin-file.FileError",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"id": "cordova-plugin-file.FileReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"id": "cordova-plugin-file.FileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"id": "cordova-plugin-file.FileUploadOptions",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"id": "cordova-plugin-file.FileUploadResult",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"id": "cordova-plugin-file.FileWriter",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"file": "plugins/cordova-plugin-file/www/Flags.js",
"id": "cordova-plugin-file.Flags",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"id": "cordova-plugin-file.LocalFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"id": "cordova-plugin-file.Metadata",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"id": "cordova-plugin-file.ProgressEvent",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"id": "cordova-plugin-file.fileSystems",
"pluginId": "cordova-plugin-file"
},
{
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"id": "cordova-plugin-file.requestFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/<API key>.js",
"id": "cordova-plugin-file.<API key>",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"id": "cordova-plugin-file.isChrome",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/Preparing.js",
"id": "cordova-plugin-file.Preparing",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/src/browser/FileProxy.js",
"id": "cordova-plugin-file.browserFileProxy",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"id": "cordova-plugin-file.fileSystemPaths",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/FileSystem.js",
"id": "cordova-plugin-file.firefoxFileSystem",
"pluginId": "cordova-plugin-file",
"merges": [
"window.FileSystem"
]
},
{
"file": "plugins/<API key>/www/MediaError.js",
"id": "<API key>.MediaError",
"pluginId": "<API key>",
"clobbers": [
"window.MediaError"
]
},
{
"file": "plugins/<API key>/www/Media.js",
"id": "<API key>.Media",
"pluginId": "<API key>",
"clobbers": [
"window.Media"
]
},
{
"file": "plugins/<API key>/www/browser/Media.js",
"id": "<API key>.BrowserMedia",
"pluginId": "<API key>",
"clobbers": [
"window.Media"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"<API key>": "1.0.5",
"<API key>": "1.1.4",
"<API key>": "1.0.5",
"<API key>": "1.2.1",
"<API key>": "1.2.1",
"<API key>": "3.2.2",
"<API key>": "2.1.3",
"<API key>": "1.2.2",
"<API key>": "1.0.5-dev",
"<API key>": "1.2.4",
"<API key>": "1.0.6",
"<API key>": "1.3.0",
"<API key>": "1.1.0",
"cordova-plugin-file": "4.3.2",
"<API key>": "2.2.0"
}
// BOTTOM OF METADATA
});
|
<?php
// Controller for latestdeaths.
class Deaths extends Controller {
public function index() {
require("config.php");
$this->load->database();
if(@$_REQUEST['world'] == 0)
$world = 0;
else
$world = (int)@$_REQUEST['world'];
$world_name = ($config['worlds'] == $world);
$players_deaths = $this->db->query('SELECT `player_deaths`.`id`, `player_deaths`.`date`, `player_deaths`.`level`, `players`.`name`, `players`.`world_id` FROM `player_deaths` LEFT JOIN `players` ON `player_deaths`.`player_id` = `players`.`id` ORDER BY `date` DESC LIMIT 0,'.$config['latestdeathlimit'])->result();
if (!empty($players_deaths))
{
foreach ($players_deaths as $death)
{
$sql = $this->db->query('SELECT environment_killers.name AS monster_name, players.name AS player_name, players.deleted AS player_exists FROM killers LEFT JOIN environment_killers ON killers.id = environment_killers.kill_id LEFT JOIN player_killers ON killers.id = player_killers.kill_id LEFT JOIN players ON players.id = player_killers.player_id WHERE killers.death_id = '.$death->id.' ORDER BY killers.final_hit DESC, killers.id ASC')->result();
$players_rows = '<td><a href="?subtopic=characters&name='.urlencode($death->name).'"><b>'.$death->name.'</b></a> ';
$i = 0;
$count = count($death);
foreach($sql as $deaths)
{
$i++;
if($deaths->player_name != "")
{
if($i == 1)
$players_rows .= "killed at level <b>".$death->level."</b>";
else if($i == $count)
$players_rows .= " and";
else
$players_rows .= ",";
$players_rows .= " by ";
if($deaths->monster_name != "")
$players_rows .= $deaths->monster_name." summoned by ";
if($deaths->player_exists == 0)
$players_rows .= "<a href=\"index.php?subtopic=characters&name=".urlencode($deaths->player_name)."\">";
$players_rows .= $deaths->player_name;
if($deaths->player_exists == 0)
$players_rows .= "</a>";
}
else
{
if($i == 1)
$players_rows .= "died at level <b>".$death->level."</b>";
else if($i == $count)
$players_rows .= " and";
else
$players_rows .= ",";
$players_rows .= " by ".$deaths->monster_name;
}
$players_rows .= "</td>";
$data['deaths'][] = array('players_rows'=>$players_rows,'date'=>$death->date,'name'=>$death->name,'player_name'=>$deaths->player_name,'monster_name'=>$deaths->monster_name,'player_exists'=>$deaths->player_exists);
$players_rows = "";
}
}
$this->load->helper("form");
$this->load->view("deaths", $data);
}
else
{
echo "<h1>There are no players killed yet.</h1>";
}
}
}
?>
|
#!/bin/bash
# flashx.tv module
# This file is part of Plowshare.
# Plowshare is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Plowshare is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<API key>='http://\(www\.\)\?flashx\.tv/'
<API key>=""
<API key>=yes
<API key>=no
<API key>=
<API key>=
<API key>=""
# Output a flashx file download URL
# $1: cookie file
# $2: flashx url
# stdout: real file download link
flashx_download() {
local -r COOKIE_FILE=$1
local -r URL=$2
local PAGE CONFIG_URL EMBED_URL FILE_NAME FILE_URL
PAGE=$(curl -c "$COOKIE_FILE" --location "$URL") || return
if match 'Video not found, deleted, abused or wrong link\|Video not found, deleted or abused, sorry!' \
"$PAGE"; then
return $ERR_LINK_DEAD
fi
if match '<h2>404 Error</h2>' "$PAGE"; then
return $ERR_LINK_DEAD
fi
FILE_NAME=$(parse_tag '<div class=.video_title' 'div' <<< "$PAGE" | html_to_utf8) || return
# On main page
EMBED_URL=$(echo "$PAGE" | parse '<div class="<API key>"' 'src="\([^"]*\)' 1) || return
PAGE=$(curl -b "$COOKIE_FILE" "$EMBED_URL") || return
# Inside iframe embed on main page
local FORM_HTML FORM_URL FORM_HASH FORM_SEC_HASH
FORM_HTML=$(grep_form_by_name "$PAGE" 'fxplayit') || return
FORM_URL=$(echo "$FORM_HTML" | parse_form_action) || return
FORM_HASH=$(echo "$FORM_HTML" | <API key> 'hash') || return
FORM_SEC_HASH=$(echo "$FORM_HTML" | <API key> 'sechash') || return
PAGE=$(curl -b "$COOKIE_FILE" \
--referer "$EMBED_URL" \
--data "hash=$FORM_HASH" \
--data "sechash=$FORM_SEC_HASH" \
--header "Cookie: refid=; vr_referrer=" \
"$(basename_url "$EMBED_URL")/player/$FORM_URL") || return
# Player's response
CONFIG_URL=$(echo "$PAGE" | parse '<param name="movie"' 'config=\([^"]*\)') || return
PAGE=$(curl -b "$COOKIE_FILE" --location "$CONFIG_URL") || return
# XML config file
FILE_URL=$(parse_tag 'file' <<< "$PAGE") || return
echo "$FILE_URL"
echo "$FILE_NAME"
}
# Probe a download URL
# $1: cookie file (unused here)
# $2: flashx.tv url
# $3: requested capability list
# stdout: 1 capability per line
flashx_probe() {
local -r URL=$2
local -r REQ_IN=$3
local PAGE REQ_OUT FILE_NAME
PAGE=$(curl --location "$URL") || return
if match 'Video not found, deleted, abused or wrong link\|Video not found, deleted or abused, sorry!' \
"$PAGE"; then
return $ERR_LINK_DEAD
fi
if match '<h2>404 Error</h2>' "$PAGE"; then
return $ERR_LINK_DEAD
fi
REQ_OUT=c
if [[ $REQ_IN = *f* ]]; then
FILE_NAME=$(parse_tag '<div class="video_title"' 'div' <<< "$PAGE" | html_to_utf8) && \
echo "$FILE_NAME" && REQ_OUT="${REQ_OUT}f"
fi
echo $REQ_OUT
}
|
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from typing import Any, Dict, Set
from snapcraft import project
from snapcraft.internal.project_loader import grammar
from snapcraft.internal import pluginhandler, repo
from .<API key> import package_transformer
class <API key>:
"""Process part properties that support grammar.
Stage packages example:
from unittest import mock
import snapcraft
# Pretend that all packages are valid
repo = mock.Mock()
repo.is_valid.return_value = True
plugin = mock.Mock()
plugin.stage_packages = [{'try': ['foo']}]
processor = <API key>(
plugin=plugin,
properties={},
project=snapcraft.project.Project(),
repo=repo)
processor.get_stage_packages()
{'foo'}
Build packages example:
from unittest import mock
import snapcraft
# Pretend that all packages are valid
repo = mock.Mock()
repo.is_valid.return_value = True
plugin = mock.Mock()
plugin.build_packages = [{'try': ['foo']}]
processor = <API key>(
plugin=plugin,
properties={},
project=snapcraft.project.Project(),
repo=repo)
processor.get_build_packages()
{'foo'}
Source example:
from unittest import mock
import snapcraft
plugin = mock.Mock()
plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']}
processor = <API key>(
plugin=plugin,
properties=plugin.properties,
project=snapcraft.project.Project(),
repo=None)
processor.get_source()
'foo'
"""
def __init__(
self,
*,
plugin: pluginhandler.PluginHandler,
properties: Dict[str, Any],
project: project.Project,
repo: "repo.Ubuntu"
) -> None:
self._project = project
self._repo = repo
self._build_snap_grammar = getattr(plugin, "build_snaps", [])
self.__build_snaps = set() # type: Set[str]
self.<API key> = getattr(plugin, "build_packages", [])
self.__build_packages = set() # type: Set[str]
self.<API key> = getattr(plugin, "stage_packages", [])
self.__stage_packages = set() # type: Set[str]
source_grammar = properties.get("source", [""])
if not isinstance(source_grammar, list):
self._source_grammar = [source_grammar]
else:
self._source_grammar = source_grammar
self.__source = ""
def get_source(self) -> str:
if not self.__source:
# The grammar is array-based, even though we only support a single
# source.
processor = grammar.GrammarProcessor(
self._source_grammar, self._project, lambda s: True
)
source_array = processor.process()
if len(source_array) > 0:
self.__source = source_array.pop()
return self.__source
def get_build_snaps(self) -> Set[str]:
if not self.__build_snaps:
processor = grammar.GrammarProcessor(
self._build_snap_grammar,
self._project,
repo.snaps.SnapPackage.is_valid_snap,
)
self.__build_snaps = processor.process()
return self.__build_snaps
def get_build_packages(self) -> Set[str]:
if not self.__build_packages:
processor = grammar.GrammarProcessor(
self.<API key>,
self._project,
self._repo.<API key>,
transformer=package_transformer,
)
self.__build_packages = processor.process()
return self.__build_packages
def get_stage_packages(self) -> Set[str]:
if not self.__stage_packages:
processor = grammar.GrammarProcessor(
self.<API key>,
self._project,
self._repo.is_valid,
transformer=package_transformer,
)
self.__stage_packages = processor.process()
return self.__stage_packages
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# import frappe
import unittest
class <API key>(unittest.TestCase):
pass
|
#include <cmath>
#include <cfloat> // DBL_MAX
#include "Action_GIST.h"
#include "CpptrajStdio.h"
#include "Constants.h"
#include "DataSet_MatrixFlt.h"
#include "DataSet_GridFlt.h"
#include "DataSet_GridDbl.h"
#include "ProgressBar.h"
#include "StringRoutines.h"
#include "DistRoutines.h"
#ifdef _OPENMP
# include <omp.h>
#endif
const double Action_GIST::maxD_ = DBL_MAX;
Action_GIST::Action_GIST() :
debug_(0),
numthreads_(1),
#ifdef CUDA
numberAtoms_(0),
numberAtomTypes_(0),
headAtomType_(0),
solvent_(NULL),
NBindex_c_(NULL),
molecule_c_(NULL),
paramsLJ_c_(NULL),
max_c_(NULL),
min_c_(NULL),
result_w_c_(NULL),
result_s_c_(NULL),
result_O_c_(NULL),
result_N_c_(NULL),
#endif
gridspacing_(0),
gridcntr_(0.0),
griddim_(0.0),
gO_(0),
gH_(0),
Esw_(0),
Eww_(0),
dTStrans_(0),
dTSorient_(0),
dTSsix_(0),
neighbor_norm_(0),
dipole_(0),
order_norm_(0),
dipolex_(0),
dipoley_(0),
dipolez_(0),
PME_(0),
U_PME_(0),
ww_Eij_(0),
G_max_(0.0),
CurrentParm_(0),
datafile_(0),
eijfile_(0),
infofile_(0),
fltFmt_(TextFormat::GDOUBLE),
intFmt_(TextFormat::INTEGER),
BULK_DENS_(0.0),
temperature_(0.0),
NeighborCut2_(12.25), // 3.5^2
// <API key>(0),
// <API key>(0),
MAX_GRID_PT_(0),
NSOLVENT_(0),
N_ON_GRID_(0),
nMolAtoms_(0),
NFRAME_(0),
max_nwat_(0),
doOrder_(false),
doEij_(false),
skipE_(false),
includeIons_(true)
{}
/** GIST help */
void Action_GIST::Help() const {
mprintf("\t[doorder] [doeij] [skipE] [skipS] [refdens <rdval>] [temp <tval>]\n"
"\t[noimage] [gridcntr <xval> <yval> <zval>] [excludeions]\n"
"\t[griddim <nx> <ny> <nz>] [gridspacn <spaceval>] [neighborcut <ncut>]\n"
"\t[prefix <filename prefix>] [ext <grid extension>] [out <output suffix>]\n"
"\t[floatfmt {double|scientific|general}] [floatwidth <fw>] [floatprec <fp>]\n"
"\t[intwidth <iw>]\n"
"\t[info <info suffix>]\n");
# ifdef LIBPME
mprintf("\t[nopme|pme %s\n\t %s\n\t %s]\n", EwaldOptions::KeywordsCommon1(), EwaldOptions::KeywordsCommon2(), EwaldOptions::KeywordsPME());
# endif
mprintf("Perform Grid Inhomogenous Solvation Theory calculation.\n"
#ifdef CUDA
"The option doeij is not available, when using the CUDA accelerated version,\n"
"as this would need way too much memory."
#endif
);
}
/** Init GIST action. */
Action::RetType Action_GIST::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
debug_ = debugIn;
# ifdef MPI
if (init.TrajComm().Size() > 1) {
mprinterr("Error: 'gist' action does not work with > 1 process (%i processes currently).\n",
init.TrajComm().Size());
return Action::ERR;
}
# endif
gist_init_.Start();
prefix_ = actionArgs.GetStringKey("prefix");
if (prefix_.empty()) prefix_.assign("gist");
std::string ext = actionArgs.GetStringKey("ext");
if (ext.empty()) ext.assign(".dx");
std::string gistout = actionArgs.GetStringKey("out");
if (gistout.empty()) gistout.assign(prefix_ + "-output.dat");
datafile_ = init.DFL().AddCpptrajFile( gistout, "GIST output" );
if (datafile_ == 0) return Action::ERR;
// Info file: if not specified use STDOUT
gistout = actionArgs.GetStringKey("info");
if (!gistout.empty()) gistout = prefix_ + "-" + gistout;
infofile_ = init.DFL().AddCpptrajFile( gistout, "GIST info", DataFileList::TEXT, true );
if (infofile_ == 0) return Action::ERR;
// Grid files
DataFile* file_gO = init.DFL().AddDataFile( prefix_ + "-gO" + ext );
DataFile* file_gH = init.DFL().AddDataFile( prefix_ + "-gH" + ext );
DataFile* file_Esw = init.DFL().AddDataFile(prefix_ + "-Esw-dens" + ext);
DataFile* file_Eww = init.DFL().AddDataFile(prefix_ + "-Eww-dens" + ext);
DataFile* file_dTStrans = init.DFL().AddDataFile(prefix_ + "-dTStrans-dens" + ext);
DataFile* file_dTSorient = init.DFL().AddDataFile(prefix_ + "-dTSorient-dens" + ext);
DataFile* file_dTSsix = init.DFL().AddDataFile(prefix_ + "-dTSsix-dens" + ext);
DataFile* file_neighbor_norm = init.DFL().AddDataFile(prefix_ + "-neighbor-norm" + ext);
DataFile* file_dipole = init.DFL().AddDataFile(prefix_ + "-dipole-dens" + ext);
DataFile* file_order_norm = init.DFL().AddDataFile(prefix_ + "-order-norm" + ext);
DataFile* file_dipolex = init.DFL().AddDataFile(prefix_ + "-dipolex-dens" + ext);
DataFile* file_dipoley = init.DFL().AddDataFile(prefix_ + "-dipoley-dens" + ext);
DataFile* file_dipolez = init.DFL().AddDataFile(prefix_ + "-dipolez-dens" + ext);
// Output format keywords
std::string floatfmt = actionArgs.GetStringKey("floatfmt");
if (!floatfmt.empty()) {
if (floatfmt == "double")
fltFmt_.SetFormatType(TextFormat::DOUBLE);
else if (floatfmt == "scientific")
fltFmt_.SetFormatType(TextFormat::SCIENTIFIC);
else if (floatfmt == "general")
fltFmt_.SetFormatType(TextFormat::GDOUBLE);
else {
mprinterr("Error: Unrecognized format type for 'floatfmt': %s\n", floatfmt.c_str());
return Action::ERR;
}
}
fltFmt_.<API key>( actionArgs.getKeyInt("floatwidth", 0),
actionArgs.getKeyInt("floatprec", -1) );
intFmt_.SetFormatWidth( actionArgs.getKeyInt("intwidth", 0) );
// Other keywords
double neighborCut = actionArgs.getKeyDouble("neighborcut", 3.5);
NeighborCut2_ = neighborCut * neighborCut;
includeIons_ = !actionArgs.hasKey("excludeions");
imageOpt_.InitImaging( !(actionArgs.hasKey("noimage")), actionArgs.hasKey("nonortho") );
doOrder_ = actionArgs.hasKey("doorder");
doEij_ = actionArgs.hasKey("doeij");
#ifdef CUDA
if (this->doEij_) {
mprinterr("Error: 'doeij' cannot be specified when using CUDA.\n");
return Action::ERR;
}
#endif
skipE_ = actionArgs.hasKey("skipE");
if (skipE_) {
if (doEij_) {
mprinterr("Error: 'doeij' cannot be specified if 'skipE' is specified.\n");
return Action::ERR;
}
}
// Parse PME options
// TODO once PME output is stable, make pme true the default when LIBPME present.
//# ifdef LIBPME
// usePme_ = true;
//# else
usePme_ = false;
//# endif
# ifdef CUDA
// Disable PME for CUDA
usePme_ = false;
# endif
if (actionArgs.hasKey("pme"))
usePme_ = true;
else if (actionArgs.hasKey("nopme"))
usePme_ = false;
// PME and doeij are not compatible
if (usePme_ && doEij_) {
mprinterr("Error: 'doeij' cannot be used with PME. Specify 'nopme' to use 'doeij'\n");
return Action::ERR;
}
if (usePme_) {
# ifdef LIBPME
pmeOpts_.AllowLjPme(false);
if (pmeOpts_.GetOptions(EwaldOptions::PME, actionArgs, "GIST")) {
mprinterr("Error: Getting PME options for GIST failed.\n");
return Action::ERR;
}
# else
mprinterr("Error: 'pme' with GIST requires compilation with LIBPME.\n");
return Action::ERR;
# endif
}
DataFile* file_energy_pme = 0;
DataFile* file_U_energy_pme = 0;
if (usePme_) {
file_energy_pme = init.DFL().AddDataFile(prefix_ + "-Water-Etot-pme-dens" + ext);
file_U_energy_pme = init.DFL().AddDataFile(prefix_ + "-<API key>"+ ext);
}
this->skipS_ = actionArgs.hasKey("skipS");
if (doEij_) {
eijfile_ = init.DFL().AddCpptrajFile(prefix_ + "-Eww_ij.dat", "GIST Eij matrix file");
if (eijfile_ == 0) return Action::ERR;
}
// Set Bulk Density 55.5M
BULK_DENS_ = actionArgs.getKeyDouble("refdens", 0.0334);
if ( BULK_DENS_ > (0.0334*1.2) )
mprintf("Warning: water reference density is high, consider using 0.0334 for 1g/cc water density\n");
else if ( BULK_DENS_ < (0.0334*0.8) )
mprintf("Warning: water reference density is low, consider using 0.0334 for 1g/cc water density\n");
temperature_ = actionArgs.getKeyDouble("temp", 300.0);
if (temperature_ < 0.0) {
mprinterr("Error: Negative temperature specified.\n");
return Action::ERR;
}
// Grid spacing
gridspacing_ = actionArgs.getKeyDouble("gridspacn", 0.50);
// Grid center
gridcntr_ = Vec3(0.0);
if ( actionArgs.hasKey("gridcntr") ) {
gridcntr_[0] = actionArgs.getNextDouble(-1);
gridcntr_[1] = actionArgs.getNextDouble(-1);
gridcntr_[2] = actionArgs.getNextDouble(-1);
} else
mprintf("Warning: No grid center values specified, using default (origin)\n");
// Grid dimensions
int nx = 40;
int ny = 40;
int nz = 40;
if ( actionArgs.hasKey("griddim") ) {
nx = actionArgs.getNextInteger(-1);
ny = actionArgs.getNextInteger(-1);
nz = actionArgs.getNextInteger(-1);
} else
mprintf("Warning: No grid dimension values specified, using default (40,40,40)\n");
griddim_ = Vec3((double)nx, (double)ny, (double)nz);
// Data set name
std::string dsname = actionArgs.GetStringKey("name");
if (dsname.empty())
dsname = init.DSL().GenerateDefaultName("GIST");
// Set up DataSets.
gO_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gO"));
gH_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gH"));
Esw_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Esw"));
Eww_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Eww"));
dTStrans_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTStrans"));
dTSorient_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSorient"));
dTSsix_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSsix"));
neighbor_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "neighbor"));
dipole_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dipole"));
order_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "order"));
dipolex_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolex"));
dipoley_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipoley"));
dipolez_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolez"));
if (gO_==0 || gH_==0 || Esw_==0 || Eww_==0 || dTStrans_==0 || dTSorient_==0 ||
dTSsix_==0 || neighbor_norm_==0 || dipole_==0 || order_norm_==0 ||
dipolex_==0 || dipoley_==0 || dipolez_==0)
return Action::ERR;
if (usePme_) {
PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname,"PME"));
U_PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT,MetaData(dsname,"U_PME"));
if (PME_ == 0 || U_PME_ == 0) return Action::ERR;
}
if (doEij_) {
ww_Eij_ = (DataSet_MatrixFlt*)init.DSL().AddSet(DataSet::MATRIX_FLT, MetaData(dsname, "Eij"));
if (ww_Eij_ == 0) return Action::ERR;
}
// Allocate DataSets. TODO non-orthogonal grids as well
Vec3 v_spacing( gridspacing_ );
gO_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
MAX_GRID_PT_ = gO_->Size();
gH_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
Esw_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
Eww_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTStrans_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTSorient_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTSsix_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
neighbor_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipole_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
order_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipolex_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipoley_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipolez_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
if (usePme_) {
PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing);
U_PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing);
}
if (ww_Eij_ != 0) {
if (ww_Eij_->AllocateTriangle( MAX_GRID_PT_ )) {
mprinterr("Error: Could not allocate memory for water-water Eij matrix.\n");
return Action::ERR;
}
}
// Add sets to files
file_gO->AddDataSet( gO_ );
file_gH->AddDataSet( gH_ );
file_Esw->AddDataSet( Esw_ );
file_Eww->AddDataSet( Eww_ );
file_dTStrans->AddDataSet( dTStrans_ );
file_dTSorient->AddDataSet( dTSorient_ );
file_dTSsix->AddDataSet( dTSsix_ );
file_neighbor_norm->AddDataSet( neighbor_norm_ );
file_dipole->AddDataSet( dipole_ );
file_order_norm->AddDataSet( order_norm_ );
file_dipolex->AddDataSet( dipolex_ );
file_dipoley->AddDataSet( dipoley_ );
file_dipolez->AddDataSet( dipolez_ );
if (usePme_) {
file_energy_pme->AddDataSet(PME_);
file_U_energy_pme->AddDataSet(U_PME_);
}
// Set up grid params TODO non-orthogonal as well
G_max_ = Vec3( (double)nx * gridspacing_ + 1.5,
(double)ny * gridspacing_ + 1.5,
(double)nz * gridspacing_ + 1.5 );
N_waters_.assign( MAX_GRID_PT_, 0 );
N_solute_atoms_.assign( MAX_GRID_PT_, 0);
N_hydrogens_.assign( MAX_GRID_PT_, 0 );
voxel_xyz_.resize( MAX_GRID_PT_ ); // [] = X Y Z
voxel_Q_.resize( MAX_GRID_PT_ ); // [] = W4 X4 Y4 Z4
numthreads_ = 1;
# ifdef _OPENMP
# pragma omp parallel
{
if (omp_get_thread_num() == 0)
numthreads_ = omp_get_num_threads();
}
# endif
if (!skipE_) {
E_UV_VDW_.resize( numthreads_ );
E_UV_Elec_.resize( numthreads_ );
E_VV_VDW_.resize( numthreads_ );
E_VV_Elec_.resize( numthreads_ );
neighbor_.resize( numthreads_ );
for (int thread = 0; thread != numthreads_; thread++) {
E_UV_VDW_[thread].assign( MAX_GRID_PT_, 0 );
E_UV_Elec_[thread].assign( MAX_GRID_PT_, 0 );
E_VV_VDW_[thread].assign( MAX_GRID_PT_, 0 );
E_VV_Elec_[thread].assign( MAX_GRID_PT_, 0 );
neighbor_[thread].assign( MAX_GRID_PT_, 0 );
}
if (usePme_) {
E_pme_.assign( MAX_GRID_PT_, 0 );
U_E_pme_.assign( MAX_GRID_PT_, 0 );
//E_pme_.resize( numthreads_);
//U_E_pme_.resize(numthreads_);
//for (int thread = 0; thread != numthreads_; thread++) {
// E_pme_[thread].assign( MAX_GRID_PT_,0);
// U_E_pme_[thread].assign( MAX_GRID_PT_,0);
}
# ifdef _OPENMP
if (doEij_) {
// Since allocating a separate matrix for every thread will consume a lot
// of memory and since the Eij matrices tend to be sparse since solute is
// often present, each thread will record any interaction energies they
// calculate separately and add to the Eij matrix afterwards to avoid
// memory clashes. Probably not ideal if the bulk of the grid is water however.
EIJ_V1_.resize( numthreads_ );
EIJ_V2_.resize( numthreads_ );
EIJ_EN_.resize( numthreads_ );
}
# endif
#ifdef CUDA
if (this->skipE_ && this->doOrder_) {
mprintf("When the keyword \"skipE\" is supplied, \"doorder\" cannot be"
" chosen, as both calculations are done on the GPU at the same"
" time.\nIgnoring \"doorder!\"\n");
}
#endif
}
//Box gbox;
//gbox.SetBetaLengths( 90.0, (double)nx * gridspacing_,
// (double)ny * gridspacing_,
// (double)nz * gridspacing_ );
//grid_.Setup_O_Box( nx, ny, nz, gO_->GridOrigin(), gbox );
//grid_.Setup_O_D( nx, ny, nz, gO_->GridOrigin(), v_spacing );
mprintf(" GIST:\n");
mprintf("\tOutput prefix= '%s', grid output extension= '%s'\n", prefix_.c_str(), ext.c_str());
mprintf("\tOutput float format string= '%s', output integer format string= '%s'\n", fltFmt_.fmt(), intFmt_.fmt());
mprintf("\tGIST info written to '%s'\n", infofile_->Filename().full());
mprintf("\tName for data sets: %s\n", dsname.c_str());
if (doOrder_)
mprintf("\tDoing order calculation.\n");
else
mprintf("\tSkipping order calculation.\n");
if (skipE_)
mprintf("\tSkipping energy calculation.\n");
else {
mprintf("\tPerforming energy calculation.\n");
if (numthreads_ > 1)
mprintf("\tParallelizing energy calculation with %i threads.\n", numthreads_);
if (usePme_) {
mprintf("\tUsing PME.\n");
pmeOpts_.PrintOptions();
}
}
mprintf("\tCut off for determining solvent O-O neighbors is %f Ang\n", sqrt(NeighborCut2_));
if (includeIons_)
mprintf("\tIons will be included in the solute region.\n");
else
mprintf("\tIons will be excluded from the calculation.\n");
if (doEij_) {
mprintf("\tComputing and printing water-water Eij matrix, output to '%s'\n",
eijfile_->Filename().full());
mprintf("\tWater-water Eij matrix size is %s\n",
ByteString(ww_Eij_->MemUsageInBytes(), BYTE_DECIMAL).c_str());
} else
mprintf("\tSkipping water-water Eij matrix.\n");
mprintf("\tWater reference density: %6.4f molecules/Ang^3\n", BULK_DENS_);
mprintf("\tSimulation temperature: %6.4f K\n", temperature_);
if (imageOpt_.UseImage())
mprintf("\tDistances will be imaged.\n");
else
mprintf("\tDistances will not be imaged.\n");
if (imageOpt_.ForceNonOrtho())
mprintf("\tWill use non-orthogonal imaging routines for all cell types.\n");
gO_->GridInfo();
mprintf("\tNumber of voxels: %u, voxel volume: %f Ang^3\n",
MAX_GRID_PT_, gO_->Bin().VoxelVolume());
mprintf("#Please cite these papers if you use GIST results in a publication:\n"
"# Steven Ramsey, Crystal Nguyen, Romelia Salomon-Ferrer, Ross C. Walker, Michael K. Gilson, and Tom Kurtzman. J. Comp. Chem. 37 (21) 2016\n"
"# Crystal Nguyen, Michael K. Gilson, and Tom Young, arXiv:1108.4876v1 (2011)\n"
"# Crystal N. Nguyen, Tom Kurtzman Young, and Michael K. Gilson,\n"
"# J. Chem. Phys. 137, 044101 (2012)\n"
"
#ifdef LIBPME
"#When using the PME-enhanced version of GIST, please cite:\n"
"# Lieyang Chen, Anthony Cruz, Daniel R. Roe, Andy C. Simmonett, Lauren Wickstrom, Nanjie Deng, Tom Kurtzman. JCTC (2021) DOI: 10.1021/acs.jctc.0c01185\n"
#endif
#ifdef CUDA
"#When using the GPU parallelized version of GIST, please cite:\n"
"# Johannes Kraml, Anna S. Kamenik, Franz Waibl, Michael Schauperl, Klaus R. Liedl, JCTC (2019)\n"
#endif
);
# ifdef <API key>
mprintf("DEBUG: Using regular non-orthogonal distance routine.\n");
# endif
gist_init_.Stop();
return Action::OK;
}
\return True if given floating point values are not equal within a tolerance
static inline bool NotEqual(double v1, double v2) { return ( fabs(v1 - v2) > Constants::SMALL ); }
/** Set up GIST action. */
Action::RetType Action_GIST::Setup(ActionSetup& setup) {
gist_setup_.Start();
CurrentParm_ = setup.TopAddress();
// We need box info
if (!setup.CoordInfo().TrajBox().HasBox()) {
mprinterr("Error: Must have explicit solvent with periodic boundaries!");
return Action::ERR;
}
imageOpt_.SetupImaging( setup.CoordInfo().TrajBox().HasBox() );
#ifdef CUDA
this->numberAtoms_ = setup.Top().Natom();
this->solvent_ = new bool[this->numberAtoms_];
#endif
// Initialize PME
if (usePme_) {
# ifdef LIBPME
if (gistPme_.Init( setup.CoordInfo().TrajBox(), pmeOpts_, debug_ )) {
mprinterr("Error: GIST PME init failed.\n");
return Action::ERR;
}
// By default all atoms are selected for GIST PME to match up with atom_voxel_ array.
if (gistPme_.Setup_PME_GIST( setup.Top(), numthreads_, NeighborCut2_ )) {
mprinterr("Error: GIST PME setup/array allocation failed.\n");
return Action::ERR;
}
# else
mprinterr("Error: GIST PME requires compilation with LIBPME.\n");
return Action::ERR;
# endif
}
// Get molecule number for each solvent molecule
//mol_nums_.clear();
O_idxs_.clear();
A_idxs_.clear();
atom_voxel_.clear();
atomIsSolute_.clear();
atomIsSolventO_.clear();
U_idxs_.clear();
// NOTE: these are just guesses
O_idxs_.reserve( setup.Top().Nsolvent() );
A_idxs_.reserve( setup.Top().Natom() );
// atom_voxel_ and atomIsSolute will be indexed by atom
atom_voxel_.assign( setup.Top().Natom(), OFF_GRID_ );
atomIsSolute_.assign(setup.Top().Natom(), false);
atomIsSolventO_.assign(setup.Top().Natom(), false);
U_idxs_.reserve(setup.Top().Natom()-setup.Top().Nsolvent()*nMolAtoms_);
unsigned int midx = 0;
unsigned int NsolventAtoms = 0;
unsigned int NsoluteAtoms = 0;
bool isFirstSolvent = true;
for (Topology::mol_iterator mol = setup.Top().MolStart();
mol != setup.Top().MolEnd(); ++mol, ++midx)
{
if (mol->IsSolvent()) {
// NOTE: We assume the oxygen is the first atom!
int o_idx = mol->MolUnit().Front();
#ifdef CUDA
this->headAtomType_ = setup.Top()[o_idx].TypeIndex();
#endif
// Check that molecule has correct # of atoms
unsigned int molNumAtoms = (unsigned int)mol->NumAtoms();
if (nMolAtoms_ == 0) {
nMolAtoms_ = molNumAtoms;
mprintf("\tEach solvent molecule has %u atoms\n", nMolAtoms_);
} else if (molNumAtoms != nMolAtoms_) {
mprinterr("Error: All solvent molecules must have same # atoms.\n"
"Error: Molecule '%s' has %u atoms, expected %u.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str(),
molNumAtoms, nMolAtoms_);
return Action::ERR;
}
//mol_nums_.push_back( midx ); // TODO needed?
// Check that first atom is actually Oxygen
if (setup.Top()[o_idx].Element() != Atom::OXYGEN) {
mprinterr("Error: Molecule '%s' is not water or does not have oxygen atom.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str());
return Action::ERR;
}
O_idxs_.push_back( o_idx );
atomIsSolventO_[o_idx] = true;
// Check that the next two atoms are Hydrogens
if (setup.Top()[o_idx+1].Element() != Atom::HYDROGEN ||
setup.Top()[o_idx+2].Element() != Atom::HYDROGEN)
{
mprinterr("Error: Molecule '%s' does not have hydrogen atoms.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str());
return Action::ERR;
}
// Save all atom indices for energy calc, including extra points
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
A_idxs_.push_back( o_idx + IDX );
atomIsSolute_[A_idxs_.back()] = false; // The identity of the atom is water
atom_voxel_[A_idxs_.back()] = OFF_GRID_;
#ifdef CUDA
this->molecule_.push_back( setup.Top()[o_idx + IDX ].MolNum() );
this->charges_.push_back( setup.Top()[o_idx + IDX ].Charge() );
this->atomTypes_.push_back( setup.Top()[o_idx + IDX ].TypeIndex() );
this->solvent_[ o_idx + IDX ] = true;
#endif
}
NsolventAtoms += nMolAtoms_;
// If first solvent molecule, save charges. If not, check that charges match.
if (isFirstSolvent) {
double q_sum = 0.0;
Q_.reserve( nMolAtoms_ );
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
Q_.push_back( setup.Top()[o_idx+IDX].Charge() );
q_sum += Q_.back();
//mprintf("DEBUG: Q= %20.10E q_sum= %20.10E\n", setup.Top()[o_idx+IDX].Charge(), q_sum);
}
// Sanity checks.
// NOTE: We know indices 1 and 2 are hydrogens (with 0 being oxygen); this is checked above.
if (NotEqual(Q_[1], Q_[2]))
mprintf("Warning: Charges on water hydrogens do not match (%g, %g).\n", Q_[1], Q_[2]);
if (fabs( q_sum ) > 0.0)
mprintf("Warning: Charges on water do not sum to 0 (%g)\n", q_sum);
//mprintf("DEBUG: Water charges: O=%g H1=%g H2=%g\n", q_O_, q_H1_, q_H2_);
} else {
for (unsigned int IDX = 0; IDX < nMolAtoms_; IDX++) {
double q_atom = setup.Top()[o_idx+IDX].Charge();
if (NotEqual(Q_[IDX], q_atom)) {
mprintf("Warning: Charge on water '%s' (%g) does not match first water (%g).\n",
setup.Top().TruncResAtomName( o_idx+IDX ).c_str(), q_atom, Q_[IDX]);
}
}
}
isFirstSolvent = false;
} else {
// This is a non-solvent molecule. Save atom indices. May want to exclude
// if only 1 atom (probably ion).
if (mol->NumAtoms() > 1 || includeIons_) {
for (Unit::const_iterator seg = mol->MolUnit().segBegin();
seg != mol->MolUnit().segEnd(); ++seg)
{
for (int u_idx = seg->Begin(); u_idx != seg->End(); ++u_idx) {
A_idxs_.push_back( u_idx );
atomIsSolute_[A_idxs_.back()] = true; // the identity of the atom is solute
NsoluteAtoms++;
U_idxs_.push_back( u_idx ); // store the solute atom index for locating voxel index
#ifdef CUDA
this->molecule_.push_back( setup.Top()[ u_idx ].MolNum() );
this->charges_.push_back( setup.Top()[ u_idx ].Charge() );
this->atomTypes_.push_back( setup.Top()[ u_idx ].TypeIndex() );
this->solvent_[ u_idx ] = false;
#endif
}
}
}
}
}
NSOLVENT_ = O_idxs_.size();
mprintf("\t%zu solvent molecules, %u solvent atoms, %u solute atoms (%zu total).\n",
O_idxs_.size(), NsolventAtoms, NsoluteAtoms, A_idxs_.size());
if (doOrder_ && NSOLVENT_ < 5) {
mprintf("Warning: Less than 5 solvent molecules. Cannot perform order calculation.\n");
doOrder_ = false;
}
// Allocate space for saving indices of water atoms that are on the grid
// Estimate how many solvent molecules can possibly fit onto the grid.
// Add some extra voxels as a buffer.
double max_voxels = (double)MAX_GRID_PT_ + (1.10 * (double)MAX_GRID_PT_);
double totalVolume = max_voxels * gO_->Bin().VoxelVolume();
double max_mols = totalVolume * BULK_DENS_;
//mprintf("\tEstimating grid can fit a max of %.0f solvent molecules (w/ 10%% buffer).\n",
// max_mols);
OnGrid_idxs_.reserve( (size_t)max_mols * (size_t)nMolAtoms_ );
N_ON_GRID_ = 0;
if (!skipE_) {
if (imageOpt_.ImagingEnabled())
mprintf("\tImaging enabled for energy distance calculations.\n");
else
mprintf("\tNo imaging will be performed for energy distance calculations.\n");
}
#ifdef CUDA
NonbondParmType nb = setup.Top().Nonbond();
this->NBIndex_ = nb.NBindex();
this->numberAtomTypes_ = nb.Ntypes();
for (unsigned int i = 0; i < nb.NBarray().size(); ++i) {
this->lJParamsA_.push_back( (float) nb.NBarray().at(i).A() );
this->lJParamsB_.push_back( (float) nb.NBarray().at(i).B() );
}
try {
allocateCuda(((void**)&this->NBindex_c_), this->NBIndex_.size() * sizeof(int));
allocateCuda((void**)&this->max_c_, 3 * sizeof(float));
allocateCuda((void**)&this->min_c_, 3 * sizeof(float));
allocateCuda((void**)&this->result_w_c_, this->numberAtoms_ * sizeof(float));
allocateCuda((void**)&this->result_s_c_, this->numberAtoms_ * sizeof(float));
allocateCuda((void**)&this->result_O_c_, this->numberAtoms_ * 4 * sizeof(int));
allocateCuda((void**)&this->result_N_c_, this->numberAtoms_ * sizeof(int));
} catch (CudaException &e) {
mprinterr("Error: Could not allocate memory on GPU!\n");
this->freeGPUMemory();
return Action::ERR;
}
try {
this->copyToGPU();
} catch (CudaException &e) {
return Action::ERR;
}
#endif
gist_setup_.Stop();
return Action::OK;
}
const Vec3 Action_GIST::x_lab_ = Vec3(1.0, 0.0, 0.0);
const Vec3 Action_GIST::y_lab_ = Vec3(0.0, 1.0, 0.0);
const Vec3 Action_GIST::z_lab_ = Vec3(0.0, 0.0, 1.0);
const double Action_GIST::QFAC_ = Constants::ELECTOAMBER * Constants::ELECTOAMBER;
const int Action_GIST::OFF_GRID_ = -1;
/* Calculate the charge-charge, vdw interaction using pme, frame by frame
*
*/
void Action_GIST::NonbondEnergy_pme(Frame const& frameIn)
{
# ifdef LIBPME
// Two energy terms for the whole system
//double ene_pme_all = 0.0;
//double ene_vdw_all = 0.0;
// pointer to the E_pme_, where has the voxel-wise pme energy for water
double* E_pme_grid = &E_pme_[0];
// pointer to U_E_pme_, where has the voxel-wise pme energy for solute
double* U_E_pme_grid = &U_E_pme_[0];
gistPme_.<API key>(frameIn, atom_voxel_, atomIsSolute_, atomIsSolventO_,
E_UV_VDW_, E_UV_Elec_, E_VV_VDW_, E_VV_Elec_,
neighbor_);
// <API key> += ene_pme_all + ene_vdw_all;
// Water energy on the GIST grid
double pme_sum = 0.0;
for (unsigned int gidx=0; gidx < N_ON_GRID_; gidx++ )
{
int a = OnGrid_idxs_[gidx]; // index of the atom of on-grid solvent;
int a_voxel = atom_voxel_[a]; // index of the voxel
double nonbond_energy = gistPme_.E_of_atom(a);
pme_sum += nonbond_energy;
E_pme_grid[a_voxel] += nonbond_energy;
}
// Solute energy on the GIST grid
double solute_on_grid_sum = 0.0; // To sum up the potential energy on solute atoms that on the grid
for (unsigned int uidx=0; uidx < U_onGrid_idxs_.size(); uidx++ )
{
int u = U_onGrid_idxs_[uidx]; // index of the solute atom on the grid
int u_voxel = atom_voxel_[u];
double u_nonbond_energy = gistPme_.E_of_atom(u);
solute_on_grid_sum += u_nonbond_energy;
U_E_pme_grid[u_voxel] += u_nonbond_energy;
}
/*
// Total solute energy
double solute_sum = 0.0;
for (unsigned int uidx=0; uidx < U_idxs_.size(); uidx++)
{
int u = U_idxs_[uidx];
double u_nonbond_energy = gistPme_.E_of_atom(u);
solute_sum += u_nonbond_energy;
<API key> += u_nonbond_energy; // used to calculated the ensemble energy for all solute, will print out in terminal
}
*/
//mprintf("The total potential energy on water atoms: %f \n", pme_sum);
# else /*LIBPME */
mprinterr("Error: Compiled without LIBPME\n");
return;
# endif /*LIBPME */
}
/** Non-bonded energy calc. */
void Action_GIST::Ecalc(double rij2, double q1, double q2, NonbondType const& LJ,
double& Evdw, double& Eelec)
{
double rij = sqrt(rij2);
// VDW
double r2 = 1.0 / rij2;
double r6 = r2 * r2 * r2;
double r12 = r6 * r6;
double f12 = LJ.A() * r12; // A/r^12
double f6 = LJ.B() * r6; // B/r^6
Evdw = f12 - f6; // (A/r^12)-(B/r^6)
// Coulomb
double qiqj = QFAC_ * q1 * q2;
Eelec = qiqj / rij;
}
/** Calculate the energy between all solute/solvent atoms and solvent atoms
* on the grid. This is done after the intial GIST calculations
* so that all waters have voxels assigned in atom_voxel_.
* NOTE: This routine modifies the coordinates in OnGrid_XYZ_ when the cell
* has nonorthogonal shape in order to properly satsify the minimum
* image convention, so any calculations that rely on the on grid
* coordinates (like Order()) must be done *BEFORE* this routine.
*/
void Action_GIST::NonbondEnergy(Frame const& frameIn, Topology const& topIn)
{
// Set up imaging info.
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
// Wrap on-grid water coords back to primary cell TODO openmp
double* ongrid_xyz = &OnGrid_XYZ_[0];
int maxXYZ = (int)OnGrid_XYZ_.size();
int idx;
# ifdef _OPENMP
# pragma omp parallel private(idx)
{
# pragma omp for
# endif
for (idx = 0; idx < maxXYZ; idx += 3)
{
double* XYZ = ongrid_xyz + idx;
// Convert to frac coords
frameIn.BoxCrd().FracCell().TimesVec( XYZ, XYZ );
// Wrap to primary cell
XYZ[0] = XYZ[0] - floor(XYZ[0]);
XYZ[1] = XYZ[1] - floor(XYZ[1]);
XYZ[2] = XYZ[2] - floor(XYZ[2]);
// Convert back to Cartesian
frameIn.BoxCrd().UnitCell().TransposeMult( XYZ, XYZ );
}
# ifdef _OPENMP
}
# endif
}
// mprintf("DEBUG: NSolventAtoms= %zu NwatAtomsOnGrid= %u\n", O_idxs_.size()*nMolAtoms_, N_ON_GRID_);
double* E_UV_VDW = &(E_UV_VDW_[0][0]);
double* E_UV_Elec = &(E_UV_Elec_[0][0]);
double* E_VV_VDW = &(E_VV_VDW_[0][0]);
double* E_VV_Elec = &(E_VV_Elec_[0][0]);
float* Neighbor = &(neighbor_[0][0]);
double Evdw, Eelec;
int aidx;
int maxAidx = (int)A_idxs_.size();
// Loop over all solute + solvent atoms
# ifdef _OPENMP
int mythread;
Iarray* eij_v1 = 0;
Iarray* eij_v2 = 0;
Farray* eij_en = 0;
# pragma omp parallel private(aidx, mythread, E_UV_VDW, E_UV_Elec, E_VV_VDW, E_VV_Elec, Neighbor, Evdw, Eelec, eij_v1, eij_v2, eij_en)
{
mythread = omp_get_thread_num();
E_UV_VDW = &(E_UV_VDW_[mythread][0]);
E_UV_Elec = &(E_UV_Elec_[mythread][0]);
E_VV_VDW = &(E_VV_VDW_[mythread][0]);
E_VV_Elec = &(E_VV_Elec_[mythread][0]);
Neighbor = (&neighbor_[mythread][0]);
if (doEij_) {
eij_v1 = &(EIJ_V1_[mythread]);
eij_v2 = &(EIJ_V2_[mythread]);
eij_en = &(EIJ_EN_[mythread]);
eij_v1->clear();
eij_v2->clear();
eij_en->clear();
}
# pragma omp for
# endif
for (aidx = 0; aidx < maxAidx; aidx++)
{
int a1 = A_idxs_[aidx]; // Index of atom1
int a1_voxel = atom_voxel_[a1]; // Voxel of atom1
int a1_mol = topIn[ a1 ].MolNum(); // Molecule # of atom 1
Vec3 A1_XYZ( frameIn.XYZ( a1 ) ); // Coord of atom1
double qA1 = topIn[ a1 ].Charge(); // Charge of atom1
bool a1IsO = atomIsSolventO_[a1];
std::vector<Vec3> vImages;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
// Convert to frac coords
Vec3 vFrac = frameIn.BoxCrd().FracCell() * A1_XYZ;
// Wrap to primary unit cell
vFrac[0] = vFrac[0] - floor(vFrac[0]);
vFrac[1] = vFrac[1] - floor(vFrac[1]);
vFrac[2] = vFrac[2] - floor(vFrac[2]);
// Calculate all images of this atom
vImages.reserve(27);
for (int ix = -1; ix != 2; ix++)
for (int iy = -1; iy != 2; iy++)
for (int iz = -1; iz != 2; iz++)
// Convert image back to Cartesian
vImages.push_back( frameIn.BoxCrd().UnitCell().TransposeMult( vFrac + Vec3(ix,iy,iz) ) );
}
// Loop over all solvent atoms on the grid
for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx++)
{
int a2 = OnGrid_idxs_[gidx]; // Index of on-grid solvent
int a2_mol = topIn[ a2 ].MolNum(); // Molecule # of on-grid solvent
if (a1_mol != a2_mol)
{
int a2_voxel = atom_voxel_[a2]; // Voxel of on-grid solvent
const double* A2_XYZ = (&OnGrid_XYZ_[0])+gidx*3; // Coord of on-grid solvent
if (atomIsSolute_[a1]) {
// Solute to on-grid solvent energy
// Calculate distance
//gist_nonbond_dist_.Start();
double rij2;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
# ifdef <API key>
rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell());
# else
rij2 = maxD_;
for (std::vector<Vec3>::const_iterator vCart = vImages.begin();
vCart != vImages.end(); ++vCart)
{
double x = (*vCart)[0] - A2_XYZ[0];
double y = (*vCart)[1] - A2_XYZ[1];
double z = (*vCart)[2] - A2_XYZ[2];
rij2 = std::min(rij2, x*x + y*y + z*z);
}
# endif
} else if (imageOpt_.ImagingType() == ImageOption::ORTHO)
rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() );
else
rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ );
//gist_nonbond_dist_.Stop();
//gist_nonbond_UV_.Start();
// Calculate energy
Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec );
E_UV_VDW[a2_voxel] += Evdw;
E_UV_Elec[a2_voxel] += Eelec;
//gist_nonbond_UV_.Stop();
} else {
// Off-grid/on-grid solvent to on-grid solvent energy
// Only do the energy calculation if not previously done or atom1 not on grid
if (a2 != a1 && (a2 > a1 || a1_voxel == OFF_GRID_))
{
// Calculate distance
//gist_nonbond_dist_.Start();
double rij2;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
# ifdef <API key>
rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell());
# else
rij2 = maxD_;
for (std::vector<Vec3>::const_iterator vCart = vImages.begin();
vCart != vImages.end(); ++vCart)
{
double x = (*vCart)[0] - A2_XYZ[0];
double y = (*vCart)[1] - A2_XYZ[1];
double z = (*vCart)[2] - A2_XYZ[2];
rij2 = std::min(rij2, x*x + y*y + z*z);
}
# endif
} else if (imageOpt_.ImagingType() == ImageOption::ORTHO)
rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() );
else
rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ );
//gist_nonbond_dist_.Stop();
//gist_nonbond_VV_.Start();
// Calculate energy
Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec );
//mprintf("DEBUG1: v1= %i v2= %i EVV %i %i Vdw= %f Elec= %f\n", a2_voxel, a1_voxel, a2, a1, Evdw, Eelec);
E_VV_VDW[a2_voxel] += Evdw;
E_VV_Elec[a2_voxel] += Eelec;
// Store water neighbor using only O-O distance
bool is_O_O = (a1IsO && atomIsSolventO_[a2]);
if (is_O_O && rij2 < NeighborCut2_)
Neighbor[a2_voxel] += 1.0;
// If water atom1 was also on the grid update its energy as well.
if ( a1_voxel != OFF_GRID_ ) {
E_VV_VDW[a1_voxel] += Evdw;
E_VV_Elec[a1_voxel] += Eelec;
if (is_O_O && rij2 < NeighborCut2_)
Neighbor[a1_voxel] += 1.0;
if (doEij_) {
if (a1_voxel != a2_voxel) {
# ifdef _OPENMP
eij_v1->push_back( a1_voxel );
eij_v2->push_back( a2_voxel );
eij_en->push_back( Evdw + Eelec );
# else
ww_Eij_->UpdateElement(a1_voxel, a2_voxel, Evdw + Eelec);
# endif
}
}
}
//gist_nonbond_VV_.Stop();
}
}
} // END a1 and a2 not in same molecule
} // End loop over all solvent atoms on grid
} // End loop over all solvent + solute atoms
# ifdef _OPENMP
} // END pragma omp parallel
if (doEij_) {
// Add any Eijs to matrix
for (unsigned int thread = 0; thread != EIJ_V1_.size(); thread++)
for (unsigned int idx = 0; idx != EIJ_V1_[thread].size(); idx++)
ww_Eij_->UpdateElement(EIJ_V1_[thread][idx], EIJ_V2_[thread][idx], EIJ_EN_[thread][idx]);
}
# endif
}
/** GIST order calculation. */
void Action_GIST::Order(Frame const& frameIn) {
// Loop over all solvent molecules that are on the grid
for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx += nMolAtoms_)
{
int oidx1 = OnGrid_idxs_[gidx];
int voxel1 = atom_voxel_[oidx1];
Vec3 XYZ1( (&OnGrid_XYZ_[0])+gidx*3 );
// Find coordinates for 4 closest neighbors to this water (on or off grid).
// TODO set up overall grid in DoAction.
// TODO initialize WAT?
Vec3 WAT[4];
double d1 = maxD_;
double d2 = maxD_;
double d3 = maxD_;
double d4 = maxD_;
for (unsigned int sidx2 = 0; sidx2 < NSOLVENT_; sidx2++)
{
int oidx2 = O_idxs_[sidx2];
if (oidx2 != oidx1)
{
const double* XYZ2 = frameIn.XYZ( oidx2 );
double dist2 = DIST2_NoImage( XYZ1.Dptr(), XYZ2 );
if (dist2 < d1) {
d4 = d3; d3 = d2; d2 = d1; d1 = dist2;
WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = WAT[0]; WAT[0] = XYZ2;
} else if (dist2 < d2) {
d4 = d3; d3 = d2; d2 = dist2;
WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = XYZ2;
} else if (dist2 < d3) {
d4 = d3; d3 = dist2;
WAT[3] = WAT[2]; WAT[2] = XYZ2;
} else if (dist2 < d4) {
d4 = dist2;
WAT[3] = XYZ2;
}
}
}
// Compute the tetrahedral order parameter
double sum = 0.0;
for (int mol1 = 0; mol1 < 3; mol1++) {
for (int mol2 = mol1 + 1; mol2 < 4; mol2++) {
Vec3 v1 = WAT[mol1] - XYZ1;
Vec3 v2 = WAT[mol2] - XYZ1;
double r1 = v1.Magnitude2();
double r2 = v2.Magnitude2();
double cos = (v1* v2) / sqrt(r1 * r2);
sum += (cos + 1.0/3)*(cos + 1.0/3);
}
}
order_norm_->UpdateVoxel(voxel1, (1.0 - (3.0/8)*sum));
//mprintf("DBG: gidx= %u oidx1=%i voxel1= %i XYZ1={%g, %g, %g} sum= %g\n", gidx, oidx1, voxel1, XYZ1[0], XYZ1[1], XYZ1[2], sum);
} // END loop over all solvent molecules
}
/** GIST action */
Action::RetType Action_GIST::DoAction(int frameNum, ActionFrame& frm) {
gist_action_.Start();
NFRAME_++;
// TODO only !skipE?
N_ON_GRID_ = 0;
OnGrid_idxs_.clear();
OnGrid_XYZ_.clear();
// Determine imaging type
# ifdef DEBUG_GIST
//mprintf("DEBUG: Is_X_Aligned_Ortho() = %i Is_X_Aligned() = %i\n", (int)frm.Frm().BoxCrd().Is_X_Aligned_Ortho(), (int)frm.Frm().BoxCrd().Is_X_Aligned());
frm.Frm().BoxCrd().UnitCell().Print("Ucell");
frm.Frm().BoxCrd().FracCell().Print("Frac");
# endif
if (imageOpt_.ImagingEnabled())
imageOpt_.SetImageType( frm.Frm().BoxCrd().Is_X_Aligned_Ortho() );
# ifdef DEBUG_GIST
switch (imageOpt_.ImagingType()) {
case ImageOption::NO_IMAGE : mprintf("DEBUG: No Image.\n"); break;
case ImageOption::ORTHO : mprintf("DEBUG: Orthogonal image.\n"); break;
case ImageOption::NONORTHO : mprintf("DEBUG: Nonorthogonal image.\n"); break;
}
# endif
// CUDA necessary information
size_t bin_i, bin_j, bin_k;
Vec3 const& Origin = gO_->Bin().GridOrigin();
// Loop over each solvent molecule
for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++)
{
gist_grid_.Start();
int oidx = O_idxs_[sidx];
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++)
atom_voxel_[oidx+IDX] = OFF_GRID_;
const double* O_XYZ = frm.Frm().XYZ( oidx );
// Get vector of water oxygen to grid origin.
Vec3 W_G( O_XYZ[0] - Origin[0],
O_XYZ[1] - Origin[1],
O_XYZ[2] - Origin[2] );
gist_grid_.Stop();
// Check if water oxygen is no more then 1.5 Ang from grid
// NOTE: using <= to be consistent with original code
if ( W_G[0] <= G_max_[0] && W_G[0] >= -1.5 &&
W_G[1] <= G_max_[1] && W_G[1] >= -1.5 &&
W_G[2] <= G_max_[2] && W_G[2] >= -1.5 )
{
const double* H1_XYZ = frm.Frm().XYZ( oidx + 1 );
const double* H2_XYZ = frm.Frm().XYZ( oidx + 2 );
// Try to bin the oxygen
if ( gO_->Bin().Calc( O_XYZ[0], O_XYZ[1], O_XYZ[2], bin_i, bin_j, bin_k ) )
{
// Oxygen is inside the grid. Record the voxel.
// NOTE hydrogens/EP always assigned to same voxel for energy purposes.
int voxel = (int)gO_->CalcIndex(bin_i, bin_j, bin_k);
const double* wXYZ = O_XYZ;
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
atom_voxel_[oidx+IDX] = voxel;
//OnGrid_idxs_[N_ON_GRID_+IDX] = oidx + IDX;
OnGrid_idxs_.push_back( oidx+IDX );
OnGrid_XYZ_.push_back( wXYZ[0] );
OnGrid_XYZ_.push_back( wXYZ[1] );
OnGrid_XYZ_.push_back( wXYZ[2] );
wXYZ+=3;
}
N_ON_GRID_ += nMolAtoms_;
//mprintf("DEBUG1: Water atom %i voxel %i\n", oidx, voxel);
N_waters_[voxel]++;
max_nwat_ = std::max( N_waters_[voxel], max_nwat_ );
gist_euler_.Start();
// Record XYZ coords of water atoms (nonEP) in voxel TODO need EP?
voxel_xyz_[voxel].push_back( O_XYZ[0] );
voxel_xyz_[voxel].push_back( O_XYZ[1] );
voxel_xyz_[voxel].push_back( O_XYZ[2] );
// Get O-HX vectors
Vec3 H1_wat( H1_XYZ[0]-O_XYZ[0], H1_XYZ[1]-O_XYZ[1], H1_XYZ[2]-O_XYZ[2] );
Vec3 H2_wat( H2_XYZ[0]-O_XYZ[0], H2_XYZ[1]-O_XYZ[1], H2_XYZ[2]-O_XYZ[2] );
H1_wat.Normalize();
H2_wat.Normalize();
Vec3 ar1 = H1_wat.Cross( x_lab_ ); // ar1 = V cross U
Vec3 sar = ar1; // sar = V cross U
ar1.Normalize();
//H1_wat.Print("DEBUG: H1_wat");
//x_lab_.Print("DEBUG: x_lab_");
//ar1.Print("DEBUG: ar1");
//sar.Print("DEBUG: sar");
double dp1 = x_lab_ * H1_wat; // V dot U
double theta = acos(dp1);
double sign = sar * H1_wat;
//mprintf("DEBUG0: dp1= %f theta= %f sign= %f\n", dp1, theta, sign);
// NOTE: Use SMALL instead of 0 to avoid issues with denormalization
if (sign > Constants::SMALL)
theta /= 2.0;
else
theta /= -2.0;
double w1 = cos(theta);
double sin_theta = sin(theta);
//mprintf("DEBUG0: theta= %f w1= %f sin_theta= %f\n", theta, w1, sin_theta);
double x1 = ar1[0] * sin_theta;
double y1 = ar1[1] * sin_theta;
double z1 = ar1[2] * sin_theta;
double w2 = w1;
double x2 = x1;
double y2 = y1;
double z2 = z1;
Vec3 H_temp;
H_temp[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H1_wat[0];
H_temp[0] = (2*(x2*y2 + w2*z2)*H1_wat[1]) + H_temp[0];
H_temp[0] = (2*(x2*z2-w2*y2)*H1_wat[2]) + H_temp[0];
H_temp[1] = 2*(x2*y2 - w2*z2)* H1_wat[0];
H_temp[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H1_wat[1]) + H_temp[1];
H_temp[1] = (2*(y2*z2+w2*x2)*H1_wat[2]) +H_temp[1];
H_temp[2] = 2*(x2*z2+w2*y2) *H1_wat[0];
H_temp[2] = (2*(y2*z2-w2*x2)*H1_wat[1]) + H_temp[2];
H_temp[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H1_wat[2]) + H_temp[2];
H1_wat = H_temp;
Vec3 H_temp2;
H_temp2[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H2_wat[0];
H_temp2[0] = (2*(x2*y2 + w2*z2)*H2_wat[1]) + H_temp2[0];
H_temp2[0] = (2*(x2*z2-w2*y2)*H2_wat[2]) +H_temp2[0];
H_temp2[1] = 2*(x2*y2 - w2*z2) *H2_wat[0];
H_temp2[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H2_wat[1]) +H_temp2[1];
H_temp2[1] = (2*(y2*z2+w2*x2)*H2_wat[2]) +H_temp2[1];
H_temp2[2] = 2*(x2*z2+w2*y2)*H2_wat[0];
H_temp2[2] = (2*(y2*z2-w2*x2)*H2_wat[1]) +H_temp2[2];
H_temp2[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H2_wat[2]) + H_temp2[2];
H2_wat = H_temp2;
Vec3 ar2 = H_temp.Cross(H_temp2);
ar2.Normalize();
double dp2 = ar2 * z_lab_;
theta = acos(dp2);
sar = ar2.Cross( z_lab_ );
sign = sar * H_temp;
if (sign < 0)
theta /= 2.0;
else
theta /= -2.0;
double w3 = cos(theta);
sin_theta = sin(theta);
double x3 = x_lab_[0] * sin_theta;
double y3 = x_lab_[1] * sin_theta;
double z3 = x_lab_[2] * sin_theta;
double w4 = w1*w3 - x1*x3 - y1*y3 - z1*z3;
double x4 = w1*x3 + x1*w3 + y1*z3 - z1*y3;
double y4 = w1*y3 - x1*z3 + y1*w3 + z1*x3;
double z4 = w1*z3 + x1*y3 - y1*x3 + z1*w3;
voxel_Q_[voxel].push_back( w4 );
voxel_Q_[voxel].push_back( x4 );
voxel_Q_[voxel].push_back( y4 );
voxel_Q_[voxel].push_back( z4 );
//mprintf("DEBUG1: sidx= %u voxel= %i wxyz4= %g %g %g %g\n", sidx, voxel, w4, x4, y4, z4);
//mprintf("DEBUG2: wxyz3= %g %g %g %g wxyz2= %g %g %g %g wxyz1= %g %g %g\n",
// w3, x3, y3, z3,
// w2, x2, y2, z2,
// w1, x1, y1, z1);
// NOTE: No need for nw_angle_ here, it is same as N_waters_
gist_euler_.Stop();
gist_dipole_.Start();
//mprintf("DEBUG1: voxel %i dipole %f %f %f\n", voxel,
// O_XYZ[0]*q_O_ + H1_XYZ[0]*q_H1_ + H2_XYZ[0]*q_H2_,
// O_XYZ[1]*q_O_ + H1_XYZ[1]*q_H1_ + H2_XYZ[1]*q_H2_,
// O_XYZ[2]*q_O_ + H1_XYZ[2]*q_H1_ + H2_XYZ[2]*q_H2_);
double DPX = 0.0;
double DPY = 0.0;
double DPZ = 0.0;
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
const double* XYZ = frm.Frm().XYZ( oidx+IDX );
DPX += XYZ[0] * Q_[IDX];
DPY += XYZ[1] * Q_[IDX];
DPZ += XYZ[2] * Q_[IDX];
}
dipolex_->UpdateVoxel(voxel, DPX);
dipoley_->UpdateVoxel(voxel, DPY);
dipolez_->UpdateVoxel(voxel, DPZ);
gist_dipole_.Stop();
}
// Water is at most 1.5A away from grid, so we need to check for H
// even if O is outside grid.
if (gO_->Bin().Calc( H1_XYZ[0], H1_XYZ[1], H1_XYZ[2], bin_i, bin_j, bin_k ) )
N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++;
if (gO_->Bin().Calc( H2_XYZ[0], H2_XYZ[1], H2_XYZ[2], bin_i, bin_j, bin_k ) )
N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++;
} // END water is within 1.5 Ang of grid
} // END loop over each solvent molecule
// Do solute grid assignment for PME
if (usePme_) {
U_onGrid_idxs_.clear();
gist_grid_.Start();
for (unsigned int s = 0; s != U_idxs_.size(); s++)
{
int uidx = U_idxs_[s]; // the solute atom index
atom_voxel_[uidx] = OFF_GRID_;
const double* u_XYZ = frm.Frm().XYZ( uidx );
// get the vector of this solute atom to the grid origin
Vec3 U_G( u_XYZ[0] - Origin[0],
u_XYZ[1] - Origin[1],
u_XYZ[2] - Origin[2]);
//size_t bin_i, bin_j, bin_k;
if ( U_G[0] <= G_max_[0] && U_G[0] >= -1.5 &&
U_G[1] <= G_max_[1] && U_G[1] >= -1.5 &&
U_G[2] <= G_max_[2] && U_G[2] >- -1.5)
{
if ( gO_->Bin().Calc(u_XYZ[0],u_XYZ[1],u_XYZ[2],bin_i,bin_j,bin_k)) // used the gO class function to calcaute voxel index
{
int voxel = (int)gO_->CalcIndex(bin_i,bin_j,bin_k);
atom_voxel_[uidx] = voxel; // asign the voxel index to the solute atom
//U_ON_GRID_ +=1; // add +1 to the number of atom on the GIST Grid
N_solute_atoms_[voxel] +=1; // add +1 to the solute atom num in this voxel
U_onGrid_idxs_.push_back(uidx); // The index of the solute atom on GIST Grid
}
}
}
gist_grid_.Stop();
}
# ifndef CUDA
// Do order calculation if requested.
// Do not do this for CUDA since CUDA nonbond routine handles the order calc.
// NOTE: This has to be done before the nonbond energy calc since
// the nonbond calc can modify the on-grid coordinates (for minimum
// image convention when cell is non-orthogonal).
gist_order_.Start();
if (doOrder_) Order(frm.Frm());
gist_order_.Stop();
# endif
// Do nonbond energy calc if not skipping energy
gist_nonbond_.Start();
if (!skipE_) {
if (usePme_) {
// PME
NonbondEnergy_pme( frm.Frm() );
} else {
// Non-PME
# ifdef CUDA
NonbondCuda(frm);
# else
NonbondEnergy(frm.Frm(), *CurrentParm_);
# endif
}
}
gist_nonbond_.Stop();
gist_action_.Stop();
return Action::OK;
}
/** Translational entropy calc between given water and all waters in voxel 2.
* \param VX voxel 1 water X
* \param VY voxel 1 water Y
* \param VZ voxel 1 water Z
* \param W4 voxel 1 water W4
* \param X4 voxel 1 water X4
* \param Y4 voxel 1 water Y4
* \param Z4 voxel 1 water Z4
* \param voxel2 Index of second voxel
*/
void Action_GIST::TransEntropy(float VX, float VY, float VZ,
float W4, float X4, float Y4, float Z4,
int voxel2, double& NNd, double& NNs) const
{
int nw_tot = N_waters_[voxel2];
Farray const& V_XYZ = voxel_xyz_[voxel2];
Farray const& V_Q = voxel_Q_[voxel2];
for (int n1 = 0; n1 != nw_tot; n1++)
{
int i1 = n1 * 3; // index into V_XYZ for n1
double dx = (double)(VX - V_XYZ[i1 ]);
double dy = (double)(VY - V_XYZ[i1+1]);
double dz = (double)(VZ - V_XYZ[i1+2]);
double dd = dx*dx+dy*dy+dz*dz;
if (dd < NNd && dd > 0) { NNd = dd; }
int q1 = n1 * 4; // index into V_Q for n1
double rR = 2.0 * acos( fabs(W4 * V_Q[q1 ] +
X4 * V_Q[q1+1] +
Y4 * V_Q[q1+2] +
Z4 * V_Q[q1+3] )); //add fabs for quaternions distance calculation
double ds = rR*rR + dd;
if (ds < NNs && ds > 0) { NNs = ds; }
}
}
// Action_GIST::SumEVV()
void Action_GIST::SumEVV() {
if (E_VV_VDW_.size() > 1) {
for (unsigned int gr_pt = 0; gr_pt != MAX_GRID_PT_; gr_pt++) {
for (unsigned int thread = 1; thread < E_VV_VDW_.size(); thread++) {
E_UV_VDW_[0][gr_pt] += E_UV_VDW_[thread][gr_pt];
E_UV_Elec_[0][gr_pt] += E_UV_Elec_[thread][gr_pt];
E_VV_VDW_[0][gr_pt] += E_VV_VDW_[thread][gr_pt];
E_VV_Elec_[0][gr_pt] += E_VV_Elec_[thread][gr_pt];
neighbor_[0][gr_pt] += neighbor_[thread][gr_pt];
}
}
}
}
/** Calculate average voxel energy for PME grids. */
void Action_GIST::<API key>(double Vvox, DataSet_GridFlt& PME_dens, DataSet_GridFlt& U_PME_dens, Farray& PME_norm)
const
{
double PME_tot =0.0;
double U_PME_tot = 0.0;
mprintf("\t Calculating average voxel energies: \n");
ProgressBar E_progress(MAX_GRID_PT_);
for ( unsigned int gr_pt =0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
E_progress.Update(gr_pt);
int nw_total = N_waters_[gr_pt];
if (nw_total >=1)
{
PME_dens[gr_pt] = E_pme_[gr_pt] / (NFRAME_ * Vvox);
PME_norm[gr_pt] = E_pme_[gr_pt] / nw_total;
PME_tot += PME_dens[gr_pt];
}else{
PME_dens[gr_pt]=0;
PME_norm[gr_pt]=0;
}
int ns_total = N_solute_atoms_[gr_pt];
if (ns_total >=1)
{
U_PME_dens[gr_pt] = U_E_pme_[gr_pt] / (NFRAME_ * Vvox);
U_PME_tot += U_PME_dens[gr_pt];
}else{
U_PME_dens[gr_pt]=0;
}
}
PME_tot *=Vvox;
U_PME_tot *=Vvox;
infofile_->Printf("Ensemble total water energy on the grid: %9.5f Kcal/mol \n", PME_tot);
infofile_->Printf("Ensemble total solute energy on the grid: %9.5f Kcal/mol \n",U_PME_tot);
// infofile_->Printf("Ensemble solute's total potential energy : %9.5f Kcal/mol \n", <API key> / NFRAME_);
// infofile_->Printf("Ensemble system's total potential energy: %9.5f Kcal/mol \n", <API key>/NFRAME_);
}
/** Calculate average voxel energy for GIST grids. */
void Action_GIST::CalcAvgVoxelEnergy(double Vvox, DataSet_GridFlt& Eww_dens, DataSet_GridFlt& Esw_dens,
Farray& Eww_norm, Farray& Esw_norm,
DataSet_GridDbl& qtet,
DataSet_GridFlt& neighbor_norm, Farray& neighbor_dens)
{
#ifndef CUDA
Darray const& E_UV_VDW = E_UV_VDW_[0];
Darray const& E_UV_Elec = E_UV_Elec_[0];
Darray const& E_VV_VDW = E_VV_VDW_[0];
Darray const& E_VV_Elec = E_VV_Elec_[0];
#endif
Farray const& Neighbor = neighbor_[0];
#ifndef CUDA
// Sum values from other threads if necessary
SumEVV();
#endif
double Eswtot = 0.0;
double Ewwtot = 0.0;
mprintf("\tCalculating average voxel energies:\n");
ProgressBar E_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
E_progress.Update( gr_pt );
//mprintf("DEBUG1: VV vdw=%f elec=%f\n", E_VV_VDW_[gr_pt], E_VV_Elec_[gr_pt]);
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
if (nw_total > 0) {
#ifndef CUDA
Esw_dens[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / (NFRAME_ * Vvox);
Esw_norm[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / nw_total;
Eww_dens[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * NFRAME_ * Vvox);
Eww_norm[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * nw_total);
#else
double esw = this->Esw_->operator[](gr_pt);
double eww = this->Eww_->operator[](gr_pt);
Esw_dens[gr_pt] = esw / (this->NFRAME_ * Vvox);
Esw_norm[gr_pt] = esw / nw_total;
Eww_dens[gr_pt] = eww / (this->NFRAME_ * Vvox);
Eww_norm[gr_pt] = eww / nw_total;
#endif
Eswtot += Esw_dens[gr_pt];
Ewwtot += Eww_dens[gr_pt];
} else {
Esw_dens[gr_pt]=0;
Esw_norm[gr_pt]=0;
Eww_norm[gr_pt]=0;
Eww_dens[gr_pt]=0;
}
// Compute the average number of water neighbor and average order parameter.
if (nw_total > 0) {
qtet[gr_pt] /= nw_total;
//mprintf("DEBUG1: neighbor= %8.1f nw_total= %8i\n", neighbor[gr_pt], nw_total);
neighbor_norm[gr_pt] = (double)Neighbor[gr_pt] / nw_total;
}
neighbor_dens[gr_pt] = (double)Neighbor[gr_pt] / (NFRAME_ * Vvox);
} // END loop over all grid points (voxels)
Eswtot *= Vvox;
Ewwtot *= Vvox;
infofile_->Printf("Total water-solute energy of the grid: Esw = %9.5f kcal/mol\n", Eswtot);
infofile_->Printf("Total unreferenced water-water energy of the grid: Eww = %9.5f kcal/mol\n",
Ewwtot);
}
/** Handle averaging for grids and output from GIST. */
void Action_GIST::Print() {
gist_print_.Start();
double Vvox = gO_->Bin().VoxelVolume();
mprintf(" GIST OUTPUT:\n");
// The variables are kept outside, so that they are declared for later use.
// Calculate orientational entropy
DataSet_GridFlt& dTSorient_dens = static_cast<DataSet_GridFlt&>( *dTSorient_ );
Farray dTSorient_norm( MAX_GRID_PT_, 0.0 );
double dTSorienttot = 0;
int nwtt = 0;
double dTSo = 0;
if (! this->skipS_) {
// LOOP over all voxels
mprintf("\tCalculating orientational entropy:\n");
ProgressBar oe_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
oe_progress.Update( gr_pt );
dTSorient_dens[gr_pt] = 0;
dTSorient_norm[gr_pt] = 0;
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
nwtt += nw_total;
//mprintf("DEBUG1: %u nw_total %i\n", gr_pt, nw_total);
if (nw_total > 1) {
for (int n0 = 0; n0 < nw_total; n0++)
{
double NNr = 10000;
int q0 = n0 * 4; // Index into voxel_Q_ for n0
for (int n1 = 0; n1 < nw_total; n1++)
{
if (n0 != n1) {
int q1 = n1 * 4; // Index into voxel_Q_ for n1
//mprintf("DEBUG1:\t\t q1= %8i {%12.4f %12.4f %12.4f %12.4f} q0= %8i {%12.4f %12.4f %12.4f %12.4f}\n",
// q1, voxel_Q_[gr_pt][q1 ], voxel_Q_[gr_pt][q1+1], voxel_Q_[gr_pt][q1+2], voxel_Q_[gr_pt][q1+3],
// q0, voxel_Q_[gr_pt][q0 ], voxel_Q_[gr_pt][q0+1], voxel_Q_[gr_pt][q0+2], voxel_Q_[gr_pt][q0+3]);
double rR = 2.0 * acos( fabs(voxel_Q_[gr_pt][q1 ] * voxel_Q_[gr_pt][q0 ]
+ voxel_Q_[gr_pt][q1+1] * voxel_Q_[gr_pt][q0+1]
+ voxel_Q_[gr_pt][q1+2] * voxel_Q_[gr_pt][q0+2]
+ voxel_Q_[gr_pt][q1+3] * voxel_Q_[gr_pt][q0+3] )); // add fabs for quaternion distance calculation
//mprintf("DEBUG1:\t\t %8i %8i %g\n", n0, n1, rR);
if (rR > 0 && rR < NNr) NNr = rR;
}
} // END inner loop over all waters for this voxel
if (NNr < 9999 && NNr > 0) {
double dbl = log(NNr*NNr*NNr*nw_total / (3.0*Constants::TWOPI));
//mprintf("DEBUG1: %u nw_total= %i NNr= %f dbl= %f\n", gr_pt, nw_total, NNr, dbl);
dTSorient_norm[gr_pt] += dbl;
dTSo += dbl;
}
} // END outer loop over all waters for this voxel
//mprintf("DEBUG1: dTSorient_norm %f\n", dTSorient_norm[gr_pt]);
dTSorient_norm[gr_pt] = Constants::GASK_KCAL * temperature_ *
((dTSorient_norm[gr_pt]/nw_total) + Constants::EULER_MASC);
double dtso_norm_nw = (double)dTSorient_norm[gr_pt] * (double)nw_total;
dTSorient_dens[gr_pt] = (dtso_norm_nw / (NFRAME_ * Vvox));
dTSorienttot += dTSorient_dens[gr_pt];
//mprintf("DEBUG1: %f\n", dTSorienttot);
}
} // END loop over all grid points (voxels)
dTSorienttot *= Vvox;
infofile_->Printf("Maximum number of waters found in one voxel for %d frames = %d\n",
NFRAME_, max_nwat_);
infofile_->Printf("Total referenced orientational entropy of the grid:"
" dTSorient = %9.5f kcal/mol, Nf=%d\n", dTSorienttot, NFRAME_);
}
// Compute translational entropy for each voxel
double dTStranstot = 0.0;
double dTSt = 0.0;
double dTSs = 0.0;
int nwts = 0;
unsigned int nx = gO_->NX();
unsigned int ny = gO_->NY();
unsigned int nz = gO_->NZ();
unsigned int addx = ny * nz;
unsigned int addy = nz;
unsigned int addz = 1;
DataSet_GridFlt& gO = static_cast<DataSet_GridFlt&>( *gO_ );
DataSet_GridFlt& gH = static_cast<DataSet_GridFlt&>( *gH_ );
DataSet_GridFlt& dTStrans = static_cast<DataSet_GridFlt&>( *dTStrans_ );
DataSet_GridFlt& dTSsix = static_cast<DataSet_GridFlt&>( *dTSsix_ );
Farray dTStrans_norm( MAX_GRID_PT_, 0.0 );
Farray dTSsix_norm( MAX_GRID_PT_, 0.0 );
// Loop over all grid points
if (! this->skipS_)
mprintf("\tCalculating translational entropy:\n");
else
mprintf("Calculating Densities:\n");
ProgressBar te_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
te_progress.Update( gr_pt );
int numplane = gr_pt / addx;
double W_dens = 1.0 * N_waters_[gr_pt] / (NFRAME_*Vvox);
gO[gr_pt] = W_dens / BULK_DENS_;
gH[gr_pt] = 1.0 * N_hydrogens_[gr_pt] / (NFRAME_*Vvox*2*BULK_DENS_);
if (! this->skipS_) {
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
for (int n0 = 0; n0 < nw_total; n0++)
{
double NNd = 10000;
double NNs = 10000;
int i0 = n0 * 3; // index into voxel_xyz_ for n0
float VX = voxel_xyz_[gr_pt][i0 ];
float VY = voxel_xyz_[gr_pt][i0+1];
float VZ = voxel_xyz_[gr_pt][i0+2];
int q0 = n0 * 4; // index into voxel_Q_ for n0
float W4 = voxel_Q_[gr_pt][q0 ];
float X4 = voxel_Q_[gr_pt][q0+1];
float Y4 = voxel_Q_[gr_pt][q0+2];
float Z4 = voxel_Q_[gr_pt][q0+3];
// First do own voxel
for (int n1 = 0; n1 < nw_total; n1++) {
if ( n1 != n0) {
int i1 = n1 * 3; // index into voxel_xyz_ for n1
double dx = (double)(VX - voxel_xyz_[gr_pt][i1 ]);
double dy = (double)(VY - voxel_xyz_[gr_pt][i1+1]);
double dz = (double)(VZ - voxel_xyz_[gr_pt][i1+2]);
double dd = dx*dx+dy*dy+dz*dz;
if (dd < NNd && dd > 0) { NNd = dd; }
int q1 = n1 * 4; // index into voxel_Q_ for n1
double rR = 2 * acos( fabs(W4*voxel_Q_[gr_pt][q1 ] +
X4*voxel_Q_[gr_pt][q1+1] +
Y4*voxel_Q_[gr_pt][q1+2] +
Z4*voxel_Q_[gr_pt][q1+3] )); //add fabs for quaternion distance calculation
double ds = rR*rR + dd;
if (ds < NNs && ds > 0) { NNs = ds; }
}
} // END self loop over all waters for this voxel
//mprintf("DEBUG1: self NNd=%f NNs=%f\n", NNd, NNs);
// Determine which directions are possible.
bool cannotAddZ = (nz == 0 || ( gr_pt%nz == nz-1 ));
bool cannotAddY = ((nz == 0 || ny-1 == 0) || ( gr_pt%(nz*(ny-1)+(numplane*addx)) < nz));
bool cannotAddX = (gr_pt >= addx * (nx-1) && gr_pt < addx * nx );
bool cannotSubZ = (nz == 0 || gr_pt%nz == 0);
bool cannotSubY = ((nz == 0 || ny == 0) || (gr_pt%addx < nz));
bool cannotSubX = ((nz == 0 || ny == 0) || (gr_pt < addx));
bool boundary = ( cannotAddZ || cannotAddY || cannotAddX ||
cannotSubZ || cannotSubY || cannotSubX );
if (!boundary) {
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy - addx, NNd, NNs);
// add the 8 more voxels for NNr searching
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy - addz, NNd, NNs);
NNd = sqrt(NNd);
NNs = sqrt(NNs);
if (NNd < 3 && NNd > 0/*NNd < 9999 && NNd > 0*/) {
double dbl = log((NNd*NNd*NNd*NFRAME_*4*Constants::PI*BULK_DENS_)/3);
dTStrans_norm[gr_pt] += dbl;
dTSt += dbl;
dbl = log((NNs*NNs*NNs*NNs*NNs*NNs*NFRAME_*Constants::PI*BULK_DENS_)/48);
dTSsix_norm[gr_pt] += dbl;
dTSs += dbl;
//mprintf("DEBUG1: dbl=%f NNs=%f\n", dbl, NNs);
}
}
} // END loop over all waters for this voxel
if (dTStrans_norm[gr_pt] != 0) {
nwts += nw_total;
dTStrans_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTStrans_norm[gr_pt]/nw_total) +
Constants::EULER_MASC );
dTSsix_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTSsix_norm[gr_pt]/nw_total) +
Constants::EULER_MASC );
}
double dtst_norm_nw = (double)dTStrans_norm[gr_pt] * (double)nw_total;
dTStrans[gr_pt] = (dtst_norm_nw / (NFRAME_*Vvox));
double dtss_norm_nw = (double)dTSsix_norm[gr_pt] * (double)nw_total;
dTSsix[gr_pt] = (dtss_norm_nw / (NFRAME_*Vvox));
dTStranstot += dTStrans[gr_pt];
} // END loop over all grid points (voxels)
}
if (!this->skipS_) {
dTStranstot *= Vvox;
double dTSst = 0.0;
double dTStt = 0.0;
if (nwts > 0) {
dTSst = Constants::GASK_KCAL*temperature_*((dTSs/nwts) + Constants::EULER_MASC);
dTStt = Constants::GASK_KCAL*temperature_*((dTSt/nwts) + Constants::EULER_MASC);
}
double dTSot = Constants::GASK_KCAL*temperature_*((dTSo/nwtt) + Constants::EULER_MASC);
infofile_->Printf("watcount in vol = %d\n", nwtt);
infofile_->Printf("watcount in subvol = %d\n", nwts);
infofile_->Printf("Total referenced translational entropy of the grid:"
" dTStrans = %9.5f kcal/mol, Nf=%d\n", dTStranstot, NFRAME_);
infofile_->Printf("Total 6d if all one vox: %9.5f kcal/mol\n", dTSst);
infofile_->Printf("Total t if all one vox: %9.5f kcal/mol\n", dTStt);
infofile_->Printf("Total o if all one vox: %9.5f kcal/mol\n", dTSot);
}
// Compute average voxel energy. Allocate these sets even if skipping energy
// to be consistent with previous output.
DataSet_GridFlt& PME_dens = static_cast<DataSet_GridFlt&>( *PME_);
DataSet_GridFlt& U_PME_dens = static_cast<DataSet_GridFlt&>( *U_PME_);
DataSet_GridFlt& Esw_dens = static_cast<DataSet_GridFlt&>( *Esw_ );
DataSet_GridFlt& Eww_dens = static_cast<DataSet_GridFlt&>( *Eww_ );
DataSet_GridFlt& neighbor_norm = static_cast<DataSet_GridFlt&>( *neighbor_norm_ );
DataSet_GridDbl& qtet = static_cast<DataSet_GridDbl&>( *order_norm_ );
Farray Esw_norm( MAX_GRID_PT_, 0.0 );
Farray Eww_norm( MAX_GRID_PT_, 0.0 );
Farray PME_norm( MAX_GRID_PT_,0.0);
Farray neighbor_dens( MAX_GRID_PT_, 0.0 );
if (!skipE_) {
if (usePme_) {
<API key>(Vvox, PME_dens, U_PME_dens, PME_norm);
}// else {
CalcAvgVoxelEnergy(Vvox, Eww_dens, Esw_dens, Eww_norm, Esw_norm, qtet,
neighbor_norm, neighbor_dens);
}
// Compute average dipole density.
DataSet_GridFlt& pol = static_cast<DataSet_GridFlt&>( *dipole_ );
DataSet_GridDbl& dipolex = static_cast<DataSet_GridDbl&>( *dipolex_ );
DataSet_GridDbl& dipoley = static_cast<DataSet_GridDbl&>( *dipoley_ );
DataSet_GridDbl& dipolez = static_cast<DataSet_GridDbl&>( *dipolez_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
dipolex[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
dipoley[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
dipolez[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
pol[gr_pt] = sqrt( dipolex[gr_pt]*dipolex[gr_pt] +
dipoley[gr_pt]*dipoley[gr_pt] +
dipolez[gr_pt]*dipolez[gr_pt] );
}
// Write the GIST output file.
// TODO: Make a data file format?
if (datafile_ != 0) {
mprintf("\tWriting GIST results for each voxel:\n");
// Create the format strings.
std::string fmtstr =
intFmt_.Fmt() + // grid point
" " + fltFmt_.Fmt() + // grid X
" " + fltFmt_.Fmt() + // grid Y
" " + fltFmt_.Fmt() + // grid Z
" " + intFmt_.Fmt() + // # waters
" " + fltFmt_.Fmt() +
" " + fltFmt_.Fmt() +
" " + fltFmt_.Fmt() + // dTStrans
" " + fltFmt_.Fmt() + // dTStrans_norm
" " + fltFmt_.Fmt() + // dTSorient_dens
" " + fltFmt_.Fmt() + // dTSorient_norm
" " + fltFmt_.Fmt() + // dTSsix
" " + fltFmt_.Fmt() + // dTSsix_norm
" " + fltFmt_.Fmt() + // Esw_dens
" " + fltFmt_.Fmt() + // Esw_norm
" " + fltFmt_.Fmt() + // Eww_dens
" " + fltFmt_.Fmt(); // EWW_norm
if (usePme_) {
fmtstr +=
" " + fltFmt_.Fmt() + // PME_dens
+ " " + fltFmt_.Fmt(); // PME_norm
}
fmtstr +=
" " + fltFmt_.Fmt() + // dipolex
" " + fltFmt_.Fmt() + // dipoley
" " + fltFmt_.Fmt() + // dipolez
" " + fltFmt_.Fmt() + // pol
" " + fltFmt_.Fmt() + // neighbor_dens
" " + fltFmt_.Fmt() + // neighbor_norm
" " + fltFmt_.Fmt() + // qtet
" \n"; // NEWLINE
if (debug_ > 0) mprintf("DEBUG: Fmt='%s'\n", fmtstr.c_str());
const char* gistOutputVersion;
if (usePme_)
gistOutputVersion = "v3";
else
gistOutputVersion = "v2";
// Do the header
datafile_->Printf("GIST Output %s "
"spacing=%.4f center=%.6f,%.6f,%.6f dims=%i,%i,%i \n"
"voxel xcoord ycoord zcoord population g_O g_H"
" dTStrans-dens(kcal/mol/A^3) dTStrans-norm(kcal/mol)"
" dTSorient-dens(kcal/mol/A^3) dTSorient-norm(kcal/mol)"
" dTSsix-dens(kcal/mol/A^3) dTSsix-norm(kcal/mol)"
" Esw-dens(kcal/mol/A^3) Esw-norm(kcal/mol)"
" Eww-dens(kcal/mol/A^3) Eww-norm-unref(kcal/mol)",
gistOutputVersion, gridspacing_,
gridcntr_[0], gridcntr_[1], gridcntr_[2],
(int)griddim_[0], (int)griddim_[1], (int)griddim_[2]);
if (usePme_)
datafile_->Printf(" PME-dens(kcal/mol/A^3) PME-norm(kcal/mol)");
datafile_->Printf(" Dipole_x-dens(D/A^3) Dipole_y-dens(D/A^3) Dipole_z-dens(D/A^3)"
" Dipole-dens(D/A^3) neighbor-dens(1/A^3) neighbor-norm order-norm\n");
// Loop over voxels
ProgressBar O_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
O_progress.Update( gr_pt );
size_t i, j, k;
gO_->ReverseIndex( gr_pt, i, j, k );
Vec3 XYZ = gO_->Bin().Center( i, j, k );
if (usePme_) {
datafile_->Printf(fmtstr.c_str(),
gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt],
dTStrans[gr_pt], dTStrans_norm[gr_pt],
dTSorient_dens[gr_pt], dTSorient_norm[gr_pt],
dTSsix[gr_pt], dTSsix_norm[gr_pt],
Esw_dens[gr_pt], Esw_norm[gr_pt],
Eww_dens[gr_pt], Eww_norm[gr_pt],
PME_dens[gr_pt], PME_norm[gr_pt],
dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt],
pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]);
} else {
datafile_->Printf(fmtstr.c_str(),
gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt],
dTStrans[gr_pt], dTStrans_norm[gr_pt],
dTSorient_dens[gr_pt], dTSorient_norm[gr_pt],
dTSsix[gr_pt], dTSsix_norm[gr_pt],
Esw_dens[gr_pt], Esw_norm[gr_pt],
Eww_dens[gr_pt], Eww_norm[gr_pt],
dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt],
pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]);
}
} // END loop over voxels
} // END datafile_ not null
// Write water-water interaction energy matrix
if (ww_Eij_ != 0) {
DataSet_MatrixFlt& ww_Eij = static_cast<DataSet_MatrixFlt&>( *ww_Eij_ );
double fac = 1.0 / (double)(NFRAME_ * 2);
for (unsigned int idx = 0; idx != ww_Eij.Size(); idx++) {
if (fabs(ww_Eij[idx]) < Constants::SMALL)
ww_Eij[idx] = 0.0;
else {
double val = (double)ww_Eij[idx];
ww_Eij[idx] = (float)(val * fac);
}
}
// Eij matrix output, skip any zeros.
for (unsigned int a = 1; a < MAX_GRID_PT_; a++) {
for (unsigned int l = 0; l < a; l++) {
double dbl = ww_Eij_->GetElement(a, l);
if (dbl != 0)
eijfile_->Printf("%10d %10d %12.5E\n", a, l, dbl);
}
}
}
gist_print_.Stop();
double total = gist_init_.Total() + gist_setup_.Total() +
gist_action_.Total() + gist_print_.Total();
mprintf("\tGIST timings:\n");
gist_init_.WriteTiming(1, "Init: ", total);
gist_setup_.WriteTiming(1, "Setup: ", total);
gist_action_.WriteTiming(1, "Action:", total);
gist_grid_.WriteTiming(2, "Grid: ", gist_action_.Total());
gist_nonbond_.WriteTiming(2, "Nonbond:", gist_action_.Total());
# ifdef LIBPME
if (usePme_)
gistPme_.Timing( gist_nonbond_.Total() );
# endif
//gist_nonbond_dist_.WriteTiming(3, "Dist2:", gist_nonbond_.Total());
//gist_nonbond_UV_.WriteTiming(3, "UV:", gist_nonbond_.Total());
//gist_nonbond_VV_.WriteTiming(3, "VV:", gist_nonbond_.Total());
//gist_nonbond_OV_.WriteTiming(3, "OV:", gist_nonbond_.Total());
gist_euler_.WriteTiming(2, "Euler: ", gist_action_.Total());
gist_dipole_.WriteTiming(2, "Dipole: ", gist_action_.Total());
gist_order_.WriteTiming(2, "Order: ", gist_action_.Total());
gist_print_.WriteTiming(1, "Print:", total);
mprintf("TIME:\tTotal: %.4f s\n", total);
#ifdef CUDA
this->freeGPUMemory();
#endif
}
#ifdef CUDA
void Action_GIST::NonbondCuda(ActionFrame frm) {
// Simply to get the information for the energetic calculations
std::vector<float> eww_result(this->numberAtoms_);
std::vector<float> esw_result(this->numberAtoms_);
std::vector<std::vector<int> > order_indices;
this->gist_nonbond_.Start();
float *recip = NULL;
float *ucell = NULL;
int boxinfo;
// Check Boxinfo and write the necessary data into recip, ucell and boxinfo.
switch(imageOpt_.ImagingType()) {
case ImageOption::NONORTHO:
recip = new float[9];
ucell = new float[9];
for (int i = 0; i < 9; ++i) {
ucell[i] = (float) frm.Frm().BoxCrd().UnitCell()[i];
recip[i] = (float) frm.Frm().BoxCrd().FracCell()[i];
}
boxinfo = 2;
break;
case ImageOption::ORTHO:
recip = new float[9];
recip[0] = frm.Frm().BoxCrd().Param(Box::X);
recip[1] = frm.Frm().BoxCrd().Param(Box::Y);
recip[2] = frm.Frm().BoxCrd().Param(Box::Z);
ucell = NULL;
boxinfo = 1;
break;
case ImageOption::NO_IMAGE:
recip = NULL;
ucell = NULL;
boxinfo = 0;
break;
default:
mprinterr("Error: Unexpected box information found.");
return;
}
std::vector<int> result_o = std::vector<int>(4 * this->numberAtoms_);
std::vector<int> result_n = std::vector<int>(this->numberAtoms_);
// Call the GPU Wrapper, which subsequently calls the kernel, after setup operations.
// Must create arrays from the vectors, does that by getting the address of the first element of the vector.
std::vector<std::vector<float> > e_result = doActionCudaEnergy(frm.Frm().xAddress(), this->NBindex_c_, this->numberAtomTypes_, this->paramsLJ_c_, this->molecule_c_, boxinfo, recip, ucell, this->numberAtoms_, this->min_c_,
this->max_c_, this->headAtomType_,this->NeighborCut2_, &(result_o[0]), &(result_n[0]), this->result_w_c_,
this->result_s_c_, this->result_O_c_, this->result_N_c_, this->doOrder_);
eww_result = e_result.at(0);
esw_result = e_result.at(1);
if (this->doOrder_) {
int counter = 0;
for (unsigned int i = 0; i < (4 * this->numberAtoms_); i += 4) {
++counter;
std::vector<int> temp;
for (unsigned int j = 0; j < 4; ++j) {
temp.push_back(result_o.at(i + j));
}
order_indices.push_back(temp);
}
}
delete[] recip; // Free memory
delete[] ucell; // Free memory
for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++) {
int headAtomIndex = O_idxs_[sidx];
size_t bin_i, bin_j, bin_k;
const double *vec = frm.Frm().XYZ(headAtomIndex);
int voxel = -1;
if (this->gO_->Bin().Calc(vec[0], vec[1], vec[2], bin_i, bin_j, bin_k)) {
voxel = this->gO_->CalcIndex(bin_i, bin_j, bin_k);
this->neighbor_.at(0).at(voxel) += result_n.at(headAtomIndex);
// This is not nice, as it assumes that O is set before the two Hydrogens
// might be the case, but is still not nice (in my opinion)
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
this->Esw_->UpdateVoxel(voxel, esw_result.at(headAtomIndex + IDX));
this->Eww_->UpdateVoxel(voxel, eww_result.at(headAtomIndex + IDX));
}
// Order calculation
if (this->doOrder_) {
double sum = 0;
Vec3 cent( frm.Frm().xAddress() + (headAtomIndex) * 3 );
std::vector<Vec3> vectors;
switch(imageOpt_.ImagingType()) {
case ImageOption::NONORTHO:
case ImageOption::ORTHO:
{
Vec3 vec(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
}
break;
default:
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3) ) - cent );
}
for (int i = 0; i < 3; ++i) {
for (int j = i + 1; j < 4; ++j) {
double cosThet = (vectors.at(i) * vectors.at(j)) / sqrt(vectors.at(i).Magnitude2() * vectors.at(j).Magnitude2());
sum += (cosThet + 1.0/3) * (cosThet + 1.0/3);
}
}
this->order_norm_->UpdateVoxel(voxel, 1.0 - (3.0/8.0) * sum);
}
}
}
this->gist_nonbond_.Stop();
}
/**
* Frees all the Memory on the GPU.
*/
void Action_GIST::freeGPUMemory(void) {
freeCuda(this->NBindex_c_);
freeCuda(this->molecule_c_);
freeCuda(this->paramsLJ_c_);
freeCuda(this->max_c_);
freeCuda(this->min_c_);
freeCuda(this->result_w_c_);
freeCuda(this->result_s_c_);
freeCuda(this->result_O_c_);
freeCuda(this->result_N_c_);
this->NBindex_c_ = NULL;
this->molecule_c_ = NULL;
this->paramsLJ_c_ = NULL;
this->max_c_ = NULL;
this->min_c_ = NULL;
this->result_w_c_= NULL;
this->result_s_c_= NULL;
this->result_O_c_ = NULL;
this->result_N_c_ = NULL;
}
/**
* Copies data from the CPU to the GPU.
* @throws: CudaException
*/
void Action_GIST::copyToGPU(void) {
try {
copyMemoryToDevice(&(this->NBIndex_[0]), this->NBindex_c_, this->NBIndex_.size() * sizeof(int));
<API key>(&(this->charges_[0]), &(this->atomTypes_[0]), this->solvent_, &(this->molecule_[0]), this->numberAtoms_, &(this->molecule_c_),
&(this->lJParamsA_[0]), &(this->lJParamsB_[0]), this->lJParamsA_.size(), &(this->paramsLJ_c_));
} catch (CudaException &ce) {
this->freeGPUMemory();
mprinterr("Error: Could not copy data to the device.\n");
throw ce;
} catch (std::exception &e) {
this->freeGPUMemory();
throw e;
}
}
#endif
|
<?php
if (!defined('KT_KIWITREES')) {
header('HTTP/1.0 403 Forbidden');
exit;
}
// add new custom_lang table
self::exec(
"CREATE TABLE IF NOT EXISTS `##custom_lang`(".
" custom_lang_id INTEGER NOT NULL AUTO_INCREMENT,".
" language VARCHAR(10) NOT NULL,".
" standard_text LONGTEXT NOT NULL,".
" custom_text LONGTEXT NOT NULL,".
" updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,".
" PRIMARY KEY (custom_lang_id)".
") COLLATE utf8_unicode_ci ENGINE=InnoDB"
);
// Update the version to indicate success
KT_Site::preference($schema_name, $next_version);
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Fri Mar 04 14:41:00 EST 2016 -->
<title><API key></title>
<meta name="date" content="2016-03-04">
<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="<API key>";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/<API key>.html">Use</a></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><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/<API key>.html" title="class in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?edu/towson/cis/cosc603/project2/monopoly/gui/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">edu.towson.cis.cosc603.project2.monopoly.gui</div>
<h2 title="Class <API key>" class="title">Class <API key></h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>edu.towson.cis.cosc603.project2.monopoly.gui.<API key></li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong"><API key></span>
extends java.lang.Object
implements <a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_summary">
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/<API key>.html#CHANCE_CELL_LABEL">CHANCE_CELL_LABEL</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/<API key>.html#<API key>()"><API key></a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/<API key>.html#format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">format</a></strong>(<a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/IOwnable.html" title="interface in edu.towson.cis.cosc603.project2.monopoly">IOwnable</a> cell)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_detail">
</a>
<h3>Field Detail</h3>
<a name="CHANCE_CELL_LABEL">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>CHANCE_CELL_LABEL</h4>
<pre>public static final java.lang.String CHANCE_CELL_LABEL</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#edu.towson.cis.cosc603.project2.monopoly.gui.<API key>.CHANCE_CELL_LABEL">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
</a>
<h3>Constructor Detail</h3>
<a name="<API key>()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4><API key></h4>
<pre>public <API key>()</pre>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>format</h4>
<pre>public java.lang.String format(<a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/IOwnable.html" title="interface in edu.towson.cis.cosc603.project2.monopoly">IOwnable</a> cell)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html#format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">format</a></code> in interface <code><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/<API key>.html">Use</a></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><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/<API key>.html" title="class in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?edu/towson/cis/cosc603/project2/monopoly/gui/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Text",
inherited=False,
gecko_name="TextReset",
additional_methods=[Method("has_underline", "bool"),
Method("has_overline", "bool"),
Method("has_line_through", "bool")]) %>
${helpers.single_keyword("text-overflow", "clip ellipsis")}
${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")}
<%helpers:longhand name="${'text-decoration' if product == 'servo' else '<API key>'}"
custom_cascade="${product == 'servo'}">
use cssparser::ToCss;
use std::fmt;
use values::computed::<API key>;
impl <API key> for SpecifiedValue {}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue {
pub underline: bool,
pub overline: bool,
pub line_through: bool,
// 'blink' is accepted in the parser but ignored.
// Just not blinking the text is a conforming implementation per CSS 2.1.
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut space = false;
if self.underline {
try!(dest.write_str("underline"));
space = true;
}
if self.overline {
if space {
try!(dest.write_str(" "));
}
try!(dest.write_str("overline"));
space = true;
}
if self.line_through {
if space {
try!(dest.write_str(" "));
}
try!(dest.write_str("line-through"));
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(<API key>)]
pub const none: T = super::SpecifiedValue {
underline: false, overline: false, line_through: false
};
}
#[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::none
}
none | [ underline || overline || line-through || blink ]
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
let mut result = SpecifiedValue {
underline: false, overline: false, line_through: false,
};
if input.try(|input| input.<API key>("none")).is_ok() {
return Ok(result)
}
let mut blink = false;
let mut empty = true;
while input.try(|input| {
if let Ok(ident) = input.expect_ident() {
<API key>! { ident,
"underline" => if result.underline { return Err(()) }
else { empty = false; result.underline = true },
"overline" => if result.overline { return Err(()) }
else { empty = false; result.overline = true },
"line-through" => if result.line_through { return Err(()) }
else { empty = false; result.line_through = true },
"blink" => if blink { return Err(()) }
else { empty = false; blink = true },
_ => return Err(())
}
} else {
return Err(());
}
Ok(())
}).is_ok() {
}
if !empty { Ok(result) } else { Err(()) }
}
% if product == "servo":
fn <API key><C: ComputedValues>(
_declaration: &PropertyDeclaration,
_inherited_style: &C,
context: &mut computed::Context<C>,
_seen: &mut PropertyBitField,
_cacheable: &mut bool,
_error_reporter: &mut StdBox<ParseErrorReporter + Send>) {
longhands::<API key>::<API key>(context);
}
% endif
</%helpers:longhand>
${helpers.single_keyword("<API key>",
"solid double dotted dashed wavy -moz-none",
products="gecko")}
${helpers.predefined_type(
"<API key>", "CSSColor",
"CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0 })",
products="gecko")}
|
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// although this looks a bit odd perhaps, this way we dont need to change the existing
// qlearning api much, so dont need to break anything that works already
#pragma once
#include <stdexcept>
#include <iostream>
#include <string>
#include "qlearning/QLearner.h"
#include "trainers/Trainer.h"
class ScenarioProxy : public Scenario {
public:
const int numActions;
const int planes;
const int size;
// float *perception; // NOT owned by us, dont delete
// float lastReward;
// int thisAction;
// bool isReset;
ScenarioProxy( int numActions, int planes, int size ) :
numActions(numActions), planes(planes), size(size) {
}
virtual int getPerceptionSize() {
return size;
}
virtual int getPerceptionPlanes() {
return planes;
}
virtual void getPerception( float *perception ) {
// perception = this->perception;
throw std::runtime_error("getPerception not implemented");
}
virtual void reset() {
// noop?
throw std::runtime_error("reset not implemented");
}
virtual int getNumActions() {
// std::cout << "numActions: " << numActions << std::endl;
return numActions;
// throw runtime_error("getNumActions not implemented");
}
virtual float act( int index ) {
// this->thisAction = index;
// return lastReward;
throw std::runtime_error("act not implemented");
}
virtual bool hasFinished() {
// return isReset;
throw std::runtime_error("hasFinished not implemented");
}
};
// The advantage of this over the original QLearning is that it doesnt do any callbacks
// so it should be super-easy to wrap, using Lua, Python, etc ...
class QLearner2 {
QLearner *qlearner;
ScenarioProxy *scenario;
NeuralNet *net;
// int planes;
// int size;
// int numActions;
public:
QLearner2( Trainer *trainer, NeuralNet *net, int numActions, int planes, int size ) : net(net) {
scenario = new ScenarioProxy( numActions, planes, size );
qlearner = new QLearner( trainer, scenario, net );
}
~QLearner2() {
delete qlearner;
delete scenario;
}
// QLearner2 *setPlanes( int planes ) {
// this->planes = planes;
// scenario->planes = planes;
// return this;
// QLearner2 *setSize( int size ) {
// this->size = size;
// scenario->size = size;
// return this;
// QLearner2 *setNumActions( int numActions ) {
// this->numActions = numActions;
// scenario->numActions = numActions;
// return this;
int step(double lastReward, bool wasReset, float *perception) {
// scenario->lastReward = lastReward;
// scenario->isReset = isReset;
// scenario->perception = currentPerception;
int action = qlearner->step( lastReward, wasReset, perception );
return action;
}
void setLambda( float lambda ) { qlearner->setLambda( lambda ); }
void setMaxSamples( int maxSamples ) { qlearner->setMaxSamples( maxSamples ); }
void setEpsilon( float epsilon ) { qlearner->setEpsilon( epsilon ); }
// void setLearningRate( float learningRate ) { qlearner->setLearningRate( learningRate ); }
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.