repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
quanghung0404/it2tech
components/com_easyblog/themes/wireframe/blogs/entry/fields.php
1170
<?php /** * @package EasyBlog * @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved. * @license GNU/GPL, see LICENSE.php * EasyBlog is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined('_JEXEC') or die('Unauthorized Access'); ?> <?php if ($fields) { ?> <div class="eb-entry-fields"> <?php foreach ($fields as $field) { ?> <?php if ($field->group->hasValues($post)) { ?> <h4 class="eb-section-heading reset-heading"><?php echo $field->group->getTitle();?></h4> <ul class="eb-fields-list eb-responsive reset-list"> <?php foreach ($field->fields as $customField) { ?> <?php $fieldValue = $customField->getDisplay($post); ?> <?php if ($fieldValue) { ?> <li> <label><?php echo $customField->title;?></label> <div><?php echo $fieldValue;?></div> </li> <?php } ?> <?php } ?> </ul> <?php } ?> <?php } ?> </div> <?php } ?>
gpl-2.0
lukasmonk/lucaschess
Engines/Windows/glaurung/src/pawns.cpp
11551
/* Glaurung, a UCI chess playing engine. Copyright (C) 2004-2008 Tord Romstad Glaurung is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Glaurung is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ //// //// Includes //// #include <cassert> #include <cstring> #include "pawns.h" //// //// Local definitions //// namespace { /// Constants and variables // Doubled pawn penalty by file, middle game. const Value DoubledPawnMidgamePenalty[8] = { Value(20), Value(30), Value(34), Value(34), Value(34), Value(34), Value(30), Value(20) }; // Doubled pawn penalty by file, endgame. const Value DoubledPawnEndgamePenalty[8] = { Value(35), Value(40), Value(40), Value(40), Value(40), Value(40), Value(40), Value(35) }; // Isolated pawn penalty by file, middle game. const Value IsolatedPawnMidgamePenalty[8] = { Value(20), Value(30), Value(34), Value(34), Value(34), Value(34), Value(30), Value(20) }; // Isolated pawn penalty by file, endgame. const Value IsolatedPawnEndgamePenalty[8] = { Value(35), Value(40), Value(40), Value(40), Value(40), Value(40), Value(40), Value(35) }; // Backward pawn penalty by file, middle game. const Value BackwardPawnMidgamePenalty[8] = { Value(16), Value(24), Value(27), Value(27), Value(27), Value(27), Value(24), Value(16) }; // Backward pawn penalty by file, endgame. const Value BackwardPawnEndgamePenalty[8] = { Value(28), Value(32), Value(32), Value(32), Value(32), Value(32), Value(32), Value(28) }; // Pawn chain membership bonus by file, middle game. const Value ChainMidgameBonus[8] = { Value(14), Value(16), Value(17), Value(18), Value(18), Value(17), Value(16), Value(14) }; // Pawn chain membership bonus by file, endgame. const Value ChainEndgameBonus[8] = { Value(16), Value(16), Value(16), Value(16), Value(16), Value(16), Value(16), Value(16) }; // Candidate passed pawn bonus by rank, middle game. const Value CandidateMidgameBonus[8] = { Value(0), Value(12), Value(12), Value(20), Value(40), Value(90), Value(0), Value(0) }; // Candidate passed pawn bonus by rank, endgame. const Value CandidateEndgameBonus[8] = { Value(0), Value(24), Value(24), Value(40), Value(80), Value(180), Value(0), Value(0) }; // Pawn storm tables for positions with opposite castling: const int QStormTable[64] = { 0, 0, 0, 0, 0, 0, 0, 0, -22, -22, -22, -13, -4, 0, 0, 0, -4, -9, -9, -9, -4, 0, 0, 0, 9, 18, 22, 18, 9, 0, 0, 0, 22, 31, 31, 22, 0, 0, 0, 0, 31, 40, 40, 31, 0, 0, 0, 0, 31, 40, 40, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; const int KStormTable[64] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, -13, -22, -27, -27, 0, 0, 0, -4, -9, -13, -18, -18, 0, 0, 0, 0, 9, 9, 9, 9, 0, 0, 0, 0, 9, 18, 27, 27, 0, 0, 0, 0, 9, 27, 40, 36, 0, 0, 0, 0, 0, 31, 40, 31, 0, 0, 0, 0, 0, 0, 0, 0 }; // Pawn storm open file bonuses by file: const int KStormOpenFileBonus[8] = { 45, 45, 30, 0, 0, 0, 0, 0 }; const int QStormOpenFileBonus[8] = { 0, 0, 0, 0, 0, 30, 45, 30 }; } //// //// Functions //// /// Constructor PawnInfoTable::PawnInfoTable(unsigned numOfEntries) { size = numOfEntries; entries = new PawnInfo[size]; if(entries == NULL) { std::cerr << "Failed to allocate " << (numOfEntries * sizeof(PawnInfo)) << " bytes for pawn hash table." << std::endl; exit(EXIT_FAILURE); } this->clear(); } /// Destructor PawnInfoTable::~PawnInfoTable() { delete [] entries; } /// PawnInfoTable::clear() clears the pawn hash table by setting all /// entries to 0. void PawnInfoTable::clear() { memset(entries, 0, size * sizeof(PawnInfo)); } /// PawnInfoTable::get_pawn_info() takes a position object as input, computes /// a PawnInfo object, and returns a pointer to it. The result is also /// stored in a hash table, so we don't have to recompute everything when /// the same pawn structure occurs again. PawnInfo *PawnInfoTable::get_pawn_info(const Position &pos) { assert(pos.is_ok()); Key key = pos.get_pawn_key(); int index = int(key & (size - 1)); PawnInfo *pi = entries + index; // If pi->key matches the position's pawn hash key, it means that we // have analysed this pawn structure before, and we can simply return the // information we found the last time instead of recomputing it: if(pi->key == key) return pi; // Clear the PawnInfo object, and set the key: pi->clear(); pi->key = key; Value mgValue[2] = {Value(0), Value(0)}; Value egValue[2] = {Value(0), Value(0)}; // Loop through the pawns for both colors: for(Color us = WHITE; us <= BLACK; us++) { Color them = opposite_color(us); Bitboard ourPawns = pos.pawns(us); Bitboard theirPawns = pos.pawns(them); Bitboard pawns = ourPawns; // Initialize pawn storm scores by giving bonuses for open files: for(File f = FILE_A; f <= FILE_H; f++) if(pos.file_is_half_open(us, f)) { pi->ksStormValue[us] += KStormOpenFileBonus[f]; pi->qsStormValue[us] += QStormOpenFileBonus[f]; } // Loop through all pawns of the current color and score each pawn: while(pawns) { Square s = pop_1st_bit(&pawns); File f = square_file(s); Rank r = square_rank(s); bool passed, doubled, isolated, backward, chain, candidate; int bonus; assert(pos.piece_on(s) == pawn_of_color(us)); // The file containing the pawn is not half open: pi->halfOpenFiles[us] &= ~(1 << f); // Passed, isolated or doubled pawn? passed = pos.pawn_is_passed(us, s); isolated = pos.pawn_is_isolated(us, s); doubled = pos.pawn_is_doubled(us, s); // We calculate kingside and queenside pawn storm // scores for both colors. These are used when evaluating // middle game positions with opposite side castling. // // Each pawn is given a base score given by a piece square table // (KStormTable[] or QStormTable[]). This score is increased if // there are enemy pawns on adjacent files in front of the pawn. // This is because we want to be able to open files against the // enemy king, and to avoid blocking the pawn structure (e.g. white // pawns on h6, g5, black pawns on h7, g6, f7). // Kingside pawn storms: bonus = KStormTable[relative_square(us, s)]; if(bonus > 0 && outpost_mask(us, s) & theirPawns) { switch(f) { case FILE_F: bonus += bonus / 4; break; case FILE_G: bonus += bonus / 2 + bonus / 4; break; case FILE_H: bonus += bonus / 2; break; default: break; } } pi->ksStormValue[us] += bonus; // Queenside pawn storms: bonus = QStormTable[relative_square(us, s)]; if(bonus > 0 && passed_pawn_mask(us, s) & theirPawns) { switch(f) { case FILE_A: bonus += bonus / 2; break; case FILE_B: bonus += bonus / 2 + bonus / 4; break; case FILE_C: bonus += bonus / 2; break; default: break; } } pi->qsStormValue[us] += bonus; // Member of a pawn chain? We could speed up the test a little by // introducing an array of masks indexed by color and square for doing // the test, but because everything is hashed, it probably won't make // any noticable difference. chain = (us == WHITE)? (ourPawns & neighboring_files_bb(f) & (rank_bb(r) | rank_bb(r-1))) : (ourPawns & neighboring_files_bb(f) & (rank_bb(r) | rank_bb(r+1))); // Test for backward pawn. // If the pawn is isolated, passed, or member of a pawn chain, it cannot // be backward: if(passed || isolated || chain) backward = false; // If the pawn can capture an enemy pawn, it's not backward: else if(pos.pawn_attacks(us, s) & theirPawns) backward = false; // Check for friendly pawns behind on neighboring files: else if(ourPawns & in_front_bb(them, r) & neighboring_files_bb(f)) backward = false; else { // We now know that there is no friendly pawns beside or behind this // pawn on neighboring files. We now check whether the pawn is // backward by looking in the forward direction on the neighboring // files, and seeing whether we meet a friendly or an enemy pawn first. Bitboard b; if(us == WHITE) { for(b=pos.pawn_attacks(us, s); !(b&(ourPawns|theirPawns)); b<<=8); backward = (b | (b << 8)) & theirPawns; } else { for(b=pos.pawn_attacks(us, s); !(b&(ourPawns|theirPawns)); b>>=8); backward = (b | (b >> 8)) & theirPawns; } } // Test for candidate passed pawn. candidate = (!passed && pos.file_is_half_open(them, f) && count_1s_max_15(neighboring_files_bb(f) & (in_front_bb(them, r) | rank_bb(r)) & ourPawns) - count_1s_max_15(neighboring_files_bb(f) & in_front_bb(us, r) & theirPawns) >= 0); // In order to prevent doubled passed pawns from receiving a too big // bonus, only the frontmost passed pawn on each file is considered as // a true passed pawn. if(passed && (ourPawns & squares_in_front_of(us, s))) { // candidate = true; passed = false; } // Score this pawn: Value mv = Value(0), ev = Value(0); if(isolated) { mv -= IsolatedPawnMidgamePenalty[f]; ev -= IsolatedPawnEndgamePenalty[f]; if(pos.file_is_half_open(them, f)) { mv -= IsolatedPawnMidgamePenalty[f] / 2; ev -= IsolatedPawnEndgamePenalty[f] / 2; } } if(doubled) { mv -= DoubledPawnMidgamePenalty[f]; ev -= DoubledPawnEndgamePenalty[f]; } if(backward) { mv -= BackwardPawnMidgamePenalty[f]; ev -= BackwardPawnEndgamePenalty[f]; if(pos.file_is_half_open(them, f)) { mv -= BackwardPawnMidgamePenalty[f] / 2; ev -= BackwardPawnEndgamePenalty[f] / 2; } } if(chain) { mv += ChainMidgameBonus[f]; ev += ChainEndgameBonus[f]; } if(candidate) { mv += CandidateMidgameBonus[pawn_rank(us, s)]; ev += CandidateEndgameBonus[pawn_rank(us, s)]; } mgValue[us] += mv; egValue[us] += ev; // If the pawn is passed, set the square of the pawn in the passedPawns // bitboard: if(passed) set_bit(&(pi->passedPawns), s); } } pi->mgValue = int16_t(mgValue[WHITE] - mgValue[BLACK]); pi->egValue = int16_t(egValue[WHITE] - egValue[BLACK]); return pi; }
gpl-2.0
tatsuhiro-t/aria2
src/DownloadEngine.cc
19075
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "DownloadEngine.h" #include <signal.h> #include <cstring> #include <cerrno> #include <algorithm> #include <numeric> #include <iterator> #include "StatCalc.h" #include "RequestGroup.h" #include "RequestGroupMan.h" #include "DownloadResult.h" #include "StatCalc.h" #include "LogFactory.h" #include "Logger.h" #include "SocketCore.h" #include "util.h" #include "a2functional.h" #include "DlAbortEx.h" #include "ServerStatMan.h" #include "CookieStorage.h" #include "A2STR.h" #include "AuthConfigFactory.h" #include "AuthConfig.h" #include "Request.h" #include "EventPoll.h" #include "Command.h" #include "FileAllocationEntry.h" #include "CheckIntegrityEntry.h" #include "BtProgressInfoFile.h" #include "DownloadContext.h" #include "fmt.h" #include "wallclock.h" #ifdef ENABLE_BITTORRENT # include "BtRegistry.h" #endif // ENABLE_BITTORRENT #ifdef ENABLE_WEBSOCKET # include "WebSocketSessionMan.h" #endif // ENABLE_WEBSOCKET #include "Option.h" #include "util_security.h" namespace aria2 { namespace global { // 0 ... running // 1 ... stop signal detected // 2 ... stop signal processed by DownloadEngine // 3 ... 2nd stop signal(force shutdown) detected // 4 ... 2nd stop signal processed by DownloadEngine // 5 ... main loop exited volatile sig_atomic_t globalHaltRequested = 0; } // namespace global namespace { constexpr auto DEFAULT_REFRESH_INTERVAL = 1_s; } // namespace DownloadEngine::DownloadEngine(std::unique_ptr<EventPoll> eventPoll) : eventPoll_(std::move(eventPoll)), haltRequested_(0), noWait_(true), refreshInterval_(DEFAULT_REFRESH_INTERVAL), lastRefresh_(Timer::zero()), cookieStorage_(make_unique<CookieStorage>()), #ifdef ENABLE_BITTORRENT btRegistry_(make_unique<BtRegistry>()), #endif // ENABLE_BITTORRENT #ifdef HAVE_ARES_ADDR_NODE asyncDNSServers_(nullptr), #endif // HAVE_ARES_ADDR_NODE dnsCache_(make_unique<DNSCache>()), option_(nullptr) { unsigned char sessionId[20]; util::generateRandomKey(sessionId); sessionId_.assign(&sessionId[0], &sessionId[sizeof(sessionId)]); } DownloadEngine::~DownloadEngine() { #ifdef HAVE_ARES_ADDR_NODE setAsyncDNSServers(nullptr); #endif // HAVE_ARES_ADDR_NODE } namespace { void executeCommand(std::deque<std::unique_ptr<Command>>& commands, Command::STATUS statusFilter) { size_t max = commands.size(); for (size_t i = 0; i < max; ++i) { auto com = std::move(commands.front()); commands.pop_front(); if (!com->statusMatch(statusFilter)) { com->clearIOEvents(); commands.push_back(std::move(com)); continue; } com->transitStatus(); if (com->execute()) { com.reset(); } else { com->clearIOEvents(); com.release(); } } } } // namespace namespace { class GlobalHaltRequestedFinalizer { public: GlobalHaltRequestedFinalizer(bool oneshot) : oneshot_(oneshot) {} ~GlobalHaltRequestedFinalizer() { if (!oneshot_) { global::globalHaltRequested = 5; } } private: bool oneshot_; }; } // namespace int DownloadEngine::run(bool oneshot) { GlobalHaltRequestedFinalizer ghrf(oneshot); while (!commands_.empty() || !routineCommands_.empty()) { if (!commands_.empty()) { waitData(); } noWait_ = false; global::wallclock().reset(); calculateStatistics(); if (lastRefresh_.difference(global::wallclock()) + A2_DELTA_MILLIS >= refreshInterval_) { refreshInterval_ = DEFAULT_REFRESH_INTERVAL; lastRefresh_ = global::wallclock(); executeCommand(commands_, Command::STATUS_ALL); } else { executeCommand(commands_, Command::STATUS_ACTIVE); } executeCommand(routineCommands_, Command::STATUS_ALL); afterEachIteration(); if (!noWait_ && oneshot) { return 1; } } onEndOfRun(); return 0; } void DownloadEngine::waitData() { struct timeval tv; if (noWait_) { tv.tv_sec = tv.tv_usec = 0; } else { auto t = std::chrono::duration_cast<std::chrono::microseconds>(refreshInterval_); tv.tv_sec = t.count() / 1000000; tv.tv_usec = t.count() % 1000000; } eventPoll_->poll(tv); } bool DownloadEngine::addSocketForReadCheck( const std::shared_ptr<SocketCore>& socket, Command* command) { return eventPoll_->addEvents(socket->getSockfd(), command, EventPoll::EVENT_READ); } bool DownloadEngine::deleteSocketForReadCheck( const std::shared_ptr<SocketCore>& socket, Command* command) { return eventPoll_->deleteEvents(socket->getSockfd(), command, EventPoll::EVENT_READ); } bool DownloadEngine::addSocketForWriteCheck( const std::shared_ptr<SocketCore>& socket, Command* command) { return eventPoll_->addEvents(socket->getSockfd(), command, EventPoll::EVENT_WRITE); } bool DownloadEngine::deleteSocketForWriteCheck( const std::shared_ptr<SocketCore>& socket, Command* command) { return eventPoll_->deleteEvents(socket->getSockfd(), command, EventPoll::EVENT_WRITE); } void DownloadEngine::calculateStatistics() { if (statCalc_) { statCalc_->calculateStat(this); } } void DownloadEngine::onEndOfRun() { requestGroupMan_->removeStoppedGroup(this); requestGroupMan_->closeFile(); requestGroupMan_->save(); } void DownloadEngine::afterEachIteration() { if (global::globalHaltRequested == 1) { A2_LOG_NOTICE(_("Shutdown sequence commencing..." " Press Ctrl-C again for emergency shutdown.")); requestHalt(); global::globalHaltRequested = 2; setNoWait(true); setRefreshInterval(std::chrono::milliseconds(0)); return; } if (global::globalHaltRequested == 3) { A2_LOG_NOTICE(_("Emergency shutdown sequence commencing...")); requestForceHalt(); global::globalHaltRequested = 4; setNoWait(true); setRefreshInterval(std::chrono::milliseconds(0)); return; } } void DownloadEngine::requestHalt() { haltRequested_ = std::max(haltRequested_, 1); requestGroupMan_->halt(); } void DownloadEngine::requestForceHalt() { haltRequested_ = std::max(haltRequested_, 2); requestGroupMan_->forceHalt(); } void DownloadEngine::setStatCalc(std::unique_ptr<StatCalc> statCalc) { statCalc_ = std::move(statCalc); } #ifdef ENABLE_ASYNC_DNS bool DownloadEngine::addNameResolverCheck( const std::shared_ptr<AsyncNameResolver>& resolver, Command* command) { return eventPoll_->addNameResolver(resolver, command); } bool DownloadEngine::deleteNameResolverCheck( const std::shared_ptr<AsyncNameResolver>& resolver, Command* command) { return eventPoll_->deleteNameResolver(resolver, command); } #endif // ENABLE_ASYNC_DNS void DownloadEngine::setNoWait(bool b) { noWait_ = b; } void DownloadEngine::addRoutineCommand(std::unique_ptr<Command> command) { routineCommands_.push_back(std::move(command)); } void DownloadEngine::poolSocket(const std::string& key, const SocketPoolEntry& entry) { A2_LOG_INFO(fmt("Pool socket for %s", key.c_str())); std::multimap<std::string, SocketPoolEntry>::value_type p(key, entry); socketPool_.insert(p); } void DownloadEngine::evictSocketPool() { if (socketPool_.empty()) { return; } std::multimap<std::string, SocketPoolEntry> newPool; A2_LOG_DEBUG("Scanning SocketPool and erasing timed out entry."); for (auto& elem : socketPool_) { if (!elem.second.isTimeout()) { newPool.insert(elem); } } A2_LOG_DEBUG( fmt("%lu entries removed.", static_cast<unsigned long>(socketPool_.size() - newPool.size()))); socketPool_ = std::move(newPool); } namespace { std::string createSockPoolKey(const std::string& host, uint16_t port, const std::string& username, const std::string& proxyhost, uint16_t proxyport) { std::string key; if (!username.empty()) { key += util::percentEncode(username); key += "@"; } key += fmt("%s(%u)", host.c_str(), port); if (!proxyhost.empty()) { key += fmt("/%s(%u)", proxyhost.c_str(), proxyport); } return key; } } // namespace void DownloadEngine::poolSocket(const std::string& ipaddr, uint16_t port, const std::string& username, const std::string& proxyhost, uint16_t proxyport, const std::shared_ptr<SocketCore>& sock, const std::string& options, std::chrono::seconds timeout) { SocketPoolEntry e(sock, options, std::move(timeout)); poolSocket(createSockPoolKey(ipaddr, port, username, proxyhost, proxyport), e); } void DownloadEngine::poolSocket(const std::string& ipaddr, uint16_t port, const std::string& proxyhost, uint16_t proxyport, const std::shared_ptr<SocketCore>& sock, std::chrono::seconds timeout) { SocketPoolEntry e(sock, std::move(timeout)); poolSocket(createSockPoolKey(ipaddr, port, A2STR::NIL, proxyhost, proxyport), e); } namespace { bool getPeerInfo(Endpoint& res, const std::shared_ptr<SocketCore>& socket) { try { res = socket->getPeerInfo(); return true; } catch (RecoverableException& e) { // socket->getPeerInfo() can fail if the socket has been // disconnected. A2_LOG_INFO_EX("Getting peer info failed. Pooling socket canceled.", e); return false; } } } // namespace void DownloadEngine::poolSocket(const std::shared_ptr<Request>& request, const std::shared_ptr<Request>& proxyRequest, const std::shared_ptr<SocketCore>& socket, std::chrono::seconds timeout) { if (proxyRequest) { // If proxy is defined, then pool socket with its hostname. poolSocket(request->getHost(), request->getPort(), proxyRequest->getHost(), proxyRequest->getPort(), socket, std::move(timeout)); return; } Endpoint peerInfo; if (getPeerInfo(peerInfo, socket)) { poolSocket(peerInfo.addr, peerInfo.port, A2STR::NIL, 0, socket, std::move(timeout)); } } void DownloadEngine::poolSocket(const std::shared_ptr<Request>& request, const std::string& username, const std::shared_ptr<Request>& proxyRequest, const std::shared_ptr<SocketCore>& socket, const std::string& options, std::chrono::seconds timeout) { if (proxyRequest) { // If proxy is defined, then pool socket with its hostname. poolSocket(request->getHost(), request->getPort(), username, proxyRequest->getHost(), proxyRequest->getPort(), socket, options, std::move(timeout)); return; } Endpoint peerInfo; if (getPeerInfo(peerInfo, socket)) { poolSocket(peerInfo.addr, peerInfo.port, username, A2STR::NIL, 0, socket, options, std::move(timeout)); } } std::multimap<std::string, DownloadEngine::SocketPoolEntry>::iterator DownloadEngine::findSocketPoolEntry(const std::string& key) { std::pair<std::multimap<std::string, SocketPoolEntry>::iterator, std::multimap<std::string, SocketPoolEntry>::iterator> range = socketPool_.equal_range(key); for (auto i = range.first, eoi = range.second; i != eoi; ++i) { const SocketPoolEntry& e = (*i).second; // We assume that if socket is readable it means peer shutdowns // connection and the socket will receive EOF. So skip it. if (!e.isTimeout() && !e.getSocket()->isReadable(0)) { A2_LOG_INFO(fmt("Found socket for %s", key.c_str())); return i; } } return socketPool_.end(); } std::shared_ptr<SocketCore> DownloadEngine::popPooledSocket(const std::string& ipaddr, uint16_t port, const std::string& proxyhost, uint16_t proxyport) { std::shared_ptr<SocketCore> s; auto i = findSocketPoolEntry( createSockPoolKey(ipaddr, port, A2STR::NIL, proxyhost, proxyport)); if (i != socketPool_.end()) { s = (*i).second.getSocket(); socketPool_.erase(i); } return s; } std::shared_ptr<SocketCore> DownloadEngine::popPooledSocket(std::string& options, const std::string& ipaddr, uint16_t port, const std::string& username, const std::string& proxyhost, uint16_t proxyport) { std::shared_ptr<SocketCore> s; auto i = findSocketPoolEntry( createSockPoolKey(ipaddr, port, username, proxyhost, proxyport)); if (i != socketPool_.end()) { s = (*i).second.getSocket(); options = (*i).second.getOptions(); socketPool_.erase(i); } return s; } std::shared_ptr<SocketCore> DownloadEngine::popPooledSocket(const std::vector<std::string>& ipaddrs, uint16_t port) { std::shared_ptr<SocketCore> s; for (const auto& ipaddr : ipaddrs) { s = popPooledSocket(ipaddr, port, A2STR::NIL, 0); if (s) { break; } } return s; } std::shared_ptr<SocketCore> DownloadEngine::popPooledSocket(std::string& options, const std::vector<std::string>& ipaddrs, uint16_t port, const std::string& username) { std::shared_ptr<SocketCore> s; for (const auto& ipaddr : ipaddrs) { s = popPooledSocket(options, ipaddr, port, username, A2STR::NIL, 0); if (s) { break; } } return s; } DownloadEngine::SocketPoolEntry::SocketPoolEntry( const std::shared_ptr<SocketCore>& socket, const std::string& options, std::chrono::seconds timeout) : socket_(socket), options_(options), timeout_(std::move(timeout)) { } DownloadEngine::SocketPoolEntry::SocketPoolEntry( const std::shared_ptr<SocketCore>& socket, std::chrono::seconds timeout) : socket_(socket), timeout_(std::move(timeout)) { } DownloadEngine::SocketPoolEntry::~SocketPoolEntry() = default; bool DownloadEngine::SocketPoolEntry::isTimeout() const { return registeredTime_.difference(global::wallclock()) >= timeout_; } cuid_t DownloadEngine::newCUID() { return cuidCounter_.newID(); } const std::string& DownloadEngine::findCachedIPAddress(const std::string& hostname, uint16_t port) const { return dnsCache_->find(hostname, port); } void DownloadEngine::cacheIPAddress(const std::string& hostname, const std::string& ipaddr, uint16_t port) { dnsCache_->put(hostname, ipaddr, port); } void DownloadEngine::markBadIPAddress(const std::string& hostname, const std::string& ipaddr, uint16_t port) { dnsCache_->markBad(hostname, ipaddr, port); } void DownloadEngine::removeCachedIPAddress(const std::string& hostname, uint16_t port) { dnsCache_->remove(hostname, port); } void DownloadEngine::setAuthConfigFactory( std::unique_ptr<AuthConfigFactory> factory) { authConfigFactory_ = std::move(factory); } const std::unique_ptr<AuthConfigFactory>& DownloadEngine::getAuthConfigFactory() const { return authConfigFactory_; } const std::unique_ptr<CookieStorage>& DownloadEngine::getCookieStorage() const { return cookieStorage_; } void DownloadEngine::setRefreshInterval(std::chrono::milliseconds interval) { refreshInterval_ = std::move(interval); } void DownloadEngine::addCommand(std::vector<std::unique_ptr<Command>> commands) { commands_.insert(commands_.end(), std::make_move_iterator(std::begin(commands)), std::make_move_iterator(std::end(commands))); } void DownloadEngine::addCommand(std::unique_ptr<Command> command) { commands_.push_back(std::move(command)); } void DownloadEngine::setRequestGroupMan(std::unique_ptr<RequestGroupMan> rgman) { requestGroupMan_ = std::move(rgman); } void DownloadEngine::setFileAllocationMan( std::unique_ptr<FileAllocationMan> faman) { fileAllocationMan_ = std::move(faman); } void DownloadEngine::setCheckIntegrityMan( std::unique_ptr<CheckIntegrityMan> ciman) { checkIntegrityMan_ = std::move(ciman); } #ifdef HAVE_ARES_ADDR_NODE void DownloadEngine::setAsyncDNSServers(ares_addr_node* asyncDNSServers) { ares_addr_node* node = asyncDNSServers_; while (node) { ares_addr_node* next = node->next; delete node; node = next; } asyncDNSServers_ = asyncDNSServers; } #endif // HAVE_ARES_ADDR_NODE #ifdef ENABLE_WEBSOCKET void DownloadEngine::setWebSocketSessionMan( std::unique_ptr<rpc::WebSocketSessionMan> wsman) { webSocketSessionMan_ = std::move(wsman); } #endif // ENABLE_WEBSOCKET bool DownloadEngine::validateToken(const std::string& token) { using namespace util::security; if (!option_->defined(PREF_RPC_SECRET)) { return true; } if (!tokenHMAC_) { tokenHMAC_ = HMAC::createRandom(); if (!tokenHMAC_) { A2_LOG_ERROR("Failed to create HMAC"); return false; } tokenExpected_ = make_unique<HMACResult>( tokenHMAC_->getResult(option_->get(PREF_RPC_SECRET))); } return *tokenExpected_ == tokenHMAC_->getResult(token); } } // namespace aria2
gpl-2.0
qoswork/opennmszh
opennms-provision/opennms-detector-lineoriented/src/test/java/org/opennms/netmgt/provision/detector/NotesDetectorTest.java
8380
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.provision.detector; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.opennms.core.test.MockLogAppender; import org.opennms.core.utils.BeanUtils; import org.opennms.netmgt.provision.DetectFuture; import org.opennms.netmgt.provision.detector.simple.NotesHttpDetector; import org.opennms.netmgt.provision.server.SimpleServer; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:/META-INF/opennms/detectors.xml"}) public class NotesDetectorTest implements InitializingBean { @Autowired private NotesHttpDetector m_detector; private SimpleServer m_server; private String headers = "HTTP/1.1 200 OK\r\n" + "Date: Tue, 28 Oct 2008 20:47:55 GMT\r\n" + "Server: Apache/2.0.54\r\n" + "Last-Modified: Fri, 16 Jun 2006 01:52:14 GMT\r\n" + "ETag: \"778216aa-2f-aa66cf80\"\r\n" + "Accept-Ranges: bytes\r\n" + "Vary: Accept-Encoding,User-Agent\r\n" + "Connection: close\r\n" + "Content-Type: text/html\r\n" + "Lotus\r\n"; private String serverContent = ""; private String serverOKResponse = headers + String.format("Content-Length: %s\r\n", serverContent.length()) + "\r\n" + serverContent; private String notFoundResponse = "HTTP/1.1 404 Not Found\r\n" + "Date: Tue, 28 Oct 2008 20:47:55 GMT\r\n" + "Server: Apache/2.0.54\r\n" + "Last-Modified: Fri, 16 Jun 2006 01:52:14 GMT\r\n" + "ETag: \"778216aa-2f-aa66cf80\"\r\n" + "Accept-Ranges: bytes\r\n" + "Content-Length: 52\r\n" + "Vary: Accept-Encoding,User-Agent\r\n" + "Connection: close\rn" + "Content-Type: text/html\r\n" + "\r\n" + "<html>\r\n" + "<body>\r\n" + "<!-- default -->\r\n" + "</body>\r\n" + "</html>"; private String notAServerResponse = "NOT A SERVER"; @Override public void afterPropertiesSet() throws Exception { BeanUtils.assertAutowiring(this); } @Before public void setUp() throws Exception { MockLogAppender.setupLogging(); } @After public void tearDown() throws IOException { if(m_server != null) { m_server.stopServer(); m_server = null; } } @Test(timeout=90000) public void testDetectorFailNotAServerResponse() throws Exception { m_detector.init(); m_server = createServer(notAServerResponse); m_detector.setPort(m_server.getLocalPort()); assertFalse(doCheck(m_detector.isServiceDetected(m_server.getInetAddress()))); } @Test(timeout=90000) public void testDetectorFailNotFoundResponseMaxRetCode399() throws Exception { m_detector.setCheckRetCode(true); m_detector.setUrl("/blog"); m_detector.setMaxRetCode(301); m_detector.init(); m_server = createServer(notFoundResponse); m_detector.setPort(m_server.getLocalPort()); assertFalse(doCheck(m_detector.isServiceDetected(m_server.getInetAddress()))); } @Test(timeout=90000) public void testDetectorSucessMaxRetCode399() throws Exception { m_detector.setCheckRetCode(true); m_detector.setUrl("/blog"); m_detector.setMaxRetCode(399); m_detector.init(); m_server = createServer(getServerOKResponse()); m_detector.setPort(m_server.getLocalPort()); assertTrue(doCheck(m_detector.isServiceDetected(m_server.getInetAddress()))); } @Test(timeout=90000) public void testDetectorFailMaxRetCodeBelow200() throws Exception { m_detector.setCheckRetCode(true); m_detector.setUrl("/blog"); m_detector.setMaxRetCode(199); m_detector.init(); m_server = createServer(getServerOKResponse()); m_detector.setPort(m_server.getLocalPort()); assertFalse(doCheck(m_detector.isServiceDetected(m_server.getInetAddress()))); } @Test(timeout=90000) public void testDetectorMaxRetCode600() throws Exception { m_detector.setCheckRetCode(true); m_detector.setMaxRetCode(600); m_detector.init(); m_server = createServer(getServerOKResponse()); m_detector.setPort(m_server.getLocalPort()); assertTrue(doCheck(m_detector.isServiceDetected(m_server.getInetAddress()))); } @Test(timeout=90000) public void testDetectorSucessCheckCodeTrue() throws Exception { m_detector.setCheckRetCode(true); m_detector.setUrl("http://localhost/"); m_detector.init(); m_server = createServer(getServerOKResponse()); m_detector.setPort(m_server.getLocalPort()); assertTrue(doCheck(m_detector.isServiceDetected(m_server.getInetAddress()))); } @Test(timeout=90000) public void testDetectorSuccessCheckCodeFalse() throws Exception { m_detector.setCheckRetCode(false); m_detector.init(); m_server = createServer(getServerOKResponse()); m_detector.setPort(m_server.getLocalPort()); assertTrue(doCheck(m_detector.isServiceDetected(m_server.getInetAddress()))); } public void setServerOKResponse(String serverOKResponse) { this.serverOKResponse = serverOKResponse; } public String getServerOKResponse() { return serverOKResponse; } private SimpleServer createServer(final String httpResponse) throws Exception { SimpleServer server = new SimpleServer() { public void onInit() { //addResponseHandler(contains("GET"), shutdownServer(httpResponse)); addResponseHandler(contains("HEAD"), shutdownServer(httpResponse)); } }; server.init(); server.startServer(); return server; } private boolean doCheck(DetectFuture future) throws InterruptedException { future.awaitFor(); return future.isServiceDetected(); } }
gpl-2.0
deshbandhu-renovite/receipt-eCommerce
node_modules/skipper-disk/standalone/build-disk-receiver-stream.js
5194
/** * Module dependencies */ var WritableStream = require('stream').Writable; var path = require('path'); var _ = require('lodash'); var fsx = require('fs-extra'); var r_buildProgressStream = require('./build-progress-stream'); var debug = require('debug')('skipper-disk'); var util = require('util'); /** * A simple receiver for Skipper that writes Upstreams to * disk at the configured path. * * Includes a garbage-collection mechanism for failed * uploads. * * @param {Object} options * @return {Stream.Writable} */ module.exports = function buildDiskReceiverStream(options, adapter) { options = options || {}; var log = options.log || function noOpLog(){}; // if maxBytes is configed in "MB" ended string // convert it into bytes if (options.maxBytes) { var _maxBytesRegResult = (options.maxBytes + '').match(/(\d+)m/i); if (_maxBytesRegResult != null){ options.maxBytes = _maxBytesRegResult[1] * 1024 * 1024; } }; _.defaults(options, { // // The default `saveAs` implements a unique filename by combining: // // • a generated UUID (like "4d5f444-38b4-4dc3-b9c3-74cb7fbbc932") // // • the uploaded file's original extension (like ".jpg") // saveAs: function(__newFile, cb) { // return cb(null, UUIDGenerator.v4() + path.extname(__newFile.filename)); // }, // Bind a progress event handler, e.g.: // function (milestone) { // milestone.id; // milestone.name; // milestone.written; // milestone.total; // milestone.percent; // }, onProgress: undefined, // Upload limit (in bytes) // defaults to ~15MB maxBytes: 15000000, // By default, upload files to `./.tmp/uploads` (relative to cwd) dirname: '.tmp/uploads' }); var receiver__ = WritableStream({ objectMode: true }); // if onProgress handler was provided, bind an event automatically: if (_.isFunction(options.onProgress)) { receiver__.on('progress', options.onProgress); } // Track the progress of all file uploads that pass through this receiver // through one or more attached Upstream(s). receiver__._files = []; // Keep track of the number total bytes written so that maxBytes can // be enforced. var totalBytesWritten = 0; // This `_write` method is invoked each time a new file is received // from the Readable stream (Upstream) which is pumping filestreams // into this receiver. (filename === `__newFile.filename`). receiver__._write = function onFile(__newFile, encoding, done) { // `__newFile.fd` is the file descriptor-- the unique identifier. // Often represents the location where file should be written. // If fd DOESNT have leading slash, resolve the path // from process.cwd() if (!__newFile.fd.match(/^\//)) { __newFile.fd = path.resolve(process.cwd(), '.tmp/uploads', __newFile.fd); } // Ensure necessary parent directories exist: fsx.mkdirs(path.dirname(__newFile.fd), function(mkdirsErr) { // If we get an error here, it's probably because the Node // user doesn't have write permissions at the designated // path. if (mkdirsErr) { return done(mkdirsErr); } // Error reading from the file stream debug('binding error handler for incoming file in skipper-disk'); __newFile.on('error', function(err) { debug('Read error on file '+__newFile.filename+ '::'+ util.inspect(err&&err.stack)); log('***** READ error on file ' + __newFile.filename, '::', err); }); // Create a new write stream to write to disk var outs__ = fsx.createWriteStream(__newFile.fd, encoding); // When the file is done writing, call the callback outs__.on('finish', function successfullyWroteFile() { log('finished file: ' + __newFile.filename); // File the file entry in the receiver with the same fd as the finished stream. var file = _.find(receiver__._files, {fd: __newFile.fd}); if (file) { // Set the byteCount of the stream to the "total" value of the file, which has // been updated as the file was written. __newFile.byteCount = file.total; } // If we couldn't find the file in the receiver, that's super weird, but output // a notice and try to continue anyway. else { debug('Warning: received `finish` event for file `' + __newFile.filename + '` uploaded via field `' + __newFile.field + '`, but could not find a record of that file in the receiver.'); debug('Was this a zero-byte file?'); debug('Attempting to return the file anyway...'); } // Indicate that a file was persisted. receiver__.emit('writefile', __newFile); done(); }); outs__.on('E_EXCEEDS_UPLOAD_LIMIT', function (err) { done(err); }); var __progress__ = r_buildProgressStream(options, __newFile, receiver__, outs__, adapter); // Finally pipe the progress THROUGH the progress stream // and out to disk. __newFile .pipe(__progress__) .pipe(outs__); }); }; return receiver__; }; // </DiskReceiver>
gpl-3.0
simon-jouet/Marlin
Marlin/src/feature/mixing.cpp
5372
/** * Marlin 3D Printer Firmware * Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfig.h" #if ENABLED(MIXING_EXTRUDER) //#define MIXER_NORMALIZER_DEBUG #include "mixing.h" Mixer mixer; #ifdef MIXER_NORMALIZER_DEBUG #include "../core/serial.h" #endif // Used up to Planner level uint_fast8_t Mixer::selected_vtool = 0; float Mixer::collector[MIXING_STEPPERS]; // mix proportion. 0.0 = off, otherwise <= COLOR_A_MASK. mixer_comp_t Mixer::color[NR_MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; // Used in Stepper int_fast8_t Mixer::runner = 0; mixer_comp_t Mixer::s_color[MIXING_STEPPERS]; mixer_accu_t Mixer::accu[MIXING_STEPPERS] = { 0 }; #if DUAL_MIXING_EXTRUDER || ENABLED(GRADIENT_MIX) mixer_perc_t Mixer::mix[MIXING_STEPPERS]; #endif void Mixer::normalize(const uint8_t tool_index) { float cmax = 0; #ifdef MIXER_NORMALIZER_DEBUG float csum = 0; #endif MIXER_STEPPER_LOOP(i) { const float v = collector[i]; NOLESS(cmax, v); #ifdef MIXER_NORMALIZER_DEBUG csum += v; #endif } #ifdef MIXER_NORMALIZER_DEBUG SERIAL_ECHOPGM("Mixer: Old relation : [ "); MIXER_STEPPER_LOOP(i) { SERIAL_ECHO_F(collector[i] / csum, 3); SERIAL_CHAR(' '); } SERIAL_ECHOLNPGM("]"); #endif // Scale all values so their maximum is COLOR_A_MASK const float scale = float(COLOR_A_MASK) / cmax; MIXER_STEPPER_LOOP(i) color[tool_index][i] = collector[i] * scale; #ifdef MIXER_NORMALIZER_DEBUG csum = 0; SERIAL_ECHOPGM("Mixer: Normalize to : [ "); MIXER_STEPPER_LOOP(i) { SERIAL_ECHO(uint16_t(color[tool_index][i])); SERIAL_CHAR(' '); csum += color[tool_index][i]; } SERIAL_ECHOLNPGM("]"); SERIAL_ECHOPGM("Mixer: New relation : [ "); MIXER_STEPPER_LOOP(i) { SERIAL_ECHO_F(uint16_t(color[tool_index][i]) / csum, 3); SERIAL_CHAR(' '); } SERIAL_ECHOLNPGM("]"); #endif #if ENABLED(GRADIENT_MIX) refresh_gradient(); #endif } void Mixer::reset_vtools() { // Virtual Tools 0, 1, 2, 3 = Filament 1, 2, 3, 4, etc. // Every virtual tool gets a pure filament for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS && t < MIXING_STEPPERS; t++) MIXER_STEPPER_LOOP(i) color[t][i] = (t == i) ? COLOR_A_MASK : 0; // Remaining virtual tools are 100% filament 1 #if MIXING_VIRTUAL_TOOLS > MIXING_STEPPERS for (uint8_t t = MIXING_STEPPERS; t < MIXING_VIRTUAL_TOOLS; t++) MIXER_STEPPER_LOOP(i) color[t][i] = (i == 0) ? COLOR_A_MASK : 0; #endif } // called at boot void Mixer::init() { reset_vtools(); #if ENABLED(RETRACT_SYNC_MIXING) // AUTORETRACT_TOOL gets the same amount of all filaments MIXER_STEPPER_LOOP(i) color[MIXER_AUTORETRACT_TOOL][i] = COLOR_A_MASK; #endif ZERO(collector); #if DUAL_MIXING_EXTRUDER || ENABLED(GRADIENT_MIX) update_mix_from_vtool(); #endif #if ENABLED(GRADIENT_MIX) update_gradient_for_planner_z(); #endif } void Mixer::refresh_collector(const float proportion/*=1.0*/, const uint8_t t/*=selected_vtool*/, float (&c)[MIXING_STEPPERS]/*=collector*/) { float csum = 0, cmax = 0; MIXER_STEPPER_LOOP(i) { const float v = color[t][i]; cmax = _MAX(cmax, v); csum += v; } //SERIAL_ECHOPAIR("Mixer::refresh_collector(", proportion, ", ", int(t), ") cmax=", cmax, " csum=", csum, " color"); const float inv_prop = proportion / csum; MIXER_STEPPER_LOOP(i) { c[i] = color[t][i] * inv_prop; //SERIAL_ECHOPAIR(" [", int(t), "][", int(i), "] = ", int(color[t][i]), " (", c[i], ") "); } //SERIAL_EOL(); } #if ENABLED(GRADIENT_MIX) #include "../module/motion.h" #include "../module/planner.h" gradient_t Mixer::gradient = { false, // enabled {0}, // color (array) 0, 0, // start_z, end_z 0, 1, // start_vtool, end_vtool {0}, {0} // start_mix[], end_mix[] #if ENABLED(GRADIENT_VTOOL) , -1 // vtool_index #endif }; float Mixer::prev_z; // = 0 void Mixer::update_gradient_for_z(const float z) { if (z == prev_z) return; prev_z = z; const float slice = gradient.end_z - gradient.start_z; float pct = (z - gradient.start_z) / slice; NOLESS(pct, 0.0f); NOMORE(pct, 1.0f); MIXER_STEPPER_LOOP(i) { const mixer_perc_t sm = gradient.start_mix[i]; mix[i] = sm + (gradient.end_mix[i] - sm) * pct; } copy_mix_to_color(gradient.color); } void Mixer::update_gradient_for_planner_z() { update_gradient_for_z(planner.get_axis_position_mm(Z_AXIS)); } #endif // GRADIENT_MIX #endif // MIXING_EXTRUDER
gpl-3.0
nickdex/cosmos
code/online_challenges/src/hackerrank/almost_sorted/almost_sorted.cpp
1100
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> int main() { int n = 0; int p = 0; int s, l; s = l = 0; int t = 0; std::cin >> n; std::vector<int> a(n); std::vector<int> b(n); for (int i; i < n; ++i) { std::cin >> a[i]; b[i] = a[i]; } std::sort(b.begin(), b.end()); for (int i = 0; i < n; ++i) { if (b[i] != a[i]) { ++p; if (t == 0) { s = i; ++t; } else l = i; } } if (p == 0) { std::cout << "yes\n"; return 0; } else if (p == 2) { std::cout << "yes" << "\n"; std::cout << "swap " << s + 1 << " " << l + 1; return 0; } for (int i = l; i > s;--i) { if (a[i] > a[i - 1]) { std::cout << "no\n"; return 0; } } std::cout << "yes \n"; std::cout << "reverse " << s + 1 << " " << l + 1; return 0; }
gpl-3.0
wiki2014/Learning-Summary
alps/cts/tests/tests/graphics/src/android/opengl/cts/EglConfigCtsActivity.java
3073
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.opengl.cts; import android.app.Activity; import android.content.Intent; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.view.WindowManager; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * {@link Activity} with a {@link GLSurfaceView} that chooses a specific configuration. */ public class EglConfigCtsActivity extends Activity { public static final String CONFIG_ID_EXTRA = "eglConfigId"; public static final String CONTEXT_CLIENT_VERSION_EXTRA = "eglContextClientVersion"; private EglConfigGLSurfaceView mView; private CountDownLatch mFinishedDrawing; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int configId = getConfigId(); int contextClientVersion = getContextClientVersion(); setTitle("EGL Config Id: " + configId + " Client Version: " + contextClientVersion); // Dismiss keyguard and keep screen on while this test is on. getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mFinishedDrawing = new CountDownLatch(1); mView = new EglConfigGLSurfaceView(this, configId, contextClientVersion, new Runnable() { @Override public void run() { mFinishedDrawing.countDown(); } }); setContentView(mView); } private int getConfigId() { Intent intent = getIntent(); if (intent != null) { return intent.getIntExtra(CONFIG_ID_EXTRA, 0); } else { return 0; } } private int getContextClientVersion() { Intent intent = getIntent(); if (intent != null) { return intent.getIntExtra(CONTEXT_CLIENT_VERSION_EXTRA, 0); } else { return 0; } } @Override protected void onResume() { super.onResume(); mView.onResume(); } @Override protected void onPause() { super.onPause(); mView.onPause(); } public void waitToFinishDrawing() throws InterruptedException { if (!mFinishedDrawing.await(3, TimeUnit.SECONDS)) { throw new IllegalStateException("Coudn't finish drawing frames!"); } } }
gpl-3.0
aroramanish63/bulmail_app
Live Backup/mycrm1/library/Zend/Search/Lucene/FSMAction.php
1660
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Search_Lucene * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: FSMAction.php 23775 2011-03-01 17:25:24Z ralph $ */ /** * Abstract Finite State Machine * * * @category Zend * @package Zend_Search_Lucene * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Search_Lucene_FSMAction { /** * Object reference * * @var object */ private $_object; /** * Method name * * @var string */ private $_method; /** * Object constructor * * @param object $object * @param string $method */ public function __construct($object, $method) { $this->_object = $object; $this->_method = $method; } public function doAction() { $methodName = $this->_method; $this->_object->$methodName(); } }
gpl-3.0
Gwynthell/FFDB
scripts/globals/items/serving_of_karni_yarik_+1.lua
1279
----------------------------------------- -- ID: 5589 -- Item: serving_of_karni_yarik_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Agility 3 -- Vitality -1 -- Attack % 20 -- Attack Cap 65 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5589); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -1); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 65); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -1); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 65); end;
gpl-3.0
0patch/Yate-YateBTS
yatebts/nib/web/ansql/set_debug.php
1335
<?php /** * set_debug.php * This file is part of the FreeSentral Project http://freesentral.com * * FreeSentral - is a Web Graphical User Interface for easy configuration of the Yate PBX software * Copyright (C) 2008-2014 Null Team * * This software is distributed under multiple licenses; * see the COPYING file in the main directory for licensing * information for this specific distribution. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ session_start(); if(isset($_SESSION["error_reporting"])) ini_set("error_reporting",$_SESSION["error_reporting"]); if(isset($_SESSION["display_errors"])) ini_set("display_errors",true); //if this was set then errors will be hidden unless set from debug_all.php page //else // ini_set("display_errors",false); if(isset($_SESSION["log_errors"])) ini_set("log_errors",$_SESSION["log_errors"]); //if this was set then errors will be logged unless set from debug_all.php page //else // ini_set("log_errors",false); if(isset($_SESSION["error_log"])) ini_set("error_log", $_SESSION["error_log"]); ?>
gpl-3.0
rimi-itk/loop-profile
themes/loop/templates/search/search-node-page-search-results.tpl.php
732
<?php /** * @file * Default template for the search results. */ ?> <div id="searchResultApp" data-ng-controller="loopResultController" data-ng-hide="no_hits_yet" class="block block-system search-result--block"> <div class="content" > <div class="contextual-links-region"> <div class="layout-full-width"> <div class="layout--inner"> <div class="layout-element-alpha"> <div data-ng-strict-di data-ng-include="template"> <p class="no-js"><?php echo t('Search requires javascript enabled'); ?></p> </div> </div> </div> </div> </div> </div> </div>
gpl-3.0
TrinityCore/WowPacketParser
WowPacketParser/Enums/TeamType.cs
341
namespace WowPacketParser.Enums { public enum TeamType { None = 0, Horde = 67, SteamwheedleCartel = 169, Alliance = 469, AllianceForces = 891, HordeForces = 892, Sanctuary = 936, Outland = 980 } }
gpl-3.0
zhinaonet/sqlmap-z
lib/core/log.py
1384
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import logging import sys from lib.core.enums import CUSTOM_LOGGING logging.addLevelName(CUSTOM_LOGGING.PAYLOAD, "PAYLOAD") logging.addLevelName(CUSTOM_LOGGING.TRAFFIC_OUT, "TRAFFIC OUT") logging.addLevelName(CUSTOM_LOGGING.TRAFFIC_IN, "TRAFFIC IN") LOGGER = logging.getLogger("sqlmapLog") LOGGER_HANDLER = None try: from thirdparty.ansistrm.ansistrm import ColorizingStreamHandler disableColor = False for argument in sys.argv: if "disable-col" in argument: disableColor = True break if disableColor: LOGGER_HANDLER = logging.StreamHandler(sys.stdout) else: LOGGER_HANDLER = ColorizingStreamHandler(sys.stdout) LOGGER_HANDLER.level_map[logging.getLevelName("PAYLOAD")] = (None, "cyan", False) LOGGER_HANDLER.level_map[logging.getLevelName("TRAFFIC OUT")] = (None, "magenta", False) LOGGER_HANDLER.level_map[logging.getLevelName("TRAFFIC IN")] = ("magenta", None, False) except ImportError: LOGGER_HANDLER = logging.StreamHandler(sys.stdout) FORMATTER = logging.Formatter("\r[%(asctime)s] [%(levelname)s] %(message)s", "%H:%M:%S") LOGGER_HANDLER.setFormatter(FORMATTER) LOGGER.addHandler(LOGGER_HANDLER) LOGGER.setLevel(logging.INFO)
gpl-3.0
myarjunar/inasafe
safe/gui/tools/help/extent_selector_help.py
6325
# coding=utf-8 """Help text for the extent selector dialog.""" from safe.utilities.i18n import tr from safe import messaging as m from safe.messaging import styles from safe.utilities.resources import resources_path SUBSECTION_STYLE = styles.SUBSECTION_LEVEL_3_STYLE INFO_STYLE = styles.BLUE_LEVEL_4_STYLE SMALL_ICON_STYLE = styles.SMALL_ICON_STYLE __author__ = 'ismailsunni' def extent_selector_help(): """Help message for extent selector dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message def heading(): """Helper method that returns just the header. This method was added so that the text could be reused in the other contexts. .. versionadded:: 3.2.2 :returns: A heading object. :rtype: safe.messaging.heading.Heading """ message = m.Heading( tr('Analysis extent selector help'), **SUBSECTION_STYLE) return message def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() paragraph = m.Paragraph( m.Image( 'file:///%s/img/screenshots/' 'analysis-area-screenshot.png' % resources_path()), style_class='text-center' ) message.add(paragraph) paragraph = m.Paragraph(tr( 'This tool allows you to specify which geographical region should be ' 'used for your analysis. If you want to check what area will be ' 'included in your analysis, enable the \'Toggle scenario outlines\' ' 'tool on the InaSAFE toolbar:'), m.Image( 'file:///%s/img/icons/' 'toggle-rubber-bands.svg' % resources_path(), **SMALL_ICON_STYLE), ) message.add(paragraph) paragraph = m.Paragraph(tr( 'Your user defined extent will be shown on the map as a rectangle. ' 'There are a number of different modes that can be used which are ' 'described below:')) message.add(paragraph) message.add(extent_mode_content()) return message def extent_mode_content(): """Helper method that returns just the content in extent mode. This method was added so that the text could be reused in the wizard. :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() header = m.Heading(tr( 'Use intersection of hazard and exposure layers'), **INFO_STYLE) message.add(header) paragraph = m.Paragraph(tr( 'The largest area that can be analysed is the intersection of the ' 'hazard and exposure layers you have added. To choose this option, ' 'click \'Use intersection of hazard and exposure layers\'. ')) message.add(paragraph) paragraph = m.Paragraph(tr( 'Sometimes it is more useful to analyse a smaller area. This could be ' 'to reduce processing time (smaller areas with process faster) or ' 'because information is only needed in a certain area (e.g. if a ' 'district only wants information for their district, not for the ' 'entire city). If you want to analyse a smaller area, there are a few ' 'different ways to do this.')) message.add(paragraph) header = m.Heading(tr( 'Use intersection of hazard, exposure and current view extent'), **INFO_STYLE) message.add(header) paragraph = m.Paragraph(tr( 'If you wish to conduct the analysis on the area currently shown in ' 'the window, you can set the analysis area to \'Use intersection of ' 'hazard, exposure and current view extent\'. If the extents of the ' 'datasets are smaller than the view extent, the analysis area will be ' 'reduced to the extents of the datasets.')) message.add(paragraph) header = m.Heading(tr( 'Use intersection of hazard, exposure and this bookmark'), **INFO_STYLE) message.add(header) paragraph = m.Paragraph(tr( 'You can also use one of your QGIS bookmarks to set the analysis ' 'area.'), m.ImportantText(tr( 'This option will be greyed out if you have no bookmarks.'))) message.add(paragraph) paragraph = m.Paragraph(tr( 'To create a bookmark, zoom to the area you want to create a bookmark ' 'for. When you are happy with the extent, click the \'New bookmark\' ' 'button in the QGIS toolbar.')) message.add(paragraph) paragraph = m.Paragraph(tr( 'The drop down menu in the InaSAFE Analysis Area window should now be ' 'activated. When you choose a bookmark from the drop down menu it ' 'will zoom to the analysis area selected by the bookmark.')) message.add(paragraph) header = m.Heading(tr( 'Use intersection of hazard, exposure and this bounding box'), **INFO_STYLE) message.add(header) paragraph = m.Paragraph(tr( 'You can also choose the analysis area interactively by clicking ' '\'Use intersection of hazard, exposure and this bounding box\'. This ' 'will allow you to click \'Drag on map\' which will temporarily hide ' 'this window and allow you to drag a rectangle on the map. After you ' 'have finished dragging the rectangle, this window will reappear with ' 'values in the North, South, East and West boxes. If the extents of ' 'the datasets are smaller than the user defined analysis area, the ' 'analysis area will be reduced to the extents of the datasets.')) message.add(paragraph) paragraph = m.Paragraph(tr( 'Alternatively, you can enter the coordinates directly into the ' 'N/S/E/W boxes once the \'Use intersection of hazard, exposure and ' 'this bounding box\' option is selected (using the same coordinate ' 'reference system, or CRS, as the map is currently set).')) message.add(paragraph) return message
gpl-3.0
dsibournemouth/autoweka
weka-3.7.7/src/main/java/weka/filters/unsupervised/instance/RemoveMisclassified.java
21510
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * RemoveMisclassified.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.filters.unsupervised.instance; import java.util.Enumeration; import java.util.Vector; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.core.Capabilities; import weka.core.Instance; import weka.core.Instances; import weka.core.Option; import weka.core.OptionHandler; import weka.core.RevisionUtils; import weka.core.Utils; import weka.filters.Filter; import weka.filters.UnsupervisedFilter; /** <!-- globalinfo-start --> * A filter that removes instances which are incorrectly classified. Useful for removing outliers. * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -W &lt;classifier specification&gt; * Full class name of classifier to use, followed * by scheme options. eg: * "weka.classifiers.bayes.NaiveBayes -D" * (default: weka.classifiers.rules.ZeroR)</pre> * * <pre> -C &lt;class index&gt; * Attribute on which misclassifications are based. * If &lt; 0 will use any current set class or default to the last attribute.</pre> * * <pre> -F &lt;number of folds&gt; * The number of folds to use for cross-validation cleansing. * (&lt;2 = no cross-validation - default).</pre> * * <pre> -T &lt;threshold&gt; * Threshold for the max error when predicting numeric class. * (Value should be &gt;= 0, default = 0.1).</pre> * * <pre> -I * The maximum number of cleansing iterations to perform. * (&lt;1 = until fully cleansed - default)</pre> * * <pre> -V * Invert the match so that correctly classified instances are discarded. * </pre> * <!-- options-end --> * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision: 8034 $ */ public class RemoveMisclassified extends Filter implements UnsupervisedFilter, OptionHandler { /** for serialization */ static final long serialVersionUID = 5469157004717663171L; /** The classifier used to do the cleansing */ protected Classifier m_cleansingClassifier = new weka.classifiers.rules.ZeroR(); /** The attribute to treat as the class for purposes of cleansing. */ protected int m_classIndex = -1; /** The number of cross validation folds to perform (&lt;2 = no cross validation) */ protected int m_numOfCrossValidationFolds = 0; /** The maximum number of cleansing iterations to perform (&lt;1 = until fully cleansed) */ protected int m_numOfCleansingIterations = 0; /** The threshold for deciding when a numeric value is correctly classified */ protected double m_numericClassifyThreshold = 0.1; /** Whether to invert the match so the correctly classified instances are discarded */ protected boolean m_invertMatching = false; /** Have we processed the first batch (i.e. training data)? */ protected boolean m_firstBatchFinished = false; /** * Returns the Capabilities of this filter. * * @return the capabilities of this object * @see Capabilities */ public Capabilities getCapabilities() { Capabilities result; if (getClassifier() == null) { result = super.getCapabilities(); result.disableAll(); } else { result = getClassifier().getCapabilities(); } result.setMinimumNumberInstances(0); return result; } /** * Sets the format of the input instances. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - only the * structure is required). * @return true if the outputFormat may be collected immediately * @throws Exception if the inputFormat can't be set successfully */ public boolean setInputFormat(Instances instanceInfo) throws Exception { super.setInputFormat(instanceInfo); setOutputFormat(instanceInfo); m_firstBatchFinished = false; return true; } /** * Cleanses the data based on misclassifications when used training data. * * @param data the data to train with and cleanse * @return the cleansed data * @throws Exception if something goes wrong */ private Instances cleanseTrain(Instances data) throws Exception { Instance inst; Instances buildSet = new Instances(data); Instances temp = new Instances(data, data.numInstances()); Instances inverseSet = new Instances(data, data.numInstances()); int count = 0; double ans; int iterations = 0; int classIndex = m_classIndex; if (classIndex < 0) classIndex = data.classIndex(); if (classIndex < 0) classIndex = data.numAttributes()-1; // loop until perfect while(count != buildSet.numInstances()) { // check if hit maximum number of iterations iterations++; if (m_numOfCleansingIterations > 0 && iterations > m_numOfCleansingIterations) break; // build classifier count = buildSet.numInstances(); buildSet.setClassIndex(classIndex); m_cleansingClassifier.buildClassifier(buildSet); temp = new Instances(buildSet, buildSet.numInstances()); // test on training data for (int i = 0; i < buildSet.numInstances(); i++) { inst = buildSet.instance(i); ans = m_cleansingClassifier.classifyInstance(inst); if (buildSet.classAttribute().isNumeric()) { if (ans >= inst.classValue() - m_numericClassifyThreshold && ans <= inst.classValue() + m_numericClassifyThreshold) { temp.add(inst); } else if (m_invertMatching) { inverseSet.add(inst); } } else { //class is nominal if (ans == inst.classValue()) { temp.add(inst); } else if (m_invertMatching) { inverseSet.add(inst); } } } buildSet = temp; } if (m_invertMatching) { inverseSet.setClassIndex(data.classIndex()); return inverseSet; } else { buildSet.setClassIndex(data.classIndex()); return buildSet; } } /** * Cleanses the data based on misclassifications when performing cross-validation. * * @param data the data to train with and cleanse * @return the cleansed data * @throws Exception if something goes wrong */ private Instances cleanseCross(Instances data) throws Exception { Instance inst; Instances crossSet = new Instances(data); Instances temp = new Instances(data, data.numInstances()); Instances inverseSet = new Instances(data, data.numInstances()); int count = 0; double ans; int iterations = 0; int classIndex = m_classIndex; if (classIndex < 0) classIndex = data.classIndex(); if (classIndex < 0) classIndex = data.numAttributes()-1; // loop until perfect while (count != crossSet.numInstances() && crossSet.numInstances() >= m_numOfCrossValidationFolds) { count = crossSet.numInstances(); // check if hit maximum number of iterations iterations++; if (m_numOfCleansingIterations > 0 && iterations > m_numOfCleansingIterations) break; crossSet.setClassIndex(classIndex); if (crossSet.classAttribute().isNominal()) { crossSet.stratify(m_numOfCrossValidationFolds); } // do the folds temp = new Instances(crossSet, crossSet.numInstances()); for (int fold = 0; fold < m_numOfCrossValidationFolds; fold++) { Instances train = crossSet.trainCV(m_numOfCrossValidationFolds, fold); m_cleansingClassifier.buildClassifier(train); Instances test = crossSet.testCV(m_numOfCrossValidationFolds, fold); //now test for (int i = 0; i < test.numInstances(); i++) { inst = test.instance(i); ans = m_cleansingClassifier.classifyInstance(inst); if (crossSet.classAttribute().isNumeric()) { if (ans >= inst.classValue() - m_numericClassifyThreshold && ans <= inst.classValue() + m_numericClassifyThreshold) { temp.add(inst); } else if (m_invertMatching) { inverseSet.add(inst); } } else { //class is nominal if (ans == inst.classValue()) { temp.add(inst); } else if (m_invertMatching) { inverseSet.add(inst); } } } } crossSet = temp; } if (m_invertMatching) { inverseSet.setClassIndex(data.classIndex()); return inverseSet; } else { crossSet.setClassIndex(data.classIndex()); return crossSet; } } /** * Input an instance for filtering. * * @param instance the input instance * @return true if the filtered instance may now be * collected with output(). * @throws NullPointerException if the input format has not been * defined. * @throws Exception if the input instance was not of the correct * format or if there was a problem with the filtering. */ public boolean input(Instance instance) throws Exception { if (inputFormatPeek() == null) { throw new NullPointerException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } if (m_firstBatchFinished) { push(instance); return true; } else { bufferInput(instance); return false; } } /** * Signify that this batch of input to the filter is finished. * * @return true if there are instances pending output * @throws IllegalStateException if no input structure has been defined */ public boolean batchFinished() throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (!m_firstBatchFinished) { Instances filtered; if (m_numOfCrossValidationFolds < 2) { filtered = cleanseTrain(getInputFormat()); } else { filtered = cleanseCross(getInputFormat()); } for (int i=0; i<filtered.numInstances(); i++) { push(filtered.instance(i)); } m_firstBatchFinished = true; flushInput(); } m_NewBatch = true; return (numPendingOutput() != 0); } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector newVector = new Vector(6); newVector.addElement(new Option( "\tFull class name of classifier to use, followed\n" + "\tby scheme options. eg:\n" + "\t\t\"weka.classifiers.bayes.NaiveBayes -D\"\n" + "\t(default: weka.classifiers.rules.ZeroR)", "W", 1, "-W <classifier specification>")); newVector.addElement(new Option( "\tAttribute on which misclassifications are based.\n" + "\tIf < 0 will use any current set class or default to the last attribute.", "C", 1, "-C <class index>")); newVector.addElement(new Option( "\tThe number of folds to use for cross-validation cleansing.\n" +"\t(<2 = no cross-validation - default).", "F", 1, "-F <number of folds>")); newVector.addElement(new Option( "\tThreshold for the max error when predicting numeric class.\n" +"\t(Value should be >= 0, default = 0.1).", "T", 1, "-T <threshold>")); newVector.addElement(new Option( "\tThe maximum number of cleansing iterations to perform.\n" +"\t(<1 = until fully cleansed - default)", "I", 1,"-I")); newVector.addElement(new Option( "\tInvert the match so that correctly classified instances are discarded.\n", "V", 0,"-V")); return newVector.elements(); } /** * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -W &lt;classifier specification&gt; * Full class name of classifier to use, followed * by scheme options. eg: * "weka.classifiers.bayes.NaiveBayes -D" * (default: weka.classifiers.rules.ZeroR)</pre> * * <pre> -C &lt;class index&gt; * Attribute on which misclassifications are based. * If &lt; 0 will use any current set class or default to the last attribute.</pre> * * <pre> -F &lt;number of folds&gt; * The number of folds to use for cross-validation cleansing. * (&lt;2 = no cross-validation - default).</pre> * * <pre> -T &lt;threshold&gt; * Threshold for the max error when predicting numeric class. * (Value should be &gt;= 0, default = 0.1).</pre> * * <pre> -I * The maximum number of cleansing iterations to perform. * (&lt;1 = until fully cleansed - default)</pre> * * <pre> -V * Invert the match so that correctly classified instances are discarded. * </pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String classifierString = Utils.getOption('W', options); if (classifierString.length() == 0) classifierString = weka.classifiers.rules.ZeroR.class.getName(); String[] classifierSpec = Utils.splitOptions(classifierString); if (classifierSpec.length == 0) { throw new Exception("Invalid classifier specification string"); } String classifierName = classifierSpec[0]; classifierSpec[0] = ""; setClassifier(AbstractClassifier.forName(classifierName, classifierSpec)); String cString = Utils.getOption('C', options); if (cString.length() != 0) { setClassIndex((new Double(cString)).intValue()); } else { setClassIndex(-1); } String fString = Utils.getOption('F', options); if (fString.length() != 0) { setNumFolds((new Double(fString)).intValue()); } else { setNumFolds(0); } String tString = Utils.getOption('T', options); if (tString.length() != 0) { setThreshold((new Double(tString)).doubleValue()); } else { setThreshold(0.1); } String iString = Utils.getOption('I', options); if (iString.length() != 0) { setMaxIterations((new Double(iString)).intValue()); } else { setMaxIterations(0); } if (Utils.getFlag('V', options)) { setInvert(true); } else { setInvert(false); } Utils.checkForRemainingOptions(options); } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ public String [] getOptions() { String [] options = new String [15]; int current = 0; options[current++] = "-W"; options[current++] = "" + getClassifierSpec(); options[current++] = "-C"; options[current++] = "" + getClassIndex(); options[current++] = "-F"; options[current++] = "" + getNumFolds(); options[current++] = "-T"; options[current++] = "" + getThreshold(); options[current++] = "-I"; options[current++] = "" + getMaxIterations(); if (getInvert()) { options[current++] = "-V"; } while (current < options.length) { options[current++] = ""; } return options; } /** * Returns a string describing this filter * * @return a description of the filter suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "A filter that removes instances which are incorrectly classified. " + "Useful for removing outliers."; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String classifierTipText() { return "The classifier upon which to base the misclassifications."; } /** * Sets the classifier to classify instances with. * * @param classifier The classifier to be used (with its options set). */ public void setClassifier(Classifier classifier) { m_cleansingClassifier = classifier; } /** * Gets the classifier used by the filter. * * @return The classifier to be used. */ public Classifier getClassifier() { return m_cleansingClassifier; } /** * Gets the classifier specification string, which contains the class name of * the classifier and any options to the classifier. * * @return the classifier string. */ protected String getClassifierSpec() { Classifier c = getClassifier(); if (c instanceof OptionHandler) { return c.getClass().getName() + " " + Utils.joinOptions(((OptionHandler)c).getOptions()); } return c.getClass().getName(); } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String classIndexTipText() { return "Index of the class upon which to base the misclassifications. " + "If < 0 will use any current set class or default to the last attribute."; } /** * Sets the attribute on which misclassifications are based. * If &lt; 0 will use any current set class or default to the last attribute. * * @param classIndex the class index. */ public void setClassIndex(int classIndex) { m_classIndex = classIndex; } /** * Gets the attribute on which misclassifications are based. * * @return the class index. */ public int getClassIndex() { return m_classIndex; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String numFoldsTipText() { return "The number of cross-validation folds to use. If < 2 then no cross-validation will be performed."; } /** * Sets the number of cross-validation folds to use * - &lt; 2 means no cross-validation. * * @param numOfFolds the number of folds. */ public void setNumFolds(int numOfFolds) { m_numOfCrossValidationFolds = numOfFolds; } /** * Gets the number of cross-validation folds used by the filter. * * @return the number of folds. */ public int getNumFolds() { return m_numOfCrossValidationFolds; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String thresholdTipText() { return "Threshold for the max allowable error when predicting a numeric class. Should be >= 0."; } /** * Sets the threshold for the max error when predicting a numeric class. * The value should be &gt;= 0. * * @param threshold the numeric theshold. */ public void setThreshold(double threshold) { m_numericClassifyThreshold = threshold; } /** * Gets the threshold for the max error when predicting a numeric class. * * @return the numeric threshold. */ public double getThreshold() { return m_numericClassifyThreshold; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String maxIterationsTipText() { return "The maximum number of iterations to perform. < 1 means filter will go until fully cleansed."; } /** * Sets the maximum number of cleansing iterations to perform * - &lt; 1 means go until fully cleansed * * @param iterations the maximum number of iterations. */ public void setMaxIterations(int iterations) { m_numOfCleansingIterations = iterations; } /** * Gets the maximum number of cleansing iterations performed * * @return the maximum number of iterations. */ public int getMaxIterations() { return m_numOfCleansingIterations; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String invertTipText() { return "Whether or not to invert the selection. If true, correctly classified instances will be discarded."; } /** * Set whether selection is inverted. * * @param invert whether or not to invert selection. */ public void setInvert(boolean invert) { m_invertMatching = invert; } /** * Get whether selection is inverted. * * @return whether or not selection is inverted. */ public boolean getInvert() { return m_invertMatching; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 8034 $"); } /** * Main method for testing this class. * * @param argv should contain arguments to the filter: use -h for help */ public static void main(String [] argv) { runFilter(new RemoveMisclassified(), argv); } }
gpl-3.0
rudhir-upretee/Sumo_With_Netsim
tools/contributed/traci4j/src/it/polito/appeal/traci/protocol/StatusResponse.java
1972
/* Copyright (C) 2011 ApPeAL Group, Politecnico di Torino This file is part of TraCI4J. TraCI4J is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TraCI4J is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with TraCI4J. If not, see <http://www.gnu.org/licenses/>. */ package it.polito.appeal.traci.protocol; import java.io.IOException; import de.uniluebeck.itm.tcpip.Storage; public class StatusResponse { private final int id; private final int result; private final String description; public StatusResponse(int id) { this(id, Constants.RTYPE_OK, ""); } public StatusResponse(int id, int result, String description) { this.id = id; this.result = result; this.description = description; } public StatusResponse(Storage packet) throws IOException { int len = packet.readByte(); if (len == 0) packet.readInt(); // length is ignored; we can derive it id = packet.readUnsignedByte(); result = packet.readUnsignedByte(); description = packet.readStringASCII(); } public int id() { return id; } /** * @return the result */ public int result() { return result; } /** * @return the description */ public String description() { return description; } public void writeTo(Storage out) throws IOException { out.writeByte(0); out.writeInt(5+1+1+4+description.length()); out.writeByte(id); out.writeByte(result); out.writeStringASCII(description); } }
gpl-3.0
jlopezjuy/ClothesHipster
anelapi/src/main/java/com/anelsoftware/clothes/domain/PersistentAuditEvent.java
1867
package com.anelsoftware.clothes.domain; import java.io.Serializable; import java.time.LocalDateTime; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; /** * Persist AuditEvent managed by the Spring Boot actuator * @see org.springframework.boot.actuate.audit.AuditEvent */ @Entity @Table(name = "jhi_persistent_audit_event") public class PersistentAuditEvent implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "event_id") private Long id; @NotNull @Column(nullable = false) private String principal; @Column(name = "event_date") private LocalDateTime auditEventDate; @Column(name = "event_type") private String auditEventType; @ElementCollection @MapKeyColumn(name = "name") @Column(name = "value") @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id")) private Map<String, String> data = new HashMap<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPrincipal() { return principal; } public void setPrincipal(String principal) { this.principal = principal; } public LocalDateTime getAuditEventDate() { return auditEventDate; } public void setAuditEventDate(LocalDateTime auditEventDate) { this.auditEventDate = auditEventDate; } public String getAuditEventType() { return auditEventType; } public void setAuditEventType(String auditEventType) { this.auditEventType = auditEventType; } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } }
gpl-3.0
obulpathi/java
examples/ch12/GUnzip.java
1206
//file: GUnzip.java import java.io.*; import java.util.zip.*; public class GUnzip { public static int sChunk = 8192; public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } // create input stream String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length( ) - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; // decompress the file try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close( ); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close( ); } catch (IOException e) {} } }
gpl-3.0
lveci/nest
beam/beam-ui/src/test/java/org/esa/beam/framework/ui/diagram/DiagramTest.java
1768
/* * Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.beam.framework.ui.diagram; import junit.framework.TestCase; import org.esa.beam.util.math.Range; import java.awt.geom.Point2D; public class DiagramTest extends TestCase { public void testTransform() { Diagram.RectTransform rectTransform = new Diagram.RectTransform(new Range(0, 10), new Range(-1, +1), new Range(100, 200), new Range(100, 0)); Point2D a, b; a = new Point2D.Double(5, 0); b = rectTransform.transformA2B(a, null); assertEquals(new Point2D.Double(150.0, 50.0), b); assertEquals(a, rectTransform.transformB2A(b, null)); a = new Point2D.Double(7.5, -0.25); b = rectTransform.transformA2B(a, null); assertEquals(new Point2D.Double(175.0, 62.5), b); assertEquals(a, rectTransform.transformB2A(b, null)); } }
gpl-3.0
simonschaufi/kimai
js/init.js
3162
/* -*- Mode: jQuery; tab-width: 4; indent-tabs-mode: nil -*- */ /** * This file is part of * Kimai - Open Source Time Tracking // https://www.kimai.org * (c) 2006-2009 Kimai-Development-Team * * Kimai is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; Version 3, 29 June 2007 * * Kimai is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Kimai; If not, see <http://www.gnu.org/licenses/>. */ // Runs when the DOM of the Kimai GUI is loaded => MAIN init script! var userColumnWidth; var customerColumnWidth; var projectColumnWidth; var activityColumnWidth; var currentDay = (new Date()).getDate(); var fading_enabled = true; var extensionShrinkMode = 0; // 0 = show, 1 = hide var customerShrinkMode = 0; var userShrinkMode = 0; var filterUsers = []; var filterCustomers = []; var filterProjects = []; var filterActivities = []; var lists_visibility = []; var lists_user_annotations = {}; var lists_customer_annotations = {}; var lists_project_annotations = {}; var lists_activity_annotations = {}; $(document).ready(function () { var preselected_customer = 0; if (userID) { // automatic tab-change on reload ki_active_tab_target = Cookies.get('ki_active_tab_target_' + userID); ki_active_tab_path = Cookies.get('ki_active_tab_path_' + userID); } else { ki_active_tab_target = null; ki_active_tab_path = null; } if (ki_active_tab_target && ki_active_tab_path) { changeTab(ki_active_tab_target, ki_active_tab_path); } else { changeTab(0, 'ki_timesheets/init.php'); } $('#main_tools_button').hoverIntent({ sensitivity: 7, interval: 300, over: showTools, timeout: 6000, out: hideTools }); $('#main_credits_button').click(function () { this.blur(); floaterShow('floaters.php', 'credits', 0, 0, 650); return false; }); $('#main_prefs_button').click(function () { this.blur(); floaterShow('floaters.php', 'prefs', 0, 0, 450); return false; }); $('#buzzer').click(function () { buzzer(); }); if (currentRecording > -1 || (selected_customer && selected_project && selected_activity)) { $('#buzzer').removeClass('disabled'); } n_uhr(); if (currentRecording > -1) { show_stopwatch(); } else { show_selectors(); } var lists_resizeTimer = null; $(window).bind('resize', function () { resize_menu(); resize_floater(); if (lists_resizeTimer) { clearTimeout(lists_resizeTimer); } lists_resizeTimer = setTimeout(lists_resize, 500); }); // Implement missing method for browsers like IE. // thanks to http://stellapower.net/content/javascript-support-and-arrayindexof-ie if (!Array.indexOf) { Array.prototype.indexOf = function (obj, start) { for (var i = (start || 0); i < this.length; i++) { if (this[i] == obj) { return i; } } return -1; } } });
gpl-3.0
BSDStudios/parity
js/src/api/rpc/web3/web3.js
1036
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import { inHex } from '../../format/input'; export default class Web3 { constructor (transport) { this._transport = transport; } clientVersion () { return this._transport .execute('web3_clientVersion'); } sha3 (hexStr) { return this._transport .execute('web3_sha3', inHex(hexStr)); } }
gpl-3.0
scurest/Player
src/sprite_character.cpp
4003
/* * This file is part of EasyRPG Player. * * EasyRPG Player is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EasyRPG Player is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. */ // Headers #include "sprite_character.h" #include "cache.h" #include "game_map.h" #include "bitmap.h" Sprite_Character::Sprite_Character(Game_Character* character) : character(character), tile_id(0), character_index(0), chara_width(0), chara_height(0) { Update(); } void Sprite_Character::Update() { Sprite::Update(); Rect r; if (tile_id != character->GetTileId() || character_name != character->GetSpriteName() || character_index != character->GetSpriteIndex()) { tile_id = character->GetTileId(); character_name = character->GetSpriteName(); character_index = character->GetSpriteIndex(); if (tile_id > 0) { FileRequestAsync* tile_request = AsyncHandler::RequestFile("ChipSet", Game_Map::GetChipsetName()); request_id = tile_request->Bind(&Sprite_Character::OnTileSpriteReady, this); tile_request->Start(); } else { if (character_name.empty()) { SetBitmap(BitmapRef()); } else { FileRequestAsync* char_request = AsyncHandler::RequestFile("CharSet", character_name); request_id = char_request->Bind(&Sprite_Character::OnCharSpriteReady, this); char_request->Start(); } } } if (tile_id == 0) { int row = character->GetSpriteDirection(); r.Set(character->GetPattern() * chara_width, row * chara_height, chara_width, chara_height); SetSrcRect(r); } if (character->IsFlashPending()) { Color col = character->GetFlashColor(); int dur = character->GetFlashTimeLeft(); Flash(col, dur); // TODO: Gradual decrease of Flash Time Left character->SetFlashTimeLeft(0); } SetVisible(character->GetVisible()); if (GetVisible()) { SetOpacity(character->GetOpacity()); } SetX(character->GetScreenX()); SetY(character->GetScreenY()); SetZ(character->GetScreenZ()); //SetBlendType(character->GetBlendType()); int bush_split = 4 - character->GetBushDepth(); SetBushDepth(bush_split > 3 ? 0 : GetHeight() / bush_split); } Game_Character* Sprite_Character::GetCharacter() { return character; } void Sprite_Character::SetCharacter(Game_Character* new_character) { character = new_character; } void Sprite_Character::OnTileSpriteReady(FileRequestResult*) { std::string chipset = Game_Map::GetChipsetName(); BitmapRef tile; if (!chipset.empty()) { tile = Cache::Tile(Game_Map::GetChipsetName(), tile_id); } else { tile = Bitmap::Create(16, 16, Color()); } SetBitmap(tile); Rect r; r.Set(0, 0, TILE_SIZE, TILE_SIZE); SetSrcRect(r); SetOx(8); SetOy(16); Update(); } void Sprite_Character::OnCharSpriteReady(FileRequestResult*) { SetBitmap(Cache::Charset(character_name)); // Allow large 4x2 spriteset of 3x4 sprites // when the character name starts with a $ sign. // This is not exactly the VX Ace way because // VX Ace uses a single 1x1 spriteset of 3x4 sprites. if (character_name.size() && character_name.at(0) == '$') { chara_width = GetBitmap()->GetWidth() / 4 / 3 * (TILE_SIZE / 16); chara_height = GetBitmap()->GetHeight() / 2 / 4 * (TILE_SIZE / 16); } else { chara_width = 24 * (TILE_SIZE / 16); chara_height = 32 * (TILE_SIZE / 16); } SetOx(chara_width / 2); SetOy(chara_height); int sx = (character_index % 4) * chara_width * 3; int sy = (character_index / 4) * chara_height * 4; Rect r; r.Set(sx, sy, chara_width * 3, chara_height * 4); SetSpriteRect(r); Update(); }
gpl-3.0
davisc/django-osgeo-importer
osgeo_importer/tests/helpers.py
3063
from django.conf import settings from django import db def create_datastore(workspace_name, connection, catalog): """Convenience method for creating a datastore. """ from geoserver.catalog import FailedRequestError settings = connection.settings_dict ds_name = settings['NAME'] params = { 'database': ds_name, 'passwd': settings['PASSWORD'], 'namespace': 'http://www.geonode.org/', 'type': 'PostGIS', 'dbtype': 'postgis', 'host': settings['HOST'], 'user': settings['USER'], 'port': settings['PORT'], 'enabled': 'True' } store = catalog.create_datastore(ds_name, workspace=workspace_name) store.connection_parameters.update(params) try: catalog.save(store) except FailedRequestError: # assuming this is because it already exists pass return catalog.get_store(ds_name) def works_with_geoserver(wrapped_func): """ A decorator for test methods with functionality that should work with or without geoserver configured in settings. Some signal handlers in geonode.geoserver presume a geoserver workspace and datastore are configured. This decorator makes sure that is true during the test if geonode.geoserver is in INSTALLED_APPS and they get torn down appropriately afterwards. """ if 'geonode.geoserver' in settings.INSTALLED_APPS: try: from geonode.geoserver.helpers import ogc_server_settings from geoserver.catalog import Catalog can_set_up_geoserver_workspace = True except ImportError: can_set_up_geoserver_workspace = False if can_set_up_geoserver_workspace: def wrapper(self, *args, **kwargs): workspace_name = 'geonode' django_datastore = db.connections['datastore'] catalog = Catalog( ogc_server_settings.internal_rest, *ogc_server_settings.credentials ) # Set up workspace/datastore as appropriate ws = catalog.get_workspace(workspace_name) delete_ws = False if ws is None: ws = catalog.create_workspace(workspace_name, 'http://www.geonode.org/') delete_ws = True datastore = create_datastore(workspace_name, django_datastore, catalog) # test method called here try: ret = wrapped_func(self, *args, **kwargs) finally: # Tear down workspace/datastore as appropriate if delete_ws: catalog.delete(ws, recurse=True) else: catalog.delete(datastore, recurse=True) return ret else: wrapper = wrapped_func else: # workspace setup not needed, don't bother wrapping the function wrapper = wrapped_func return wrapper
gpl-3.0
unreal666/outwiker
src/outwiker/actions/close.py
532
# -*- coding: utf-8 -*- from outwiker.gui.baseaction import BaseAction from outwiker.core.commands import closeWiki class CloseAction (BaseAction): """ Закрытие дерева заметок """ stringId = u"CloseWiki" def __init__(self, application): self._application = application @property def title(self): return _(u"Close") @property def description(self): return _(u"Close a tree notes") def run(self, params): closeWiki(self._application)
gpl-3.0
Elektro1776/latestEarthables
core/client/tmp/broccoli_persistent_filterbabel-output_path-5YZ9mQhf.tmp/ghost-admin/models/user.js
7097
define('ghost-admin/models/user', ['exports', 'ember-data/model', 'ember-data/attr', 'ember-data/relationships', 'ember-computed', 'ember-service/inject', 'ember-concurrency', 'ghost-admin/mixins/validation-engine'], function (exports, _emberDataModel, _emberDataAttr, _emberDataRelationships, _emberComputed, _emberServiceInject, _emberConcurrency, _ghostAdminMixinsValidationEngine) { exports['default'] = _emberDataModel['default'].extend(_ghostAdminMixinsValidationEngine['default'], { validationType: 'user', uuid: (0, _emberDataAttr['default'])('string'), name: (0, _emberDataAttr['default'])('string'), slug: (0, _emberDataAttr['default'])('string'), email: (0, _emberDataAttr['default'])('string'), image: (0, _emberDataAttr['default'])('string'), cover: (0, _emberDataAttr['default'])('string'), bio: (0, _emberDataAttr['default'])('string'), website: (0, _emberDataAttr['default'])('string'), location: (0, _emberDataAttr['default'])('string'), accessibility: (0, _emberDataAttr['default'])('string'), status: (0, _emberDataAttr['default'])('string'), language: (0, _emberDataAttr['default'])('string', { defaultValue: 'en_US' }), metaTitle: (0, _emberDataAttr['default'])('string'), metaDescription: (0, _emberDataAttr['default'])('string'), lastLoginUTC: (0, _emberDataAttr['default'])('moment-utc'), createdAtUTC: (0, _emberDataAttr['default'])('moment-utc'), createdBy: (0, _emberDataAttr['default'])('number'), updatedAtUTC: (0, _emberDataAttr['default'])('moment-utc'), updatedBy: (0, _emberDataAttr['default'])('number'), roles: (0, _emberDataRelationships.hasMany)('role', { embedded: 'always', async: false }), count: (0, _emberDataAttr['default'])('raw'), facebook: (0, _emberDataAttr['default'])('facebook-url-user'), twitter: (0, _emberDataAttr['default'])('twitter-url-user'), ghostPaths: (0, _emberServiceInject['default'])(), ajax: (0, _emberServiceInject['default'])(), session: (0, _emberServiceInject['default'])(), notifications: (0, _emberServiceInject['default'])(), // TODO: Once client-side permissions are in place, // remove the hard role check. isAuthor: (0, _emberComputed.equal)('role.name', 'Author'), isEditor: (0, _emberComputed.equal)('role.name', 'Editor'), isAdmin: (0, _emberComputed.equal)('role.name', 'Administrator'), isOwner: (0, _emberComputed.equal)('role.name', 'Owner'), isLoggedIn: (0, _emberComputed['default'])('id', 'session.user.id', function () { return this.get('id') === this.get('session.user.id'); }), active: (0, _emberComputed['default'])('status', function () { return ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked'].indexOf(this.get('status')) > -1; }), invited: (0, _emberComputed['default'])('status', function () { return ['invited', 'invited-pending'].indexOf(this.get('status')) > -1; }), pending: (0, _emberComputed.equal)('status', 'invited-pending'), role: (0, _emberComputed['default'])('roles', { get: function get() { return this.get('roles.firstObject'); }, set: function set(key, value) { // Only one role per user, so remove any old data. this.get('roles').clear(); this.get('roles').pushObject(value); return value; } }), saveNewPassword: (0, _emberConcurrency.task)(regeneratorRuntime.mark(function callee$0$0() { var validation, url; return regeneratorRuntime.wrap(function callee$0$0$(context$1$0) { while (1) switch (context$1$0.prev = context$1$0.next) { case 0: validation = this.get('isLoggedIn') ? 'ownPasswordChange' : 'passwordChange'; context$1$0.prev = 1; context$1$0.next = 4; return this.validate({ property: validation }); case 4: context$1$0.next = 9; break; case 6: context$1$0.prev = 6; context$1$0.t0 = context$1$0['catch'](1); return context$1$0.abrupt('return'); case 9: context$1$0.prev = 9; url = this.get('ghostPaths.url').api('users', 'password'); context$1$0.next = 13; return this.get('ajax').put(url, { data: { password: [{ user_id: this.get('id'), oldPassword: this.get('password'), newPassword: this.get('newPassword'), ne2Password: this.get('ne2Password') }] } }); case 13: this.setProperties({ password: '', newPassword: '', ne2Password: '' }); this.get('notifications').showNotification('Password updated.', { type: 'success', key: 'user.change-password.success' }); // clear errors manually for ne2password because validation // engine only clears the "validated proeprty" // TODO: clean up once we have a better validations library this.get('errors').remove('ne2Password'); context$1$0.next = 21; break; case 18: context$1$0.prev = 18; context$1$0.t1 = context$1$0['catch'](9); this.get('notifications').showAPIError(context$1$0.t1, { key: 'user.change-password' }); case 21: case 'end': return context$1$0.stop(); } }, callee$0$0, this, [[1, 6], [9, 18]]); })).drop(), resendInvite: function resendInvite() { var fullUserData = this.toJSON(); var userData = { email: fullUserData.email, roles: fullUserData.roles }; var inviteUrl = this.get('ghostPaths.url').api('users'); return this.get('ajax').post(inviteUrl, { data: JSON.stringify({ users: [userData] }), contentType: 'application/json' }); } }); }); /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */ // validation error, don't do anything
gpl-3.0
H-uru/libhsplasma
core/Util/PlasmaVersions.cpp
1669
/* This file is part of HSPlasma. * * HSPlasma is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HSPlasma is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HSPlasma. If not, see <http://www.gnu.org/licenses/>. */ #include "PlasmaVersions.h" const char* PlasmaVer::GetVersionName(PlasmaVer ver) { switch (ver) { case pvPrime: return "Prime/UU"; case pvPots: return "PotS/CC"; case pvMoul: return "MOUL/MQO"; case pvEoa: return "Myst V/Crowthistle"; case pvHex: return "Hex Isle"; case pvUniversal: return "Universal"; default: if (ver < pvPrime) return "Choru"; if (ver > pvPots && ver < pvMoul) return "MOUL Beta"; else return "Unknown"; } } PlasmaVer PlasmaVer::GetSafestVersion(PlasmaVer ver) { if (ver <= pvPrime) return pvPrime; else if (ver == pvPots) return pvPots; else if (ver <= pvMoul) return pvMoul; else if (ver == pvEoa) return pvEoa; else if (ver == pvHex) return pvHex; else return pvUniversal; }
gpl-3.0
nickdex/cosmos
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/profunctor/profunctor.scala
51
package functors.profunctor trait Profunctor { }
gpl-3.0
stanta/darfchain
darfchain_docker/bigchaindb/backend/rethinkdb/changefeed.py
2045
import time import logging import rethinkdb as r from bigchaindb import backend from bigchaindb.backend.exceptions import BackendError from bigchaindb.backend.changefeed import ChangeFeed from bigchaindb.backend.utils import module_dispatch_registrar from bigchaindb.backend.rethinkdb.connection import RethinkDBConnection logger = logging.getLogger(__name__) register_changefeed = module_dispatch_registrar(backend.changefeed) class RethinkDBChangeFeed(ChangeFeed): """This class wraps a RethinkDB changefeed as a multipipes Node.""" def run_forever(self): for element in self.prefeed: self.outqueue.put(element) for change in run_changefeed(self.connection, self.table): is_insert = change['old_val'] is None is_delete = change['new_val'] is None is_update = not is_insert and not is_delete if is_insert and (self.operation & ChangeFeed.INSERT): self.outqueue.put(change['new_val']) elif is_delete and (self.operation & ChangeFeed.DELETE): self.outqueue.put(change['old_val']) elif is_update and (self.operation & ChangeFeed.UPDATE): self.outqueue.put(change['new_val']) def run_changefeed(connection, table): """Encapsulate operational logic of tailing changefeed from RethinkDB """ while True: try: for change in connection.run(r.table(table).changes()): yield change break except (BackendError, r.ReqlDriverError) as exc: logger.exception('Error connecting to the database, retrying') time.sleep(1) @register_changefeed(RethinkDBConnection) def get_changefeed(connection, table, operation, *, prefeed=None): """Return a RethinkDB changefeed. Returns: An instance of :class:`~bigchaindb.backend.rethinkdb.RethinkDBChangeFeed`. """ return RethinkDBChangeFeed(table, operation, prefeed=prefeed, connection=connection)
gpl-3.0
m038/plugin-IngestPluginBundle
Controller/EntryController.php
7062
<?php namespace Newscoop\IngestPluginBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Finder\Finder; use Exception; use Newscoop\IngestPluginBundle\Form\Type\FeedType; use Newscoop\IngestPluginBundle\Entity\Feed; use Newscoop\IngestPluginBundle\Entity\Feed\Entry; use Newscoop\IngestPluginBundle\Entity\Parser; use Newscoop\EventDispatcher\Events\GenericEvent; /** * @Route("/admin/ingest/entry") */ class EntryController extends Controller { /** * @Route("/list/") * @Template() */ public function listAction(Request $request) { $em = $this->container->get('em'); // End of debug code $queryBuilder = $em ->getRepository('Newscoop\IngestPluginBundle\Entity\Feed\Entry') ->createQueryBuilder('e'); $defaultData = array('feed' => '', 'published' => '', 'view' => 'slim'); $filterForm = $this->createFormBuilder($defaultData) ->setMethod('GET') ->add('feed', 'entity', array( 'class' => 'Newscoop\IngestPluginBundle\Entity\Feed', 'property' => 'name', 'empty_value' => 'plugin.ingest.entries.filter.all_feeds', 'required' => false, )) ->add('published', 'choice', array( 'choices' => array( 'Y' => 'plugin.ingest.entries.filter.yes', 'N' => 'plugin.ingest.entries.filter.no', ), 'empty_value' => 'plugin.ingest.entries.filter.all', 'label' => 'plugin.ingest.entries.filter.published', 'required' => false, )) ->add('view', 'choice', array( 'choices' => array( 'slim' => 'plugin.ingest.entries.filter.slim', 'expanded' => 'plugin.ingest.entries.filter.expanded', ), 'label' => 'plugin.ingest.entries.filter.view', )) ->add('filter', 'submit', array( 'label' => 'plugin.ingest.entries.filter.filter' )) ->getForm(); $filterForm->handleRequest($request); if ($filterForm->isValid()) { $formData = $filterForm->getData(); $query = $queryBuilder ->where('1=1'); if (!empty($formData['feed'])) { $query = $query ->andWhere($queryBuilder->expr()->in('e.feed', '?1')) ->setParameter(1, $formData['feed']); } if (!empty($formData['published'])) { if ($formData['published'] == 'Y') { $expression = $queryBuilder->expr()->isNotNull('e.published'); } else { $expression = $queryBuilder->expr()->isNull('e.published'); } $query = $query ->andWhere($expression); } } $queryBuilder ->addOrderBy('e.created', 'desc') ->addOrderBy('e.id', 'desc'); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $queryBuilder->getQuery(), $request->query->get('knp_page', 1), 10 ); $pagination->setTemplate('NewscoopIngestPluginBundle:Pagination:pagination_bootstrap3.html.twig'); return array( 'filterForm' => $filterForm->createView(), 'pagination' => $pagination, 'view' => (isset($formData) ? $formData['view'] : $defaultData['view']) ); } /** * @Route("/publish/{id}/") * @ParamConverter("get") */ public function publishAction(Request $request, Entry $entry) { $publisherService = $this->container->get('newscoop_ingest_plugin.publisher'); $publisherService->publish($entry); $this->get('session')->getFlashBag()->add( 'notice', $this->container->get('translator')->trans('plugin.ingest.entries.publishedsuccess') ); return $this->redirect($this->generateUrl('newscoop_ingestplugin_entry_list')); } /** * @Route("/prepare/{id}") * @ParamConverter("get") */ public function prepareAction(Request $request, Entry $entry) { $publisherService = $this->container->get('newscoop_ingest_plugin.publisher'); $legacyArticle = $publisherService->prepare($entry); return $this->redirect( $this->generateUrl('newscoop_ingestplugin_entry_redirecttoarticle', array( 'languageId' => $legacyArticle->getLanguageId(), 'articleNumber' => $legacyArticle->getArticleNumber(), ) ) ); } /** * @Route("/delete/{id}/") * @ParamConverter("get") * @Template() */ public function deleteAction(Request $request, Entry $entry) { if ($entry->getArticleId() !== null) { $publisherService = $this->container->get('newscoop_ingest_plugin.publisher'); $publisherService->remove($entry); } $em = $this->container->get('em'); $em->remove($entry); $em->flush(); $this->get('session')->getFlashBag()->add( 'notice', $this->container->get('translator')->trans('plugin.ingest.entries.removedsuccess') ); return $this->redirect($this->generateUrl('newscoop_ingestplugin_entry_list')); } /** * @Route("/redirect/{languageId}/{articleNumber}/") */ public function redirectToArticleAction($languageId, $articleNumber, Request $request) { $legacyArticleLink = ''; // find article $article = new \Article($languageId, $articleNumber); if (!$article->exists()) { throw new Exception( $this->container->get('translator')->trans( 'plugin.ingest.entries.articlenotfound', array('%language%' => $languageId, '%article%' => $articleNumber) ), 1 ); } $legacyArticleLink = '/admin/articles/edit.php?f_publication_id=' . $article->getPublicationId() . '&f_issue_number=' . $article->getIssueNumber() . '&f_section_number=' . $article->getSectionNumber() . '&f_article_number=' . $article->getArticleNumber() . '&f_language_id=' . $article->getLanguageId() . '&f_language_selected=' . $article->getLanguageId(); return $this->redirect($legacyArticleLink); } }
gpl-3.0
loiclacombe/higan-cli-fullscreen
ananke/configuration.cpp
438
struct Settings : Configuration::Document { string path; string geometry; Settings() { Configuration::Node node; node.append(path = userpath(), "Path"); node.append(geometry = "64,64,480,600", "Geometry"); append(node, "Settings"); directory::create({configpath(), "ananke/"}); load({configpath(), "ananke/settings.bml"}); } ~Settings() { save({configpath(), "ananke/settings.bml"}); } } config;
gpl-3.0
agtt/opencart
upload/extension/opencart/admin/controller/dashboard/map.php
3182
<?php namespace Opencart\Admin\Controller\Extension\Opencart\Dashboard; class Map extends \Opencart\System\Engine\Controller { public function index(): void { $this->load->language('extension/opencart/dashboard/map'); $this->document->setTitle($this->language->get('heading_title')); $data['breadcrumbs'] = []; $data['breadcrumbs'][] = [ 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token']) ]; $data['breadcrumbs'][] = [ 'text' => $this->language->get('text_extension'), 'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=dashboard') ]; $data['breadcrumbs'][] = [ 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('extension/opencart/dashboard/map', 'user_token=' . $this->session->data['user_token']) ]; $data['save'] = $this->url->link('extension/opencart/dashboard/map|save', 'user_token=' . $this->session->data['user_token']); $data['back'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=dashboard'); $data['dashboard_map_width'] = $this->config->get('dashboard_map_width'); $data['columns'] = []; for ($i = 3; $i <= 12; $i++) { $data['columns'][] = $i; } $data['dashboard_map_status'] = $this->config->get('dashboard_map_status'); $data['dashboard_map_sort_order'] = $this->config->get('dashboard_map_sort_order'); $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('extension/opencart/dashboard/map_form', $data)); } public function save(): void { $this->load->language('extension/opencart/dashboard/map'); $json = []; if (!$this->user->hasPermission('modify', 'extension/opencart/dashboard/map')) { $json['error'] = $this->language->get('error_permission'); } if (!$json) { $this->load->model('setting/setting'); $this->model_setting_setting->editSetting('dashboard_map', $this->request->post); $json['success'] = $this->language->get('text_success'); } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } public function dashboard(): string { $this->load->language('extension/opencart/dashboard/map'); $data['user_token'] = $this->session->data['user_token']; return $this->load->view('extension/opencart/dashboard/map_info', $data); } public function map() { $json = []; $this->load->model('extension/opencart/dashboard/map'); $results = $this->model_extension_opencart_dashboard_map->getTotalOrdersByCountry(); foreach ($results as $result) { $json[strtolower($result['iso_code_2'])] = [ 'total' => $result['total'], 'amount' => $this->currency->format($result['amount'], $this->config->get('config_currency')) ]; } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } }
gpl-3.0
tk8226/YamiPortAIO-v2
Core/AIO Ports/Support Is Easy/Program.cs
979
using EloBuddy; namespace Support { using System; using System.Reflection; using LeagueSharp; using LeagueSharp.Common; using Support.Util; using Version = System.Version; internal class Program { public static Version Version; public static void Main() { Version = Assembly.GetExecutingAssembly().GetName().Version; try { var type = Type.GetType("Support.Plugins." + ObjectManager.Player.ChampionName); if (type != null) { Helpers.UpdateCheck(); Protector.Init(); DynamicInitializer.NewInstance(type); return; } Helpers.PrintMessage(ObjectManager.Player.ChampionName + " not supported"); } catch (Exception e) { Console.WriteLine(e); } } } }
gpl-3.0
s20121035/rk3288_android5.1_repo
external/lldb/source/API/SBTypeCategory.cpp
15803
//===-- SBTypeCategory.cpp ----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/lldb-python.h" #include "lldb/API/SBTypeCategory.h" #include "lldb/API/SBTypeFilter.h" #include "lldb/API/SBTypeFormat.h" #include "lldb/API/SBTypeSummary.h" #include "lldb/API/SBTypeSynthetic.h" #include "lldb/API/SBTypeNameSpecifier.h" #include "lldb/API/SBStream.h" #include "lldb/Core/Debugger.h" #include "lldb/DataFormatters/DataVisualization.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/ScriptInterpreter.h" using namespace lldb; using namespace lldb_private; typedef std::pair<lldb::TypeCategoryImplSP,user_id_t> ImplType; SBTypeCategory::SBTypeCategory() : m_opaque_sp() { } SBTypeCategory::SBTypeCategory (const char* name) : m_opaque_sp() { DataVisualization::Categories::GetCategory(ConstString(name), m_opaque_sp); } SBTypeCategory::SBTypeCategory (const lldb::SBTypeCategory &rhs) : m_opaque_sp(rhs.m_opaque_sp) { } SBTypeCategory::~SBTypeCategory () { } bool SBTypeCategory::IsValid() const { return (m_opaque_sp.get() != NULL); } bool SBTypeCategory::GetEnabled () { if (!IsValid()) return false; return m_opaque_sp->IsEnabled(); } void SBTypeCategory::SetEnabled (bool enabled) { if (!IsValid()) return; if (enabled) DataVisualization::Categories::Enable(m_opaque_sp); else DataVisualization::Categories::Disable(m_opaque_sp); } const char* SBTypeCategory::GetName() { if (!IsValid()) return NULL; return m_opaque_sp->GetName(); } uint32_t SBTypeCategory::GetNumFormats () { if (!IsDefaultCategory()) return 0; return DataVisualization::ValueFormats::GetCount(); } uint32_t SBTypeCategory::GetNumSummaries () { if (!IsValid()) return 0; return m_opaque_sp->GetSummaryNavigator()->GetCount() + m_opaque_sp->GetRegexSummaryNavigator()->GetCount(); } uint32_t SBTypeCategory::GetNumFilters () { if (!IsValid()) return 0; return m_opaque_sp->GetFilterNavigator()->GetCount() + m_opaque_sp->GetRegexFilterNavigator()->GetCount(); } #ifndef LLDB_DISABLE_PYTHON uint32_t SBTypeCategory::GetNumSynthetics () { if (!IsValid()) return 0; return m_opaque_sp->GetSyntheticNavigator()->GetCount() + m_opaque_sp->GetRegexSyntheticNavigator()->GetCount(); } #endif lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForFilterAtIndex (uint32_t index) { if (!IsValid()) return SBTypeNameSpecifier(); return SBTypeNameSpecifier(m_opaque_sp->GetTypeNameSpecifierForFilterAtIndex(index)); } lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForFormatAtIndex (uint32_t index) { if (!IsDefaultCategory()) return SBTypeNameSpecifier(); return SBTypeNameSpecifier(DataVisualization::ValueFormats::GetTypeNameSpecifierForFormatAtIndex(index)); } lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForSummaryAtIndex (uint32_t index) { if (!IsValid()) return SBTypeNameSpecifier(); return SBTypeNameSpecifier(m_opaque_sp->GetTypeNameSpecifierForSummaryAtIndex(index)); } #ifndef LLDB_DISABLE_PYTHON lldb::SBTypeNameSpecifier SBTypeCategory::GetTypeNameSpecifierForSyntheticAtIndex (uint32_t index) { if (!IsValid()) return SBTypeNameSpecifier(); return SBTypeNameSpecifier(m_opaque_sp->GetTypeNameSpecifierForSyntheticAtIndex(index)); } #endif SBTypeFilter SBTypeCategory::GetFilterForType (SBTypeNameSpecifier spec) { if (!IsValid()) return SBTypeFilter(); if (!spec.IsValid()) return SBTypeFilter(); lldb::SyntheticChildrenSP children_sp; if (spec.IsRegex()) m_opaque_sp->GetRegexFilterNavigator()->GetExact(ConstString(spec.GetName()), children_sp); else m_opaque_sp->GetFilterNavigator()->GetExact(ConstString(spec.GetName()), children_sp); if (!children_sp) return lldb::SBTypeFilter(); TypeFilterImplSP filter_sp = std::static_pointer_cast<TypeFilterImpl>(children_sp); return lldb::SBTypeFilter(filter_sp); } SBTypeFormat SBTypeCategory::GetFormatForType (SBTypeNameSpecifier spec) { if (!IsDefaultCategory()) return SBTypeFormat(); if (!spec.IsValid()) return SBTypeFormat(); if (spec.IsRegex()) return SBTypeFormat(); return SBTypeFormat(DataVisualization::ValueFormats::GetFormat(ConstString(spec.GetName()))); } #ifndef LLDB_DISABLE_PYTHON SBTypeSummary SBTypeCategory::GetSummaryForType (SBTypeNameSpecifier spec) { if (!IsValid()) return SBTypeSummary(); if (!spec.IsValid()) return SBTypeSummary(); lldb::TypeSummaryImplSP summary_sp; if (spec.IsRegex()) m_opaque_sp->GetRegexSummaryNavigator()->GetExact(ConstString(spec.GetName()), summary_sp); else m_opaque_sp->GetSummaryNavigator()->GetExact(ConstString(spec.GetName()), summary_sp); if (!summary_sp) return lldb::SBTypeSummary(); return lldb::SBTypeSummary(summary_sp); } #endif // LLDB_DISABLE_PYTHON #ifndef LLDB_DISABLE_PYTHON SBTypeSynthetic SBTypeCategory::GetSyntheticForType (SBTypeNameSpecifier spec) { if (!IsValid()) return SBTypeSynthetic(); if (!spec.IsValid()) return SBTypeSynthetic(); lldb::SyntheticChildrenSP children_sp; if (spec.IsRegex()) m_opaque_sp->GetRegexSyntheticNavigator()->GetExact(ConstString(spec.GetName()), children_sp); else m_opaque_sp->GetSyntheticNavigator()->GetExact(ConstString(spec.GetName()), children_sp); if (!children_sp) return lldb::SBTypeSynthetic(); ScriptedSyntheticChildrenSP synth_sp = std::static_pointer_cast<ScriptedSyntheticChildren>(children_sp); return lldb::SBTypeSynthetic(synth_sp); } #endif #ifndef LLDB_DISABLE_PYTHON SBTypeFilter SBTypeCategory::GetFilterAtIndex (uint32_t index) { if (!IsValid()) return SBTypeFilter(); lldb::SyntheticChildrenSP children_sp = m_opaque_sp->GetSyntheticAtIndex((index)); if (!children_sp.get()) return lldb::SBTypeFilter(); TypeFilterImplSP filter_sp = std::static_pointer_cast<TypeFilterImpl>(children_sp); return lldb::SBTypeFilter(filter_sp); } #endif SBTypeFormat SBTypeCategory::GetFormatAtIndex (uint32_t index) { if (!IsDefaultCategory()) return SBTypeFormat(); return SBTypeFormat(DataVisualization::ValueFormats::GetFormatAtIndex((index))); } #ifndef LLDB_DISABLE_PYTHON SBTypeSummary SBTypeCategory::GetSummaryAtIndex (uint32_t index) { if (!IsValid()) return SBTypeSummary(); return SBTypeSummary(m_opaque_sp->GetSummaryAtIndex((index))); } #endif #ifndef LLDB_DISABLE_PYTHON SBTypeSynthetic SBTypeCategory::GetSyntheticAtIndex (uint32_t index) { if (!IsValid()) return SBTypeSynthetic(); lldb::SyntheticChildrenSP children_sp = m_opaque_sp->GetSyntheticAtIndex((index)); if (!children_sp.get()) return lldb::SBTypeSynthetic(); ScriptedSyntheticChildrenSP synth_sp = std::static_pointer_cast<ScriptedSyntheticChildren>(children_sp); return lldb::SBTypeSynthetic(synth_sp); } #endif bool SBTypeCategory::AddTypeFormat (SBTypeNameSpecifier type_name, SBTypeFormat format) { if (!IsDefaultCategory()) return false; if (!type_name.IsValid()) return false; if (!format.IsValid()) return false; if (type_name.IsRegex()) return false; DataVisualization::ValueFormats::Add(ConstString(type_name.GetName()), format.GetSP()); return true; } bool SBTypeCategory::DeleteTypeFormat (SBTypeNameSpecifier type_name) { if (!IsDefaultCategory()) return false; if (!type_name.IsValid()) return false; if (type_name.IsRegex()) return false; return DataVisualization::ValueFormats::Delete(ConstString(type_name.GetName())); } #ifndef LLDB_DISABLE_PYTHON bool SBTypeCategory::AddTypeSummary (SBTypeNameSpecifier type_name, SBTypeSummary summary) { if (!IsValid()) return false; if (!type_name.IsValid()) return false; if (!summary.IsValid()) return false; // FIXME: we need to iterate over all the Debugger objects and have each of them contain a copy of the function // since we currently have formatters live in a global space, while Python code lives in a specific Debugger-related environment // this should eventually be fixed by deciding a final location in the LLDB object space for formatters if (summary.IsFunctionCode()) { void *name_token = (void*)ConstString(type_name.GetName()).GetCString(); const char* script = summary.GetData(); StringList input; input.SplitIntoLines(script, strlen(script)); uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); bool need_set = true; for (uint32_t j = 0; j < num_debuggers; j++) { DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); if (debugger_sp) { ScriptInterpreter* interpreter_ptr = debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); if (interpreter_ptr) { std::string output; if (interpreter_ptr->GenerateTypeScriptFunction(input, output, name_token) && !output.empty()) { if (need_set) { need_set = false; summary.SetFunctionName(output.c_str()); } } } } } } if (type_name.IsRegex()) m_opaque_sp->GetRegexSummaryNavigator()->Add(lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), summary.GetSP()); else m_opaque_sp->GetSummaryNavigator()->Add(ConstString(type_name.GetName()), summary.GetSP()); return true; } #endif bool SBTypeCategory::DeleteTypeSummary (SBTypeNameSpecifier type_name) { if (!IsValid()) return false; if (!type_name.IsValid()) return false; if (type_name.IsRegex()) return m_opaque_sp->GetRegexSummaryNavigator()->Delete(ConstString(type_name.GetName())); else return m_opaque_sp->GetSummaryNavigator()->Delete(ConstString(type_name.GetName())); } bool SBTypeCategory::AddTypeFilter (SBTypeNameSpecifier type_name, SBTypeFilter filter) { if (!IsValid()) return false; if (!type_name.IsValid()) return false; if (!filter.IsValid()) return false; if (type_name.IsRegex()) m_opaque_sp->GetRegexFilterNavigator()->Add(lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), filter.GetSP()); else m_opaque_sp->GetFilterNavigator()->Add(ConstString(type_name.GetName()), filter.GetSP()); return true; } bool SBTypeCategory::DeleteTypeFilter (SBTypeNameSpecifier type_name) { if (!IsValid()) return false; if (!type_name.IsValid()) return false; if (type_name.IsRegex()) return m_opaque_sp->GetRegexFilterNavigator()->Delete(ConstString(type_name.GetName())); else return m_opaque_sp->GetFilterNavigator()->Delete(ConstString(type_name.GetName())); } #ifndef LLDB_DISABLE_PYTHON bool SBTypeCategory::AddTypeSynthetic (SBTypeNameSpecifier type_name, SBTypeSynthetic synth) { if (!IsValid()) return false; if (!type_name.IsValid()) return false; if (!synth.IsValid()) return false; // FIXME: we need to iterate over all the Debugger objects and have each of them contain a copy of the function // since we currently have formatters live in a global space, while Python code lives in a specific Debugger-related environment // this should eventually be fixed by deciding a final location in the LLDB object space for formatters if (synth.IsClassCode()) { void *name_token = (void*)ConstString(type_name.GetName()).GetCString(); const char* script = synth.GetData(); StringList input; input.SplitIntoLines(script, strlen(script)); uint32_t num_debuggers = lldb_private::Debugger::GetNumDebuggers(); bool need_set = true; for (uint32_t j = 0; j < num_debuggers; j++) { DebuggerSP debugger_sp = lldb_private::Debugger::GetDebuggerAtIndex(j); if (debugger_sp) { ScriptInterpreter* interpreter_ptr = debugger_sp->GetCommandInterpreter().GetScriptInterpreter(); if (interpreter_ptr) { std::string output; if (interpreter_ptr->GenerateTypeSynthClass(input, output, name_token) && !output.empty()) { if (need_set) { need_set = false; synth.SetClassName(output.c_str()); } } } } } } if (type_name.IsRegex()) m_opaque_sp->GetRegexSyntheticNavigator()->Add(lldb::RegularExpressionSP(new RegularExpression(type_name.GetName())), synth.GetSP()); else m_opaque_sp->GetSyntheticNavigator()->Add(ConstString(type_name.GetName()), synth.GetSP()); return true; } bool SBTypeCategory::DeleteTypeSynthetic (SBTypeNameSpecifier type_name) { if (!IsValid()) return false; if (!type_name.IsValid()) return false; if (type_name.IsRegex()) return m_opaque_sp->GetRegexSyntheticNavigator()->Delete(ConstString(type_name.GetName())); else return m_opaque_sp->GetSyntheticNavigator()->Delete(ConstString(type_name.GetName())); } #endif // LLDB_DISABLE_PYTHON bool SBTypeCategory::GetDescription (lldb::SBStream &description, lldb::DescriptionLevel description_level) { if (!IsValid()) return false; description.Printf("Category name: %s\n",GetName()); return true; } lldb::SBTypeCategory & SBTypeCategory::operator = (const lldb::SBTypeCategory &rhs) { if (this != &rhs) { m_opaque_sp = rhs.m_opaque_sp; } return *this; } bool SBTypeCategory::operator == (lldb::SBTypeCategory &rhs) { if (IsValid() == false) return !rhs.IsValid(); return m_opaque_sp.get() == rhs.m_opaque_sp.get(); } bool SBTypeCategory::operator != (lldb::SBTypeCategory &rhs) { if (IsValid() == false) return rhs.IsValid(); return m_opaque_sp.get() != rhs.m_opaque_sp.get(); } lldb::TypeCategoryImplSP SBTypeCategory::GetSP () { if (!IsValid()) return lldb::TypeCategoryImplSP(); return m_opaque_sp; } void SBTypeCategory::SetSP (const lldb::TypeCategoryImplSP &typecategory_impl_sp) { m_opaque_sp = typecategory_impl_sp; } SBTypeCategory::SBTypeCategory (const lldb::TypeCategoryImplSP &typecategory_impl_sp) : m_opaque_sp(typecategory_impl_sp) { } bool SBTypeCategory::IsDefaultCategory() { if (!IsValid()) return false; return (strcmp(m_opaque_sp->GetName(),"default") == 0); }
gpl-3.0
periodic1236/nutrimatic
openfst-1.0/src/bin/fstprune.cc
1330
// fstprune.cc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: allauzen@google.com (Cyril Allauzen) // // \file // Prunes states and arcs of an FST w.r.t. the shortest path weight. // #include "./prune-main.h" namespace fst { // Register templated main for common arcs types. REGISTER_FST_MAIN(PruneMain, StdArc); } // namespace fst int main(int argc, char **argv) { string usage = "Prunes states and arcs of an FST.\n\n Usage: "; usage += argv[0]; usage += " [in.fst [out.fst]]\n"; usage += " Flags: delta, weight, nstate\n"; std::set_new_handler(FailedNewHandler); SetFlags(usage.c_str(), &argc, &argv, true); if (argc > 3) { ShowUsage(); return 1; } // Invokes PruneMain<Arc> where arc type is determined from argv[1]. return CALL_FST_MAIN(PruneMain, argc, argv); }
gpl-3.0
collectiveaccess/providence
vendor/sabre/xml/tests/Sabre/Xml/Element/Eater.php
2172
<?php declare(strict_types=1); namespace Sabre\Xml\Element; use Sabre\Xml; /** * The intention for this reader class, is to read past the end element. This * should trigger a ParseException. * * @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/). * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ class Eater implements Xml\Element { /** * The serialize method is called during xml writing. * * It should use the $writer argument to encode this object into Xml. * * Important note: it is not needed to create the parent element. The * parent element is already created, and we only have to worry about * attributes, child elements and text (if any). * * Important note 2: If you are writing any new elements, you are also * responsible for closing them. */ public function xmlSerialize(Xml\Writer $writer) { $writer->startElement('{http://sabredav.org/ns}elem1'); $writer->write('hiiii!'); $writer->endElement(); } /** * The deserialize method is called during xml parsing. * * This method is called statictly, this is because in theory this method * may be used as a type of constructor, or factory method. * * Often you want to return an instance of the current class, but you are * free to return other data as well. * * Important note 2: You are responsible for advancing the reader to the * next element. Not doing anything will result in a never-ending loop. * * If you just want to skip parsing for this element altogether, you can * just call $reader->next(); * * $reader->parseSubTree() will parse the entire sub-tree, and advance to * the next element. * * @return mixed */ public static function xmlDeserialize(Xml\Reader $reader) { $reader->next(); $count = 1; while ($count) { $reader->read(); if ($reader->nodeType === $reader::END_ELEMENT) { --$count; } } $reader->read(); } }
gpl-3.0
anicma/orfeo
accionesMasivas/libs/Smarty_Compiler.class.php
93266
<?php /** * Project: Smarty: the PHP compiling template engine * File: Smarty_Compiler.class.php * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @link http://www.smarty.net/ * @author Monte Ohrt <monte at ohrt dot com> * @author Andrei Zmievski <andrei@php.net> * @version 2.6.22 * @copyright 2001-2005 New Digital Group, Inc. * @package Smarty */ /* $Id$ */ /** * Template compiling class * @package Smarty */ class Smarty_Compiler extends Smarty { // internal vars /**#@+ * @access private */ var $_folded_blocks = array(); // keeps folded template blocks var $_current_file = null; // the current template being compiled var $_current_line_no = 1; // line number for error messages var $_capture_stack = array(); // keeps track of nested capture buffers var $_plugin_info = array(); // keeps track of plugins to load var $_init_smarty_vars = false; var $_permitted_tokens = array('true','false','yes','no','on','off','null'); var $_db_qstr_regexp = null; // regexps are setup in the constructor var $_si_qstr_regexp = null; var $_qstr_regexp = null; var $_func_regexp = null; var $_reg_obj_regexp = null; var $_var_bracket_regexp = null; var $_num_const_regexp = null; var $_dvar_guts_regexp = null; var $_dvar_regexp = null; var $_cvar_regexp = null; var $_svar_regexp = null; var $_avar_regexp = null; var $_mod_regexp = null; var $_var_regexp = null; var $_parenth_param_regexp = null; var $_func_call_regexp = null; var $_obj_ext_regexp = null; var $_obj_start_regexp = null; var $_obj_params_regexp = null; var $_obj_call_regexp = null; var $_cacheable_state = 0; var $_cache_attrs_count = 0; var $_nocache_count = 0; var $_cache_serial = null; var $_cache_include = null; var $_strip_depth = 0; var $_additional_newline = "\n"; var $_phpversion = 0; /**#@-*/ /** * The class constructor. */ function Smarty_Compiler() { $this->_phpversion = substr(phpversion(),0,1); // matches double quoted strings: // "foobar" // "foo\"bar" $this->_db_qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'; // matches single quoted strings: // 'foobar' // 'foo\'bar' $this->_si_qstr_regexp = '\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\''; // matches single or double quoted strings $this->_qstr_regexp = '(?:' . $this->_db_qstr_regexp . '|' . $this->_si_qstr_regexp . ')'; // matches bracket portion of vars // [0] // [foo] // [$bar] $this->_var_bracket_regexp = '\[\$?[\w\.]+\]'; // matches numerical constants // 30 // -12 // 13.22 $this->_num_const_regexp = '(?:\-?\d+(?:\.\d+)?)'; // matches $ vars (not objects): // $foo // $foo.bar // $foo.bar.foobar // $foo[0] // $foo[$bar] // $foo[5][blah] // $foo[5].bar[$foobar][4] $this->_dvar_math_regexp = '(?:[\+\*\/\%]|(?:-(?!>)))'; $this->_dvar_math_var_regexp = '[\$\w\.\+\-\*\/\%\d\>\[\]]'; $this->_dvar_guts_regexp = '\w+(?:' . $this->_var_bracket_regexp . ')*(?:\.\$?\w+(?:' . $this->_var_bracket_regexp . ')*)*(?:' . $this->_dvar_math_regexp . '(?:' . $this->_num_const_regexp . '|' . $this->_dvar_math_var_regexp . ')*)?'; $this->_dvar_regexp = '\$' . $this->_dvar_guts_regexp; // matches config vars: // #foo# // #foobar123_foo# $this->_cvar_regexp = '\#\w+\#'; // matches section vars: // %foo.bar% $this->_svar_regexp = '\%\w+\.\w+\%'; // matches all valid variables (no quotes, no modifiers) $this->_avar_regexp = '(?:' . $this->_dvar_regexp . '|' . $this->_cvar_regexp . '|' . $this->_svar_regexp . ')'; // matches valid variable syntax: // $foo // $foo // #foo# // #foo# // "text" // "text" $this->_var_regexp = '(?:' . $this->_avar_regexp . '|' . $this->_qstr_regexp . ')'; // matches valid object call (one level of object nesting allowed in parameters): // $foo->bar // $foo->bar() // $foo->bar("text") // $foo->bar($foo, $bar, "text") // $foo->bar($foo, "foo") // $foo->bar->foo() // $foo->bar->foo->bar() // $foo->bar($foo->bar) // $foo->bar($foo->bar()) // $foo->bar($foo->bar($blah,$foo,44,"foo",$foo[0].bar)) // $foo->getBar()->getFoo() // $foo->getBar()->foo $this->_obj_ext_regexp = '\->(?:\$?' . $this->_dvar_guts_regexp . ')'; $this->_obj_restricted_param_regexp = '(?:' . '(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . ')(?:' . $this->_obj_ext_regexp . '(?:\((?:(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . ')' . '(?:\s*,\s*(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . '))*)?\))?)*)'; $this->_obj_single_param_regexp = '(?:\w+|' . $this->_obj_restricted_param_regexp . '(?:\s*,\s*(?:(?:\w+|' . $this->_var_regexp . $this->_obj_restricted_param_regexp . ')))*)'; $this->_obj_params_regexp = '\((?:' . $this->_obj_single_param_regexp . '(?:\s*,\s*' . $this->_obj_single_param_regexp . ')*)?\)'; $this->_obj_start_regexp = '(?:' . $this->_dvar_regexp . '(?:' . $this->_obj_ext_regexp . ')+)'; $this->_obj_call_regexp = '(?:' . $this->_obj_start_regexp . '(?:' . $this->_obj_params_regexp . ')?(?:' . $this->_dvar_math_regexp . '(?:' . $this->_num_const_regexp . '|' . $this->_dvar_math_var_regexp . ')*)?)'; // matches valid modifier syntax: // |foo // |@foo // |foo:"bar" // |foo:$bar // |foo:"bar":$foobar // |foo|bar // |foo:$foo->bar $this->_mod_regexp = '(?:\|@?\w+(?::(?:\w+|' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_avar_regexp . '|' . $this->_qstr_regexp .'))*)'; // matches valid function name: // foo123 // _foo_bar $this->_func_regexp = '[a-zA-Z_]\w*'; // matches valid registered object: // foo->bar $this->_reg_obj_regexp = '[a-zA-Z_]\w*->[a-zA-Z_]\w*'; // matches valid parameter values: // true // $foo // $foo|bar // #foo# // #foo#|bar // "text" // "text"|bar // $foo->bar $this->_param_regexp = '(?:\s*(?:' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '|' . $this->_num_const_regexp . '|\w+)(?>' . $this->_mod_regexp . '*)\s*)'; // matches valid parenthesised function parameters: // // "text" // $foo, $bar, "text" // $foo|bar, "foo"|bar, $foo->bar($foo)|bar $this->_parenth_param_regexp = '(?:\((?:\w+|' . $this->_param_regexp . '(?:\s*,\s*(?:(?:\w+|' . $this->_param_regexp . ')))*)?\))'; // matches valid function call: // foo() // foo_bar($foo) // _foo_bar($foo,"bar") // foo123($foo,$foo->bar(),"foo") $this->_func_call_regexp = '(?:' . $this->_func_regexp . '\s*(?:' . $this->_parenth_param_regexp . '))'; } /** * compile a resource * * sets $compiled_content to the compiled source * @param string $resource_name * @param string $source_content * @param string $compiled_content * @return true */ function _compile_file($resource_name, $source_content, &$compiled_content) { if ($this->security) { // do not allow php syntax to be executed unless specified if ($this->php_handling == SMARTY_PHP_ALLOW && !$this->security_settings['PHP_HANDLING']) { $this->php_handling = SMARTY_PHP_PASSTHRU; } } $this->_load_filters(); $this->_current_file = $resource_name; $this->_current_line_no = 1; $ldq = preg_quote($this->left_delimiter, '~'); $rdq = preg_quote($this->right_delimiter, '~'); // run template source through prefilter functions if (count($this->_plugins['prefilter']) > 0) { foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) { if ($prefilter === false) continue; if ($prefilter[3] || is_callable($prefilter[0])) { $source_content = call_user_func_array($prefilter[0], array($source_content, &$this)); $this->_plugins['prefilter'][$filter_name][3] = true; } else { $this->_trigger_fatal_error("[plugin] prefilter '$filter_name' is not implemented"); } } } /* fetch all special blocks */ $search = "~{$ldq}\*(.*?)\*{$rdq}|{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}|{$ldq}\s*php\s*{$rdq}(.*?){$ldq}\s*/php\s*{$rdq}~s"; preg_match_all($search, $source_content, $match, PREG_SET_ORDER); $this->_folded_blocks = $match; reset($this->_folded_blocks); /* replace special blocks by "{php}" */ $source_content = preg_replace($search.'e', "'" . $this->_quote_replace($this->left_delimiter) . 'php' . "' . str_repeat(\"\n\", substr_count('\\0', \"\n\")) .'" . $this->_quote_replace($this->right_delimiter) . "'" , $source_content); /* Gather all template tags. */ preg_match_all("~{$ldq}\s*(.*?)\s*{$rdq}~s", $source_content, $_match); $template_tags = $_match[1]; /* Split content by template tags to obtain non-template content. */ $text_blocks = preg_split("~{$ldq}.*?{$rdq}~s", $source_content); /* loop through text blocks */ for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++) { /* match anything resembling php tags */ if (preg_match_all('~(<\?(?:\w+|=)?|\?>|language\s*=\s*[\"\']?\s*php\s*[\"\']?)~is', $text_blocks[$curr_tb], $sp_match)) { /* replace tags with placeholders to prevent recursive replacements */ $sp_match[1] = array_unique($sp_match[1]); usort($sp_match[1], '_smarty_sort_length'); for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) { $text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],'%%%SMARTYSP'.$curr_sp.'%%%',$text_blocks[$curr_tb]); } /* process each one */ for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) { if ($this->php_handling == SMARTY_PHP_PASSTHRU) { /* echo php contents */ $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '<?php echo \''.str_replace("'", "\'", $sp_match[1][$curr_sp]).'\'; ?>'."\n", $text_blocks[$curr_tb]); } else if ($this->php_handling == SMARTY_PHP_QUOTE) { /* quote php tags */ $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', htmlspecialchars($sp_match[1][$curr_sp]), $text_blocks[$curr_tb]); } else if ($this->php_handling == SMARTY_PHP_REMOVE) { /* remove php tags */ $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '', $text_blocks[$curr_tb]); } else { /* SMARTY_PHP_ALLOW, but echo non php starting tags */ $sp_match[1][$curr_sp] = preg_replace('~(<\?(?!php|=|$))~i', '<?php echo \'\\1\'?>'."\n", $sp_match[1][$curr_sp]); $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]); } } } } /* Compile the template tags into PHP code. */ $compiled_tags = array(); for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) { $this->_current_line_no += substr_count($text_blocks[$i], "\n"); $compiled_tags[] = $this->_compile_tag($template_tags[$i]); $this->_current_line_no += substr_count($template_tags[$i], "\n"); } if (count($this->_tag_stack)>0) { list($_open_tag, $_line_no) = end($this->_tag_stack); $this->_syntax_error("unclosed tag \{$_open_tag} (opened line $_line_no).", E_USER_ERROR, __FILE__, __LINE__); return; } /* Reformat $text_blocks between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */ $strip = false; for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) { if ($compiled_tags[$i] == '{strip}') { $compiled_tags[$i] = ''; $strip = true; /* remove leading whitespaces */ $text_blocks[$i + 1] = ltrim($text_blocks[$i + 1]); } if ($strip) { /* strip all $text_blocks before the next '/strip' */ for ($j = $i + 1; $j < $for_max; $j++) { /* remove leading and trailing whitespaces of each line */ $text_blocks[$j] = preg_replace('![\t ]*[\r\n]+[\t ]*!', '', $text_blocks[$j]); if ($compiled_tags[$j] == '{/strip}') { /* remove trailing whitespaces from the last text_block */ $text_blocks[$j] = rtrim($text_blocks[$j]); } $text_blocks[$j] = "<?php echo '" . strtr($text_blocks[$j], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>"; if ($compiled_tags[$j] == '{/strip}') { $compiled_tags[$j] = "\n"; /* slurped by php, but necessary if a newline is following the closing strip-tag */ $strip = false; $i = $j; break; } } } } $compiled_content = ''; $tag_guard = '%%%SMARTYOTG' . md5(uniqid(rand(), true)) . '%%%'; /* Interleave the compiled contents and text blocks to get the final result. */ for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) { if ($compiled_tags[$i] == '') { // tag result empty, remove first newline from following text block $text_blocks[$i+1] = preg_replace('~^(\r\n|\r|\n)~', '', $text_blocks[$i+1]); } // replace legit PHP tags with placeholder $text_blocks[$i] = str_replace('<?', $tag_guard, $text_blocks[$i]); $compiled_tags[$i] = str_replace('<?', $tag_guard, $compiled_tags[$i]); $compiled_content .= $text_blocks[$i] . $compiled_tags[$i]; } $compiled_content .= str_replace('<?', $tag_guard, $text_blocks[$i]); // escape php tags created by interleaving $compiled_content = str_replace('<?', "<?php echo '<?' ?>\n", $compiled_content); $compiled_content = preg_replace("~(?<!')language\s*=\s*[\"\']?\s*php\s*[\"\']?~", "<?php echo 'language=php' ?>\n", $compiled_content); // recover legit tags $compiled_content = str_replace($tag_guard, '<?', $compiled_content); // remove \n from the end of the file, if any if (strlen($compiled_content) && (substr($compiled_content, -1) == "\n") ) { $compiled_content = substr($compiled_content, 0, -1); } if (!empty($this->_cache_serial)) { $compiled_content = "<?php \$this->_cache_serials['".$this->_cache_include."'] = '".$this->_cache_serial."'; ?>" . $compiled_content; } // run compiled template through postfilter functions if (count($this->_plugins['postfilter']) > 0) { foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) { if ($postfilter === false) continue; if ($postfilter[3] || is_callable($postfilter[0])) { $compiled_content = call_user_func_array($postfilter[0], array($compiled_content, &$this)); $this->_plugins['postfilter'][$filter_name][3] = true; } else { $this->_trigger_fatal_error("Smarty plugin error: postfilter '$filter_name' is not implemented"); } } } // put header at the top of the compiled template $template_header = "<?php /* Smarty version ".$this->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n"; $template_header .= " compiled from ".strtr(urlencode($resource_name), array('%2F'=>'/', '%3A'=>':'))." */ ?>\n"; /* Emit code to load needed plugins. */ $this->_plugins_code = ''; if (count($this->_plugin_info)) { $_plugins_params = "array('plugins' => array("; foreach ($this->_plugin_info as $plugin_type => $plugins) { foreach ($plugins as $plugin_name => $plugin_info) { $_plugins_params .= "array('$plugin_type', '$plugin_name', '" . strtr($plugin_info[0], array("'" => "\\'", "\\" => "\\\\")) . "', $plugin_info[1], "; $_plugins_params .= $plugin_info[2] ? 'true),' : 'false),'; } } $_plugins_params .= '))'; $plugins_code = "<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');\nsmarty_core_load_plugins($_plugins_params, \$this); ?>\n"; $template_header .= $plugins_code; $this->_plugin_info = array(); $this->_plugins_code = $plugins_code; } if ($this->_init_smarty_vars) { $template_header .= "<?php require_once(SMARTY_CORE_DIR . 'core.assign_smarty_interface.php');\nsmarty_core_assign_smarty_interface(null, \$this); ?>\n"; $this->_init_smarty_vars = false; } $compiled_content = $template_header . $compiled_content; return true; } /** * Compile a template tag * * @param string $template_tag * @return string */ function _compile_tag($template_tag) { /* Matched comment. */ if (substr($template_tag, 0, 1) == '*' && substr($template_tag, -1) == '*') return ''; /* Split tag into two three parts: command, command modifiers and the arguments. */ if(! preg_match('~^(?:(' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '|\/?' . $this->_reg_obj_regexp . '|\/?' . $this->_func_regexp . ')(' . $this->_mod_regexp . '*)) (?:\s+(.*))?$ ~xs', $template_tag, $match)) { $this->_syntax_error("unrecognized tag: $template_tag", E_USER_ERROR, __FILE__, __LINE__); } $tag_command = $match[1]; $tag_modifier = isset($match[2]) ? $match[2] : null; $tag_args = isset($match[3]) ? $match[3] : null; if (preg_match('~^' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '$~', $tag_command)) { /* tag name is a variable or object */ $_return = $this->_parse_var_props($tag_command . $tag_modifier); return "<?php echo $_return; ?>" . $this->_additional_newline; } /* If the tag name is a registered object, we process it. */ if (preg_match('~^\/?' . $this->_reg_obj_regexp . '$~', $tag_command)) { return $this->_compile_registered_object_tag($tag_command, $this->_parse_attrs($tag_args), $tag_modifier); } switch ($tag_command) { case 'include': return $this->_compile_include_tag($tag_args); case 'include_php': return $this->_compile_include_php_tag($tag_args); case 'if': $this->_push_tag('if'); return $this->_compile_if_tag($tag_args); case 'else': list($_open_tag) = end($this->_tag_stack); if ($_open_tag != 'if' && $_open_tag != 'elseif') $this->_syntax_error('unexpected {else}', E_USER_ERROR, __FILE__, __LINE__); else $this->_push_tag('else'); return '<?php else: ?>'; case 'elseif': list($_open_tag) = end($this->_tag_stack); if ($_open_tag != 'if' && $_open_tag != 'elseif') $this->_syntax_error('unexpected {elseif}', E_USER_ERROR, __FILE__, __LINE__); if ($_open_tag == 'if') $this->_push_tag('elseif'); return $this->_compile_if_tag($tag_args, true); case '/if': $this->_pop_tag('if'); return '<?php endif; ?>'; case 'capture': return $this->_compile_capture_tag(true, $tag_args); case '/capture': return $this->_compile_capture_tag(false); case 'ldelim': return $this->left_delimiter; case 'rdelim': return $this->right_delimiter; case 'section': $this->_push_tag('section'); return $this->_compile_section_start($tag_args); case 'sectionelse': $this->_push_tag('sectionelse'); return "<?php endfor; else: ?>"; break; case '/section': $_open_tag = $this->_pop_tag('section'); if ($_open_tag == 'sectionelse') return "<?php endif; ?>"; else return "<?php endfor; endif; ?>"; case 'foreach': $this->_push_tag('foreach'); return $this->_compile_foreach_start($tag_args); break; case 'foreachelse': $this->_push_tag('foreachelse'); return "<?php endforeach; else: ?>"; case '/foreach': $_open_tag = $this->_pop_tag('foreach'); if ($_open_tag == 'foreachelse') return "<?php endif; unset(\$_from); ?>"; else return "<?php endforeach; endif; unset(\$_from); ?>"; break; case 'strip': case '/strip': if (substr($tag_command, 0, 1)=='/') { $this->_pop_tag('strip'); if (--$this->_strip_depth==0) { /* outermost closing {/strip} */ $this->_additional_newline = "\n"; return '{' . $tag_command . '}'; } } else { $this->_push_tag('strip'); if ($this->_strip_depth++==0) { /* outermost opening {strip} */ $this->_additional_newline = ""; return '{' . $tag_command . '}'; } } return ''; case 'php': /* handle folded tags replaced by {php} */ list(, $block) = each($this->_folded_blocks); $this->_current_line_no += substr_count($block[0], "\n"); /* the number of matched elements in the regexp in _compile_file() determins the type of folded tag that was found */ switch (count($block)) { case 2: /* comment */ return ''; case 3: /* literal */ return "<?php echo '" . strtr($block[2], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>" . $this->_additional_newline; case 4: /* php */ if ($this->security && !$this->security_settings['PHP_TAGS']) { $this->_syntax_error("(secure mode) php tags not permitted", E_USER_WARNING, __FILE__, __LINE__); return; } return '<?php ' . $block[3] .' ?>'; } break; case 'insert': return $this->_compile_insert_tag($tag_args); default: if ($this->_compile_compiler_tag($tag_command, $tag_args, $output)) { return $output; } else if ($this->_compile_block_tag($tag_command, $tag_args, $tag_modifier, $output)) { return $output; } else if ($this->_compile_custom_tag($tag_command, $tag_args, $tag_modifier, $output)) { return $output; } else { $this->_syntax_error("unrecognized tag '$tag_command'", E_USER_ERROR, __FILE__, __LINE__); } } } /** * compile the custom compiler tag * * sets $output to the compiled custom compiler tag * @param string $tag_command * @param string $tag_args * @param string $output * @return boolean */ function _compile_compiler_tag($tag_command, $tag_args, &$output) { $found = false; $have_function = true; /* * First we check if the compiler function has already been registered * or loaded from a plugin file. */ if (isset($this->_plugins['compiler'][$tag_command])) { $found = true; $plugin_func = $this->_plugins['compiler'][$tag_command][0]; if (!is_callable($plugin_func)) { $message = "compiler function '$tag_command' is not implemented"; $have_function = false; } } /* * Otherwise we need to load plugin file and look for the function * inside it. */ else if ($plugin_file = $this->_get_plugin_filepath('compiler', $tag_command)) { $found = true; include_once $plugin_file; $plugin_func = 'smarty_compiler_' . $tag_command; if (!is_callable($plugin_func)) { $message = "plugin function $plugin_func() not found in $plugin_file\n"; $have_function = false; } else { $this->_plugins['compiler'][$tag_command] = array($plugin_func, null, null, null, true); } } /* * True return value means that we either found a plugin or a * dynamically registered function. False means that we didn't and the * compiler should now emit code to load custom function plugin for this * tag. */ if ($found) { if ($have_function) { $output = call_user_func_array($plugin_func, array($tag_args, &$this)); if($output != '') { $output = '<?php ' . $this->_push_cacheable_state('compiler', $tag_command) . $output . $this->_pop_cacheable_state('compiler', $tag_command) . ' ?>'; } } else { $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__); } return true; } else { return false; } } /** * compile block function tag * * sets $output to compiled block function tag * @param string $tag_command * @param string $tag_args * @param string $tag_modifier * @param string $output * @return boolean */ function _compile_block_tag($tag_command, $tag_args, $tag_modifier, &$output) { if (substr($tag_command, 0, 1) == '/') { $start_tag = false; $tag_command = substr($tag_command, 1); } else $start_tag = true; $found = false; $have_function = true; /* * First we check if the block function has already been registered * or loaded from a plugin file. */ if (isset($this->_plugins['block'][$tag_command])) { $found = true; $plugin_func = $this->_plugins['block'][$tag_command][0]; if (!is_callable($plugin_func)) { $message = "block function '$tag_command' is not implemented"; $have_function = false; } } /* * Otherwise we need to load plugin file and look for the function * inside it. */ else if ($plugin_file = $this->_get_plugin_filepath('block', $tag_command)) { $found = true; include_once $plugin_file; $plugin_func = 'smarty_block_' . $tag_command; if (!function_exists($plugin_func)) { $message = "plugin function $plugin_func() not found in $plugin_file\n"; $have_function = false; } else { $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true); } } if (!$found) { return false; } else if (!$have_function) { $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__); return true; } /* * Even though we've located the plugin function, compilation * happens only once, so the plugin will still need to be loaded * at runtime for future requests. */ $this->_add_plugin('block', $tag_command); if ($start_tag) $this->_push_tag($tag_command); else $this->_pop_tag($tag_command); if ($start_tag) { $output = '<?php ' . $this->_push_cacheable_state('block', $tag_command); $attrs = $this->_parse_attrs($tag_args); $_cache_attrs=''; $arg_list = $this->_compile_arg_list('block', $tag_command, $attrs, $_cache_attrs); $output .= "$_cache_attrs\$this->_tag_stack[] = array('$tag_command', array(".implode(',', $arg_list).')); '; $output .= '$_block_repeat=true;' . $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);'; $output .= 'while ($_block_repeat) { ob_start(); ?>'; } else { $output = '<?php $_block_content = ob_get_contents(); ob_end_clean(); '; $_out_tag_text = $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat)'; if ($tag_modifier != '') { $this->_parse_modifiers($_out_tag_text, $tag_modifier); } $output .= '$_block_repeat=false;echo ' . $_out_tag_text . '; } '; $output .= " array_pop(\$this->_tag_stack); " . $this->_pop_cacheable_state('block', $tag_command) . '?>'; } return true; } /** * compile custom function tag * * @param string $tag_command * @param string $tag_args * @param string $tag_modifier * @return string */ function _compile_custom_tag($tag_command, $tag_args, $tag_modifier, &$output) { $found = false; $have_function = true; /* * First we check if the custom function has already been registered * or loaded from a plugin file. */ if (isset($this->_plugins['function'][$tag_command])) { $found = true; $plugin_func = $this->_plugins['function'][$tag_command][0]; if (!is_callable($plugin_func)) { $message = "custom function '$tag_command' is not implemented"; $have_function = false; } } /* * Otherwise we need to load plugin file and look for the function * inside it. */ else if ($plugin_file = $this->_get_plugin_filepath('function', $tag_command)) { $found = true; include_once $plugin_file; $plugin_func = 'smarty_function_' . $tag_command; if (!function_exists($plugin_func)) { $message = "plugin function $plugin_func() not found in $plugin_file\n"; $have_function = false; } else { $this->_plugins['function'][$tag_command] = array($plugin_func, null, null, null, true); } } if (!$found) { return false; } else if (!$have_function) { $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__); return true; } /* declare plugin to be loaded on display of the template that we compile right now */ $this->_add_plugin('function', $tag_command); $_cacheable_state = $this->_push_cacheable_state('function', $tag_command); $attrs = $this->_parse_attrs($tag_args); $_cache_attrs = ''; $arg_list = $this->_compile_arg_list('function', $tag_command, $attrs, $_cache_attrs); $output = $this->_compile_plugin_call('function', $tag_command).'(array('.implode(',', $arg_list)."), \$this)"; if($tag_modifier != '') { $this->_parse_modifiers($output, $tag_modifier); } if($output != '') { $output = '<?php ' . $_cacheable_state . $_cache_attrs . 'echo ' . $output . ';' . $this->_pop_cacheable_state('function', $tag_command) . "?>" . $this->_additional_newline; } return true; } /** * compile a registered object tag * * @param string $tag_command * @param array $attrs * @param string $tag_modifier * @return string */ function _compile_registered_object_tag($tag_command, $attrs, $tag_modifier) { if (substr($tag_command, 0, 1) == '/') { $start_tag = false; $tag_command = substr($tag_command, 1); } else { $start_tag = true; } list($object, $obj_comp) = explode('->', $tag_command); $arg_list = array(); if(count($attrs)) { $_assign_var = false; foreach ($attrs as $arg_name => $arg_value) { if($arg_name == 'assign') { $_assign_var = $arg_value; unset($attrs['assign']); continue; } if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } } if($this->_reg_objects[$object][2]) { // smarty object argument format $args = "array(".implode(',', (array)$arg_list)."), \$this"; } else { // traditional argument format $args = implode(',', array_values($attrs)); if (empty($args)) { $args = ''; } } $prefix = ''; $postfix = ''; $newline = ''; if(!is_object($this->_reg_objects[$object][0])) { $this->_trigger_fatal_error("registered '$object' is not an object" , $this->_current_file, $this->_current_line_no, __FILE__, __LINE__); } elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) { $this->_trigger_fatal_error("'$obj_comp' is not a registered component of object '$object'", $this->_current_file, $this->_current_line_no, __FILE__, __LINE__); } elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) { // method if(in_array($obj_comp, $this->_reg_objects[$object][3])) { // block method if ($start_tag) { $prefix = "\$this->_tag_stack[] = array('$obj_comp', $args); "; $prefix .= "\$_block_repeat=true; \$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], null, \$this, \$_block_repeat); "; $prefix .= "while (\$_block_repeat) { ob_start();"; $return = null; $postfix = ''; } else { $prefix = "\$_obj_block_content = ob_get_contents(); ob_end_clean(); \$_block_repeat=false;"; $return = "\$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], \$_obj_block_content, \$this, \$_block_repeat)"; $postfix = "} array_pop(\$this->_tag_stack);"; } } else { // non-block method $return = "\$this->_reg_objects['$object'][0]->$obj_comp($args)"; } } else { // property $return = "\$this->_reg_objects['$object'][0]->$obj_comp"; } if($return != null) { if($tag_modifier != '') { $this->_parse_modifiers($return, $tag_modifier); } if(!empty($_assign_var)) { $output = "\$this->assign('" . $this->_dequote($_assign_var) ."', $return);"; } else { $output = 'echo ' . $return . ';'; $newline = $this->_additional_newline; } } else { $output = ''; } return '<?php ' . $prefix . $output . $postfix . "?>" . $newline; } /** * Compile {insert ...} tag * * @param string $tag_args * @return string */ function _compile_insert_tag($tag_args) { $attrs = $this->_parse_attrs($tag_args); $name = $this->_dequote($attrs['name']); if (empty($name)) { return $this->_syntax_error("missing insert name", E_USER_ERROR, __FILE__, __LINE__); } if (!preg_match('~^\w+$~', $name)) { return $this->_syntax_error("'insert: 'name' must be an insert function name", E_USER_ERROR, __FILE__, __LINE__); } if (!empty($attrs['script'])) { $delayed_loading = true; } else { $delayed_loading = false; } foreach ($attrs as $arg_name => $arg_value) { if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } $this->_add_plugin('insert', $name, $delayed_loading); $_params = "array('args' => array(".implode(', ', (array)$arg_list)."))"; return "<?php require_once(SMARTY_CORE_DIR . 'core.run_insert_handler.php');\necho smarty_core_run_insert_handler($_params, \$this); ?>" . $this->_additional_newline; } /** * Compile {include ...} tag * * @param string $tag_args * @return string */ function _compile_include_tag($tag_args) { $attrs = $this->_parse_attrs($tag_args); $arg_list = array(); if (empty($attrs['file'])) { $this->_syntax_error("missing 'file' attribute in include tag", E_USER_ERROR, __FILE__, __LINE__); } foreach ($attrs as $arg_name => $arg_value) { if ($arg_name == 'file') { $include_file = $arg_value; continue; } else if ($arg_name == 'assign') { $assign_var = $arg_value; continue; } if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } $output = '<?php '; if (isset($assign_var)) { $output .= "ob_start();\n"; } $output .= "\$_smarty_tpl_vars = \$this->_tpl_vars;\n"; $_params = "array('smarty_include_tpl_file' => " . $include_file . ", 'smarty_include_vars' => array(".implode(',', (array)$arg_list)."))"; $output .= "\$this->_smarty_include($_params);\n" . "\$this->_tpl_vars = \$_smarty_tpl_vars;\n" . "unset(\$_smarty_tpl_vars);\n"; if (isset($assign_var)) { $output .= "\$this->assign(" . $assign_var . ", ob_get_contents()); ob_end_clean();\n"; } $output .= ' ?>'; return $output; } /** * Compile {include ...} tag * * @param string $tag_args * @return string */ function _compile_include_php_tag($tag_args) { $attrs = $this->_parse_attrs($tag_args); if (empty($attrs['file'])) { $this->_syntax_error("missing 'file' attribute in include_php tag", E_USER_ERROR, __FILE__, __LINE__); } $assign_var = (empty($attrs['assign'])) ? '' : $this->_dequote($attrs['assign']); $once_var = (empty($attrs['once']) || $attrs['once']=='false') ? 'false' : 'true'; $arg_list = array(); foreach($attrs as $arg_name => $arg_value) { if($arg_name != 'file' AND $arg_name != 'once' AND $arg_name != 'assign') { if(is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } } $_params = "array('smarty_file' => " . $attrs['file'] . ", 'smarty_assign' => '$assign_var', 'smarty_once' => $once_var, 'smarty_include_vars' => array(".implode(',', $arg_list)."))"; return "<?php require_once(SMARTY_CORE_DIR . 'core.smarty_include_php.php');\nsmarty_core_smarty_include_php($_params, \$this); ?>" . $this->_additional_newline; } /** * Compile {section ...} tag * * @param string $tag_args * @return string */ function _compile_section_start($tag_args) { $attrs = $this->_parse_attrs($tag_args); $arg_list = array(); $output = '<?php '; $section_name = $attrs['name']; if (empty($section_name)) { $this->_syntax_error("missing section name", E_USER_ERROR, __FILE__, __LINE__); } $output .= "unset(\$this->_sections[$section_name]);\n"; $section_props = "\$this->_sections[$section_name]"; foreach ($attrs as $attr_name => $attr_value) { switch ($attr_name) { case 'loop': $output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int)\$_loop); unset(\$_loop);\n"; break; case 'show': if (is_bool($attr_value)) $show_attr_value = $attr_value ? 'true' : 'false'; else $show_attr_value = "(bool)$attr_value"; $output .= "{$section_props}['show'] = $show_attr_value;\n"; break; case 'name': $output .= "{$section_props}['$attr_name'] = $attr_value;\n"; break; case 'max': case 'start': $output .= "{$section_props}['$attr_name'] = (int)$attr_value;\n"; break; case 'step': $output .= "{$section_props}['$attr_name'] = ((int)$attr_value) == 0 ? 1 : (int)$attr_value;\n"; break; default: $this->_syntax_error("unknown section attribute - '$attr_name'", E_USER_ERROR, __FILE__, __LINE__); break; } } if (!isset($attrs['show'])) $output .= "{$section_props}['show'] = true;\n"; if (!isset($attrs['loop'])) $output .= "{$section_props}['loop'] = 1;\n"; if (!isset($attrs['max'])) $output .= "{$section_props}['max'] = {$section_props}['loop'];\n"; else $output .= "if ({$section_props}['max'] < 0)\n" . " {$section_props}['max'] = {$section_props}['loop'];\n"; if (!isset($attrs['step'])) $output .= "{$section_props}['step'] = 1;\n"; if (!isset($attrs['start'])) $output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n"; else { $output .= "if ({$section_props}['start'] < 0)\n" . " {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" . "else\n" . " {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n"; } $output .= "if ({$section_props}['show']) {\n"; if (!isset($attrs['start']) && !isset($attrs['step']) && !isset($attrs['max'])) { $output .= " {$section_props}['total'] = {$section_props}['loop'];\n"; } else { $output .= " {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n"; } $output .= " if ({$section_props}['total'] == 0)\n" . " {$section_props}['show'] = false;\n" . "} else\n" . " {$section_props}['total'] = 0;\n"; $output .= "if ({$section_props}['show']):\n"; $output .= " for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1; {$section_props}['iteration'] <= {$section_props}['total']; {$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n"; $output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n"; $output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n"; $output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n"; $output .= "{$section_props}['first'] = ({$section_props}['iteration'] == 1);\n"; $output .= "{$section_props}['last'] = ({$section_props}['iteration'] == {$section_props}['total']);\n"; $output .= "?>"; return $output; } /** * Compile {foreach ...} tag. * * @param string $tag_args * @return string */ function _compile_foreach_start($tag_args) { $attrs = $this->_parse_attrs($tag_args); $arg_list = array(); if (empty($attrs['from'])) { return $this->_syntax_error("foreach: missing 'from' attribute", E_USER_ERROR, __FILE__, __LINE__); } $from = $attrs['from']; if (empty($attrs['item'])) { return $this->_syntax_error("foreach: missing 'item' attribute", E_USER_ERROR, __FILE__, __LINE__); } $item = $this->_dequote($attrs['item']); if (!preg_match('~^\w+$~', $item)) { return $this->_syntax_error("foreach: 'item' must be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__); } if (isset($attrs['key'])) { $key = $this->_dequote($attrs['key']); if (!preg_match('~^\w+$~', $key)) { return $this->_syntax_error("foreach: 'key' must to be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__); } $key_part = "\$this->_tpl_vars['$key'] => "; } else { $key = null; $key_part = ''; } if (isset($attrs['name'])) { $name = $attrs['name']; } else { $name = null; } $output = '<?php '; $output .= "\$_from = $from; if (!is_array(\$_from) && !is_object(\$_from)) { settype(\$_from, 'array'); }"; if (isset($name)) { $foreach_props = "\$this->_foreach[$name]"; $output .= "{$foreach_props} = array('total' => count(\$_from), 'iteration' => 0);\n"; $output .= "if ({$foreach_props}['total'] > 0):\n"; $output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n"; $output .= " {$foreach_props}['iteration']++;\n"; } else { $output .= "if (count(\$_from)):\n"; $output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n"; } $output .= '?>'; return $output; } /** * Compile {capture} .. {/capture} tags * * @param boolean $start true if this is the {capture} tag * @param string $tag_args * @return string */ function _compile_capture_tag($start, $tag_args = '') { $attrs = $this->_parse_attrs($tag_args); if ($start) { $buffer = isset($attrs['name']) ? $attrs['name'] : "'default'"; $assign = isset($attrs['assign']) ? $attrs['assign'] : null; $append = isset($attrs['append']) ? $attrs['append'] : null; $output = "<?php ob_start(); ?>"; $this->_capture_stack[] = array($buffer, $assign, $append); } else { list($buffer, $assign, $append) = array_pop($this->_capture_stack); $output = "<?php \$this->_smarty_vars['capture'][$buffer] = ob_get_contents(); "; if (isset($assign)) { $output .= " \$this->assign($assign, ob_get_contents());"; } if (isset($append)) { $output .= " \$this->append($append, ob_get_contents());"; } $output .= "ob_end_clean(); ?>"; } return $output; } /** * Compile {if ...} tag * * @param string $tag_args * @param boolean $elseif if true, uses elseif instead of if * @return string */ function _compile_if_tag($tag_args, $elseif = false) { /* Tokenize args for 'if' tag. */ preg_match_all('~(?> ' . $this->_obj_call_regexp . '(?:' . $this->_mod_regexp . '*)? | # valid object call ' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)? | # var or quoted string \-?0[xX][0-9a-fA-F]+|\-?\d+(?:\.\d+)?|\.\d+|!==|===|==|!=|<>|<<|>>|<=|>=|\&\&|\|\||\(|\)|,|\!|\^|=|\&|\~|<|>|\||\%|\+|\-|\/|\*|\@ | # valid non-word token \b\w+\b | # valid word token \S+ # anything else )~x', $tag_args, $match); $tokens = $match[0]; if(empty($tokens)) { $_error_msg = $elseif ? "'elseif'" : "'if'"; $_error_msg .= ' statement requires arguments'; $this->_syntax_error($_error_msg, E_USER_ERROR, __FILE__, __LINE__); } // make sure we have balanced parenthesis $token_count = array_count_values($tokens); if(isset($token_count['(']) && $token_count['('] != $token_count[')']) { $this->_syntax_error("unbalanced parenthesis in if statement", E_USER_ERROR, __FILE__, __LINE__); } $is_arg_stack = array(); for ($i = 0; $i < count($tokens); $i++) { $token = &$tokens[$i]; switch (strtolower($token)) { case '!': case '%': case '!==': case '==': case '===': case '>': case '<': case '!=': case '<>': case '<<': case '>>': case '<=': case '>=': case '&&': case '||': case '|': case '^': case '&': case '~': case ')': case ',': case '+': case '-': case '*': case '/': case '@': break; case 'eq': $token = '=='; break; case 'ne': case 'neq': $token = '!='; break; case 'lt': $token = '<'; break; case 'le': case 'lte': $token = '<='; break; case 'gt': $token = '>'; break; case 'ge': case 'gte': $token = '>='; break; case 'and': $token = '&&'; break; case 'or': $token = '||'; break; case 'not': $token = '!'; break; case 'mod': $token = '%'; break; case '(': array_push($is_arg_stack, $i); break; case 'is': /* If last token was a ')', we operate on the parenthesized expression. The start of the expression is on the stack. Otherwise, we operate on the last encountered token. */ if ($tokens[$i-1] == ')') { $is_arg_start = array_pop($is_arg_stack); if ($is_arg_start != 0) { if (preg_match('~^' . $this->_func_regexp . '$~', $tokens[$is_arg_start-1])) { $is_arg_start--; } } } else $is_arg_start = $i-1; /* Construct the argument for 'is' expression, so it knows what to operate on. */ $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start)); /* Pass all tokens from next one until the end to the 'is' expression parsing function. The function will return modified tokens, where the first one is the result of the 'is' expression and the rest are the tokens it didn't touch. */ $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1)); /* Replace the old tokens with the new ones. */ array_splice($tokens, $is_arg_start, count($tokens), $new_tokens); /* Adjust argument start so that it won't change from the current position for the next iteration. */ $i = $is_arg_start; break; default: if(preg_match('~^' . $this->_func_regexp . '$~', $token) ) { // function call if($this->security && !in_array($token, $this->security_settings['IF_FUNCS'])) { $this->_syntax_error("(secure mode) '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__); } } elseif(preg_match('~^' . $this->_var_regexp . '$~', $token) && (strpos('+-*/^%&|', substr($token, -1)) === false) && isset($tokens[$i+1]) && $tokens[$i+1] == '(') { // variable function call $this->_syntax_error("variable function call '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__); } elseif(preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)$~', $token)) { // object or variable $token = $this->_parse_var_props($token); } elseif(is_numeric($token)) { // number, skip it } else { $this->_syntax_error("unidentified token '$token'", E_USER_ERROR, __FILE__, __LINE__); } break; } } if ($elseif) return '<?php elseif ('.implode(' ', $tokens).'): ?>'; else return '<?php if ('.implode(' ', $tokens).'): ?>'; } function _compile_arg_list($type, $name, $attrs, &$cache_code) { $arg_list = array(); if (isset($type) && isset($name) && isset($this->_plugins[$type]) && isset($this->_plugins[$type][$name]) && empty($this->_plugins[$type][$name][4]) && is_array($this->_plugins[$type][$name][5]) ) { /* we have a list of parameters that should be cached */ $_cache_attrs = $this->_plugins[$type][$name][5]; $_count = $this->_cache_attrs_count++; $cache_code = "\$_cache_attrs =& \$this->_smarty_cache_attrs('$this->_cache_serial','$_count');"; } else { /* no parameters are cached */ $_cache_attrs = null; } foreach ($attrs as $arg_name => $arg_value) { if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; if (is_null($arg_value)) $arg_value = 'null'; if ($_cache_attrs && in_array($arg_name, $_cache_attrs)) { $arg_list[] = "'$arg_name' => (\$this->_cache_including) ? \$_cache_attrs['$arg_name'] : (\$_cache_attrs['$arg_name']=$arg_value)"; } else { $arg_list[] = "'$arg_name' => $arg_value"; } } return $arg_list; } /** * Parse is expression * * @param string $is_arg * @param array $tokens * @return array */ function _parse_is_expr($is_arg, $tokens) { $expr_end = 0; $negate_expr = false; if (($first_token = array_shift($tokens)) == 'not') { $negate_expr = true; $expr_type = array_shift($tokens); } else $expr_type = $first_token; switch ($expr_type) { case 'even': if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') { $expr_end++; $expr_arg = $tokens[$expr_end++]; $expr = "!(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))"; } else $expr = "!(1 & $is_arg)"; break; case 'odd': if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') { $expr_end++; $expr_arg = $tokens[$expr_end++]; $expr = "(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))"; } else $expr = "(1 & $is_arg)"; break; case 'div': if (@$tokens[$expr_end] == 'by') { $expr_end++; $expr_arg = $tokens[$expr_end++]; $expr = "!($is_arg % " . $this->_parse_var_props($expr_arg) . ")"; } else { $this->_syntax_error("expecting 'by' after 'div'", E_USER_ERROR, __FILE__, __LINE__); } break; default: $this->_syntax_error("unknown 'is' expression - '$expr_type'", E_USER_ERROR, __FILE__, __LINE__); break; } if ($negate_expr) { $expr = "!($expr)"; } array_splice($tokens, 0, $expr_end, $expr); return $tokens; } /** * Parse attribute string * * @param string $tag_args * @return array */ function _parse_attrs($tag_args) { /* Tokenize tag attributes. */ preg_match_all('~(?:' . $this->_obj_call_regexp . '|' . $this->_qstr_regexp . ' | (?>[^"\'=\s]+) )+ | [=] ~x', $tag_args, $match); $tokens = $match[0]; $attrs = array(); /* Parse state: 0 - expecting attribute name 1 - expecting '=' 2 - expecting attribute value (not '=') */ $state = 0; foreach ($tokens as $token) { switch ($state) { case 0: /* If the token is a valid identifier, we set attribute name and go to state 1. */ if (preg_match('~^\w+$~', $token)) { $attr_name = $token; $state = 1; } else $this->_syntax_error("invalid attribute name: '$token'", E_USER_ERROR, __FILE__, __LINE__); break; case 1: /* If the token is '=', then we go to state 2. */ if ($token == '=') { $state = 2; } else $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__); break; case 2: /* If token is not '=', we set the attribute value and go to state 0. */ if ($token != '=') { /* We booleanize the token if it's a non-quoted possible boolean value. */ if (preg_match('~^(on|yes|true)$~', $token)) { $token = 'true'; } else if (preg_match('~^(off|no|false)$~', $token)) { $token = 'false'; } else if ($token == 'null') { $token = 'null'; } else if (preg_match('~^' . $this->_num_const_regexp . '|0[xX][0-9a-fA-F]+$~', $token)) { /* treat integer literally */ } else if (!preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . ')*$~', $token)) { /* treat as a string, double-quote it escaping quotes */ $token = '"'.addslashes($token).'"'; } $attrs[$attr_name] = $token; $state = 0; } else $this->_syntax_error("'=' cannot be an attribute value", E_USER_ERROR, __FILE__, __LINE__); break; } $last_token = $token; } if($state != 0) { if($state == 1) { $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__); } else { $this->_syntax_error("missing attribute value", E_USER_ERROR, __FILE__, __LINE__); } } $this->_parse_vars_props($attrs); return $attrs; } /** * compile multiple variables and section properties tokens into * PHP code * * @param array $tokens */ function _parse_vars_props(&$tokens) { foreach($tokens as $key => $val) { $tokens[$key] = $this->_parse_var_props($val); } } /** * compile single variable and section properties token into * PHP code * * @param string $val * @param string $tag_attrs * @return string */ function _parse_var_props($val) { $val = trim($val); if(preg_match('~^(' . $this->_obj_call_regexp . '|' . $this->_dvar_regexp . ')(' . $this->_mod_regexp . '*)$~', $val, $match)) { // $ variable or object $return = $this->_parse_var($match[1]); $modifiers = $match[2]; if (!empty($this->default_modifiers) && !preg_match('~(^|\|)smarty:nodefaults($|\|)~',$modifiers)) { $_default_mod_string = implode('|',(array)$this->default_modifiers); $modifiers = empty($modifiers) ? $_default_mod_string : $_default_mod_string . '|' . $modifiers; } $this->_parse_modifiers($return, $modifiers); return $return; } elseif (preg_match('~^' . $this->_db_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // double quoted text preg_match('~^(' . $this->_db_qstr_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match); $return = $this->_expand_quoted_text($match[1]); if($match[2] != '') { $this->_parse_modifiers($return, $match[2]); } return $return; } elseif(preg_match('~^' . $this->_num_const_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // numerical constant preg_match('~^(' . $this->_num_const_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match); if($match[2] != '') { $this->_parse_modifiers($match[1], $match[2]); return $match[1]; } } elseif(preg_match('~^' . $this->_si_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // single quoted text preg_match('~^(' . $this->_si_qstr_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match); if($match[2] != '') { $this->_parse_modifiers($match[1], $match[2]); return $match[1]; } } elseif(preg_match('~^' . $this->_cvar_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // config var return $this->_parse_conf_var($val); } elseif(preg_match('~^' . $this->_svar_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // section var return $this->_parse_section_prop($val); } elseif(!in_array($val, $this->_permitted_tokens) && !is_numeric($val)) { // literal string return $this->_expand_quoted_text('"' . strtr($val, array('\\' => '\\\\', '"' => '\\"')) .'"'); } return $val; } /** * expand quoted text with embedded variables * * @param string $var_expr * @return string */ function _expand_quoted_text($var_expr) { // if contains unescaped $, expand it if(preg_match_all('~(?:\`(?<!\\\\)\$' . $this->_dvar_guts_regexp . '(?:' . $this->_obj_ext_regexp . ')*\`)|(?:(?<!\\\\)\$\w+(\[[a-zA-Z0-9]+\])*)~', $var_expr, $_match)) { $_match = $_match[0]; $_replace = array(); foreach($_match as $_var) { $_replace[$_var] = '".(' . $this->_parse_var(str_replace('`','',$_var)) . ')."'; } $var_expr = strtr($var_expr, $_replace); $_return = preg_replace('~\.""|(?<!\\\\)""\.~', '', $var_expr); } else { $_return = $var_expr; } // replace double quoted literal string with single quotes $_return = preg_replace('~^"([\s\w]+)"$~',"'\\1'",$_return); // escape dollar sign if not printing a var $_return = preg_replace('~\$(\W)~',"\\\\\$\\1",$_return); return $_return; } /** * parse variable expression into PHP code * * @param string $var_expr * @param string $output * @return string */ function _parse_var($var_expr) { $_has_math = false; $_has_php4_method_chaining = false; $_math_vars = preg_split('~('.$this->_dvar_math_regexp.'|'.$this->_qstr_regexp.')~', $var_expr, -1, PREG_SPLIT_DELIM_CAPTURE); if(count($_math_vars) > 1) { $_first_var = ""; $_complete_var = ""; $_output = ""; // simple check if there is any math, to stop recursion (due to modifiers with "xx % yy" as parameter) foreach($_math_vars as $_k => $_math_var) { $_math_var = $_math_vars[$_k]; if(!empty($_math_var) || is_numeric($_math_var)) { // hit a math operator, so process the stuff which came before it if(preg_match('~^' . $this->_dvar_math_regexp . '$~', $_math_var)) { $_has_math = true; if(!empty($_complete_var) || is_numeric($_complete_var)) { $_output .= $this->_parse_var($_complete_var); } // just output the math operator to php $_output .= $_math_var; if(empty($_first_var)) $_first_var = $_complete_var; $_complete_var = ""; } else { $_complete_var .= $_math_var; } } } if($_has_math) { if(!empty($_complete_var) || is_numeric($_complete_var)) $_output .= $this->_parse_var($_complete_var); // get the modifiers working (only the last var from math + modifier is left) $var_expr = $_complete_var; } } // prevent cutting of first digit in the number (we _definitly_ got a number if the first char is a digit) if(is_numeric(substr($var_expr, 0, 1))) $_var_ref = $var_expr; else $_var_ref = substr($var_expr, 1); if(!$_has_math) { // get [foo] and .foo and ->foo and (...) pieces preg_match_all('~(?:^\w+)|' . $this->_obj_params_regexp . '|(?:' . $this->_var_bracket_regexp . ')|->\$?\w+|\.\$?\w+|\S+~', $_var_ref, $match); $_indexes = $match[0]; $_var_name = array_shift($_indexes); /* Handle $smarty.* variable references as a special case. */ if ($_var_name == 'smarty') { /* * If the reference could be compiled, use the compiled output; * otherwise, fall back on the $smarty variable generated at * run-time. */ if (($smarty_ref = $this->_compile_smarty_ref($_indexes)) !== null) { $_output = $smarty_ref; } else { $_var_name = substr(array_shift($_indexes), 1); $_output = "\$this->_smarty_vars['$_var_name']"; } } elseif(is_numeric($_var_name) && is_numeric(substr($var_expr, 0, 1))) { // because . is the operator for accessing arrays thru inidizes we need to put it together again for floating point numbers if(count($_indexes) > 0) { $_var_name .= implode("", $_indexes); $_indexes = array(); } $_output = $_var_name; } else { $_output = "\$this->_tpl_vars['$_var_name']"; } foreach ($_indexes as $_index) { if (substr($_index, 0, 1) == '[') { $_index = substr($_index, 1, -1); if (is_numeric($_index)) { $_output .= "[$_index]"; } elseif (substr($_index, 0, 1) == '$') { if (strpos($_index, '.') !== false) { $_output .= '[' . $this->_parse_var($_index) . ']'; } else { $_output .= "[\$this->_tpl_vars['" . substr($_index, 1) . "']]"; } } else { $_var_parts = explode('.', $_index); $_var_section = $_var_parts[0]; $_var_section_prop = isset($_var_parts[1]) ? $_var_parts[1] : 'index'; $_output .= "[\$this->_sections['$_var_section']['$_var_section_prop']]"; } } else if (substr($_index, 0, 1) == '.') { if (substr($_index, 1, 1) == '$') $_output .= "[\$this->_tpl_vars['" . substr($_index, 2) . "']]"; else $_output .= "['" . substr($_index, 1) . "']"; } else if (substr($_index,0,2) == '->') { if(substr($_index,2,2) == '__') { $this->_syntax_error('call to internal object members is not allowed', E_USER_ERROR, __FILE__, __LINE__); } elseif($this->security && substr($_index, 2, 1) == '_') { $this->_syntax_error('(secure) call to private object member is not allowed', E_USER_ERROR, __FILE__, __LINE__); } elseif (substr($_index, 2, 1) == '$') { if ($this->security) { $this->_syntax_error('(secure) call to dynamic object member is not allowed', E_USER_ERROR, __FILE__, __LINE__); } else { $_output .= '->{(($_var=$this->_tpl_vars[\''.substr($_index,3).'\']) && substr($_var,0,2)!=\'__\') ? $_var : $this->trigger_error("cannot access property \\"$_var\\"")}'; } } else { if ($this->_phpversion < 5) { $_has_php4_method_chaining = true; $_output .= "; \$_foo = \$_foo"; } $_output .= $_index; } } elseif (substr($_index, 0, 1) == '(') { $_index = $this->_parse_parenth_args($_index); $_output .= $_index; } else { $_output .= $_index; } } } if ($_has_php4_method_chaining) { $_tmp = str_replace("'","\'",'$_foo = '.$_output.'; return $_foo;'); return "eval('".$_tmp."')"; } else { return $_output; } } /** * parse arguments in function call parenthesis * * @param string $parenth_args * @return string */ function _parse_parenth_args($parenth_args) { preg_match_all('~' . $this->_param_regexp . '~',$parenth_args, $match); $orig_vals = $match = $match[0]; $this->_parse_vars_props($match); $replace = array(); for ($i = 0, $count = count($match); $i < $count; $i++) { $replace[$orig_vals[$i]] = $match[$i]; } return strtr($parenth_args, $replace); } /** * parse configuration variable expression into PHP code * * @param string $conf_var_expr */ function _parse_conf_var($conf_var_expr) { $parts = explode('|', $conf_var_expr, 2); $var_ref = $parts[0]; $modifiers = isset($parts[1]) ? $parts[1] : ''; $var_name = substr($var_ref, 1, -1); $output = "\$this->_config[0]['vars']['$var_name']"; $this->_parse_modifiers($output, $modifiers); return $output; } /** * parse section property expression into PHP code * * @param string $section_prop_expr * @return string */ function _parse_section_prop($section_prop_expr) { $parts = explode('|', $section_prop_expr, 2); $var_ref = $parts[0]; $modifiers = isset($parts[1]) ? $parts[1] : ''; preg_match('!%(\w+)\.(\w+)%!', $var_ref, $match); $section_name = $match[1]; $prop_name = $match[2]; $output = "\$this->_sections['$section_name']['$prop_name']"; $this->_parse_modifiers($output, $modifiers); return $output; } /** * parse modifier chain into PHP code * * sets $output to parsed modified chain * @param string $output * @param string $modifier_string */ function _parse_modifiers(&$output, $modifier_string) { preg_match_all('~\|(@?\w+)((?>:(?:'. $this->_qstr_regexp . '|[^|]+))*)~', '|' . $modifier_string, $_match); list(, $_modifiers, $modifier_arg_strings) = $_match; for ($_i = 0, $_for_max = count($_modifiers); $_i < $_for_max; $_i++) { $_modifier_name = $_modifiers[$_i]; if($_modifier_name == 'smarty') { // skip smarty modifier continue; } preg_match_all('~:(' . $this->_qstr_regexp . '|[^:]+)~', $modifier_arg_strings[$_i], $_match); $_modifier_args = $_match[1]; if (substr($_modifier_name, 0, 1) == '@') { $_map_array = false; $_modifier_name = substr($_modifier_name, 1); } else { $_map_array = true; } if (empty($this->_plugins['modifier'][$_modifier_name]) && !$this->_get_plugin_filepath('modifier', $_modifier_name) && function_exists($_modifier_name)) { if ($this->security && !in_array($_modifier_name, $this->security_settings['MODIFIER_FUNCS'])) { $this->_trigger_fatal_error("[plugin] (secure mode) modifier '$_modifier_name' is not allowed" , $this->_current_file, $this->_current_line_no, __FILE__, __LINE__); } else { $this->_plugins['modifier'][$_modifier_name] = array($_modifier_name, null, null, false); } } $this->_add_plugin('modifier', $_modifier_name); $this->_parse_vars_props($_modifier_args); if($_modifier_name == 'default') { // supress notifications of default modifier vars and args if(substr($output, 0, 1) == '$') { $output = '@' . $output; } if(isset($_modifier_args[0]) && substr($_modifier_args[0], 0, 1) == '$') { $_modifier_args[0] = '@' . $_modifier_args[0]; } } if (count($_modifier_args) > 0) $_modifier_args = ', '.implode(', ', $_modifier_args); else $_modifier_args = ''; if ($_map_array) { $output = "((is_array(\$_tmp=$output)) ? \$this->_run_mod_handler('$_modifier_name', true, \$_tmp$_modifier_args) : " . $this->_compile_plugin_call('modifier', $_modifier_name) . "(\$_tmp$_modifier_args))"; } else { $output = $this->_compile_plugin_call('modifier', $_modifier_name)."($output$_modifier_args)"; } } } /** * add plugin * * @param string $type * @param string $name * @param boolean? $delayed_loading */ function _add_plugin($type, $name, $delayed_loading = null) { if (!isset($this->_plugin_info[$type])) { $this->_plugin_info[$type] = array(); } if (!isset($this->_plugin_info[$type][$name])) { $this->_plugin_info[$type][$name] = array($this->_current_file, $this->_current_line_no, $delayed_loading); } } /** * Compiles references of type $smarty.foo * * @param string $indexes * @return string */ function _compile_smarty_ref(&$indexes) { /* Extract the reference name. */ $_ref = substr($indexes[0], 1); foreach($indexes as $_index_no=>$_index) { if (substr($_index, 0, 1) != '.' && $_index_no<2 || !preg_match('~^(\.|\[|->)~', $_index)) { $this->_syntax_error('$smarty' . implode('', array_slice($indexes, 0, 2)) . ' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__); } } switch ($_ref) { case 'now': $compiled_ref = 'time()'; $_max_index = 1; break; case 'foreach': array_shift($indexes); $_var = $this->_parse_var_props(substr($indexes[0], 1)); $_propname = substr($indexes[1], 1); $_max_index = 1; switch ($_propname) { case 'index': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['iteration']-1)"; break; case 'first': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['iteration'] <= 1)"; break; case 'last': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['iteration'] == \$this->_foreach[$_var]['total'])"; break; case 'show': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['total'] > 0)"; break; default: unset($_max_index); $compiled_ref = "\$this->_foreach[$_var]"; } break; case 'section': array_shift($indexes); $_var = $this->_parse_var_props(substr($indexes[0], 1)); $compiled_ref = "\$this->_sections[$_var]"; break; case 'get': $compiled_ref = ($this->request_use_auto_globals) ? '$_GET' : "\$GLOBALS['HTTP_GET_VARS']"; break; case 'post': $compiled_ref = ($this->request_use_auto_globals) ? '$_POST' : "\$GLOBALS['HTTP_POST_VARS']"; break; case 'cookies': $compiled_ref = ($this->request_use_auto_globals) ? '$_COOKIE' : "\$GLOBALS['HTTP_COOKIE_VARS']"; break; case 'env': $compiled_ref = ($this->request_use_auto_globals) ? '$_ENV' : "\$GLOBALS['HTTP_ENV_VARS']"; break; case 'server': $compiled_ref = ($this->request_use_auto_globals) ? '$_SERVER' : "\$GLOBALS['HTTP_SERVER_VARS']"; break; case 'session': $compiled_ref = ($this->request_use_auto_globals) ? '$_SESSION' : "\$GLOBALS['HTTP_SESSION_VARS']"; break; /* * These cases are handled either at run-time or elsewhere in the * compiler. */ case 'request': if ($this->request_use_auto_globals) { $compiled_ref = '$_REQUEST'; break; } else { $this->_init_smarty_vars = true; } return null; case 'capture': return null; case 'template': $compiled_ref = "'$this->_current_file'"; $_max_index = 1; break; case 'version': $compiled_ref = "'$this->_version'"; $_max_index = 1; break; case 'const': if ($this->security && !$this->security_settings['ALLOW_CONSTANTS']) { $this->_syntax_error("(secure mode) constants not permitted", E_USER_WARNING, __FILE__, __LINE__); return; } array_shift($indexes); if (preg_match('!^\.\w+$!', $indexes[0])) { $compiled_ref = '@' . substr($indexes[0], 1); } else { $_val = $this->_parse_var_props(substr($indexes[0], 1)); $compiled_ref = '@constant(' . $_val . ')'; } $_max_index = 1; break; case 'config': $compiled_ref = "\$this->_config[0]['vars']"; $_max_index = 3; break; case 'ldelim': $compiled_ref = "'$this->left_delimiter'"; break; case 'rdelim': $compiled_ref = "'$this->right_delimiter'"; break; default: $this->_syntax_error('$smarty.' . $_ref . ' is an unknown reference', E_USER_ERROR, __FILE__, __LINE__); break; } if (isset($_max_index) && count($indexes) > $_max_index) { $this->_syntax_error('$smarty' . implode('', $indexes) .' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__); } array_shift($indexes); return $compiled_ref; } /** * compiles call to plugin of type $type with name $name * returns a string containing the function-name or method call * without the paramter-list that would have follow to make the * call valid php-syntax * * @param string $type * @param string $name * @return string */ function _compile_plugin_call($type, $name) { if (isset($this->_plugins[$type][$name])) { /* plugin loaded */ if (is_array($this->_plugins[$type][$name][0])) { return ((is_object($this->_plugins[$type][$name][0][0])) ? "\$this->_plugins['$type']['$name'][0][0]->" /* method callback */ : (string)($this->_plugins[$type][$name][0][0]).'::' /* class callback */ ). $this->_plugins[$type][$name][0][1]; } else { /* function callback */ return $this->_plugins[$type][$name][0]; } } else { /* plugin not loaded -> auto-loadable-plugin */ return 'smarty_'.$type.'_'.$name; } } /** * load pre- and post-filters */ function _load_filters() { if (count($this->_plugins['prefilter']) > 0) { foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) { if ($prefilter === false) { unset($this->_plugins['prefilter'][$filter_name]); $_params = array('plugins' => array(array('prefilter', $filter_name, null, null, false))); require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins($_params, $this); } } } if (count($this->_plugins['postfilter']) > 0) { foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) { if ($postfilter === false) { unset($this->_plugins['postfilter'][$filter_name]); $_params = array('plugins' => array(array('postfilter', $filter_name, null, null, false))); require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins($_params, $this); } } } } /** * Quote subpattern references * * @param string $string * @return string */ function _quote_replace($string) { return strtr($string, array('\\' => '\\\\', '$' => '\\$')); } /** * display Smarty syntax error * * @param string $error_msg * @param integer $error_type * @param string $file * @param integer $line */ function _syntax_error($error_msg, $error_type = E_USER_ERROR, $file=null, $line=null) { $this->_trigger_fatal_error("syntax error: $error_msg", $this->_current_file, $this->_current_line_no, $file, $line, $error_type); } /** * check if the compilation changes from cacheable to * non-cacheable state with the beginning of the current * plugin. return php-code to reflect the transition. * @return string */ function _push_cacheable_state($type, $name) { $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4]; if ($_cacheable || 0<$this->_cacheable_state++) return ''; if (!isset($this->_cache_serial)) $this->_cache_serial = md5(uniqid('Smarty')); $_ret = 'if ($this->caching && !$this->_cache_including): echo \'{nocache:' . $this->_cache_serial . '#' . $this->_nocache_count . '}\'; endif;'; return $_ret; } /** * check if the compilation changes from non-cacheable to * cacheable state with the end of the current plugin return * php-code to reflect the transition. * @return string */ function _pop_cacheable_state($type, $name) { $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4]; if ($_cacheable || --$this->_cacheable_state>0) return ''; return 'if ($this->caching && !$this->_cache_including): echo \'{/nocache:' . $this->_cache_serial . '#' . ($this->_nocache_count++) . '}\'; endif;'; } /** * push opening tag-name, file-name and line-number on the tag-stack * @param string the opening tag's name */ function _push_tag($open_tag) { array_push($this->_tag_stack, array($open_tag, $this->_current_line_no)); } /** * pop closing tag-name * raise an error if this stack-top doesn't match with the closing tag * @param string the closing tag's name * @return string the opening tag's name */ function _pop_tag($close_tag) { $message = ''; if (count($this->_tag_stack)>0) { list($_open_tag, $_line_no) = array_pop($this->_tag_stack); if ($close_tag == $_open_tag) { return $_open_tag; } if ($close_tag == 'if' && ($_open_tag == 'else' || $_open_tag == 'elseif' )) { return $this->_pop_tag($close_tag); } if ($close_tag == 'section' && $_open_tag == 'sectionelse') { $this->_pop_tag($close_tag); return $_open_tag; } if ($close_tag == 'foreach' && $_open_tag == 'foreachelse') { $this->_pop_tag($close_tag); return $_open_tag; } if ($_open_tag == 'else' || $_open_tag == 'elseif') { $_open_tag = 'if'; } elseif ($_open_tag == 'sectionelse') { $_open_tag = 'section'; } elseif ($_open_tag == 'foreachelse') { $_open_tag = 'foreach'; } $message = " expected {/$_open_tag} (opened line $_line_no)."; } $this->_syntax_error("mismatched tag {/$close_tag}.$message", E_USER_ERROR, __FILE__, __LINE__); } } /** * compare to values by their string length * * @access private * @param string $a * @param string $b * @return 0|-1|1 */ function _smarty_sort_length($a, $b) { if($a == $b) return 0; if(strlen($a) == strlen($b)) return ($a > $b) ? -1 : 1; return (strlen($a) > strlen($b)) ? -1 : 1; } /* vim: set et: */ ?>
gpl-3.0
joruri/joruri-maps
lib/system/controller/scaffold/commitment.rb
1814
# encoding: utf-8 module System::Controller::Scaffold::Commitment def rollback(item) _rollback(item) end protected def _rollback(item, options = {}) conditions = {:unid => item.unid, :version => params[:version], :name => 'attributes'} com = System::Commitment.find(:first, :conditions => conditions) respond_to do |format| if item.editable? && com.rollback(item) options[:after_process].call if options[:after_process] location = url_for(:action => :index) status = params[:_created_status] || :created flash[:notice] = options[:notice] || 'ロールバック処理が完了しました' #system_log.add(:item => item, :action => 'rollback') format.html { redirect_to location } format.xml { render :xml => to_xml(item), :status => status, :location => location } else format.html { render :action => :show } format.xml { render :xml => com.errors, :status => :unprocessable_entity } end end end def _commitment_attributes(item) c = System::Commitment.find(params[:cid]) self.class.layout 'empty' respond_to do |format| format.html { html = '' c.attributes_to_hash.each{|k, v| html += "#{k.to_s} : #{v.to_s}<hr />"} render :text => html } format.xml { render :xml => c.attributes_to_hash } end end def _commitment_page(item) c = System::Commitment.find(params[:cid]) self.class.layout 'empty' return render(:text => c.page_data) end def _commitment_rollback(item) c = System::Commitment.find(params[:cid]) c.attributes_to_hash.each do |k, v| next if k.to_s == 'id' next if k.to_s =~ /\_at/ eval("item.#{k.to_s} = v") end item.state = 'draft' _update(item) end end
gpl-3.0
idega/com.idega.core
src/java/com/idega/user/data/UserGroupRepresentativeHomeImpl.java
945
package com.idega.user.data; public class UserGroupRepresentativeHomeImpl extends com.idega.user.data.GroupHomeImpl implements UserGroupRepresentativeHome //public class UserGroupRepresentativeHomeImpl extends com.idega.data.IDOFactory implements UserGroupRepresentativeHome { protected Class getEntityInterfaceClass(){ return UserGroupRepresentative.class; } // public UserGroupRepresentative create() throws javax.ejb.CreateException{ // return (UserGroupRepresentative) super.createIDO(); // } // // // public UserGroupRepresentative findByPrimaryKey(Object pk) throws javax.ejb.FinderException{ // return (UserGroupRepresentative) super.findByPrimaryKeyIDO(pk); // } public java.lang.String getGroupType(){ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.lang.String theReturn = ((UserGroupRepresentativeBMPBean)entity).ejbHomeGetGroupType(); this.idoCheckInPooledEntity(entity); return theReturn; } }
gpl-3.0
micaherne/moodle
install/lang/nl/admin.php
1918
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Automatically generated strings for Moodle 2.1 installer * * Do not edit this file manually! It contains just a subset of strings * needed during the very first steps of installation. This file was * generated automatically by export-installer.php (which is part of AMOS * {@link http://docs.moodle.org/en/Development:Languages/AMOS}) using the * list of strings defined in /install/stringnames.txt. * * @package installer * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['clianswerno'] = 'n'; $string['cliansweryes'] = 'j'; $string['cliincorrectvalueerror'] = 'Fout, waarde "{$a->value}" voor de optie "{$a->option}" is niet juist'; $string['cliincorrectvalueretry'] = 'Foute waarde. Probeer opnieuw'; $string['clitypevalue'] = 'type waarde'; $string['clitypevaluedefault'] = 'type waarde, druk op Enter om de standaardwaarde te gebruiken ({$a})'; $string['cliunknowoption'] = 'Onherkenbare opties: {$a} gebruik --help optie.'; $string['cliyesnoprompt'] = 'typ j (ja) of n (nee)'; $string['environmentrequireinstall'] = 'moet geïnstalleerd/ingeschakeld zijn'; $string['environmentrequireversion'] = 'versie {$a->needed} is vereist en je gebruikt nu versie {$a->current}';
gpl-3.0
kroody/mosh
src/frontend/stmclient.cc
13056
/* Mosh: the mobile shell Copyright 2012 Keith Winstein This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <errno.h> #include <locale.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/poll.h> #include <sys/ioctl.h> #include <sys/types.h> #include <pwd.h> #include <signal.h> #include <time.h> #if HAVE_PTY_H #include <pty.h> #elif HAVE_UTIL_H #include <util.h> #endif #include "sigfd.h" #include "stmclient.h" #include "swrite.h" #include "completeterminal.h" #include "user.h" #include "fatal_assert.h" #include "locale_utils.h" #include "networktransport.cc" void STMClient::init( void ) { if ( !is_utf8_locale() ) { fprintf( stderr, "mosh-client needs a UTF-8 native locale to run.\n\n" ); fprintf( stderr, "Unfortunately, the locale environment variables currently specify\nthe character set \"%s\".\n\n", locale_charset() ); int unused __attribute((unused)) = system( "locale" ); exit( 1 ); } /* Verify terminal configuration */ if ( tcgetattr( STDIN_FILENO, &saved_termios ) < 0 ) { perror( "tcgetattr" ); exit( 1 ); } /* Put terminal driver in raw mode */ raw_termios = saved_termios; #ifdef HAVE_IUTF8 if ( !(raw_termios.c_iflag & IUTF8) ) { // fprintf( stderr, "Warning: Locale is UTF-8 but termios IUTF8 flag not set. Setting IUTF8 flag.\n" ); /* Probably not really necessary since we are putting terminal driver into raw mode anyway. */ raw_termios.c_iflag |= IUTF8; } #endif /* HAVE_IUTF8 */ cfmakeraw( &raw_termios ); if ( tcsetattr( STDIN_FILENO, TCSANOW, &raw_termios ) < 0 ) { perror( "tcsetattr" ); exit( 1 ); } /* Put terminal in application-cursor-key mode */ swrite( STDOUT_FILENO, Terminal::Emulator::open().c_str() ); /* Add our name to window title */ if ( !getenv( "MOSH_TITLE_NOPREFIX" ) ) { overlays.set_title_prefix( wstring( L"[mosh] " ) ); } wchar_t tmp[ 128 ]; swprintf( tmp, 128, L"Nothing received from server on UDP port %d.", port ); connecting_notification = wstring( tmp ); } void STMClient::shutdown( void ) { /* Restore screen state */ overlays.get_notification_engine().set_notification_string( wstring( L"" ) ); overlays.get_notification_engine().server_heard( timestamp() ); overlays.set_title_prefix( wstring( L"" ) ); output_new_frame(); /* Restore terminal and terminal-driver state */ swrite( STDOUT_FILENO, Terminal::Emulator::close().c_str() ); if ( tcsetattr( STDIN_FILENO, TCSANOW, &saved_termios ) < 0 ) { perror( "tcsetattr" ); exit( 1 ); } if ( still_connecting() ) { fprintf( stderr, "mosh did not make a successful connection to %s:%d.\n", ip.c_str(), port ); fprintf( stderr, "Please verify that UDP port %d is not firewalled and can reach the server.\n\n", port ); fprintf( stderr, "(By default, mosh uses a UDP port between 60000 and 61000. The -p option\nselects a specific UDP port number.)\n" ); } else if ( network ) { if ( !clean_shutdown ) { fprintf( stderr, "\n\nmosh did not shut down cleanly. Please note that the\nmosh-server process may still be running on the server.\n" ); } } } void STMClient::main_init( void ) { /* establish a fd for signals */ signal_fd = sigfd_init(); if ( signal_fd < 0 ) { perror( "sigfd_init" ); return; } fatal_assert( sigfd_trap( SIGWINCH ) == 0 ); fatal_assert( sigfd_trap( SIGTERM ) == 0 ); fatal_assert( sigfd_trap( SIGINT ) == 0 ); fatal_assert( sigfd_trap( SIGHUP ) == 0 ); fatal_assert( sigfd_trap( SIGPIPE ) == 0 ); fatal_assert( sigfd_trap( SIGTSTP ) == 0 ); fatal_assert( sigfd_trap( SIGCONT ) == 0 ); /* get initial window size */ if ( ioctl( STDIN_FILENO, TIOCGWINSZ, &window_size ) < 0 ) { perror( "ioctl TIOCGWINSZ" ); return; } /* local state */ local_framebuffer = new Terminal::Framebuffer( window_size.ws_col, window_size.ws_row ); new_state = new Terminal::Framebuffer( 1, 1 ); /* initialize screen */ string init = display.new_frame( false, *local_framebuffer, *local_framebuffer ); swrite( STDOUT_FILENO, init.data(), init.size() ); /* open network */ Network::UserStream blank; Terminal::Complete local_terminal( window_size.ws_col, window_size.ws_row ); network = new Network::Transport< Network::UserStream, Terminal::Complete >( blank, local_terminal, key.c_str(), ip.c_str(), port ); network->set_send_delay( 1 ); /* minimal delay on outgoing keystrokes */ /* tell server the size of the terminal */ network->get_current_state().push_back( Parser::Resize( window_size.ws_col, window_size.ws_row ) ); } void STMClient::output_new_frame( void ) { if ( !network ) { /* clean shutdown even when not initialized */ return; } /* fetch target state */ *new_state = network->get_latest_remote_state().state.get_fb(); /* apply local overlays */ overlays.apply( *new_state ); /* apply any mutations */ display.downgrade( *new_state ); /* calculate minimal difference from where we are */ const string diff( display.new_frame( !repaint_requested, *local_framebuffer, *new_state ) ); swrite( STDOUT_FILENO, diff.data(), diff.size() ); repaint_requested = false; /* switch pointers */ Terminal::Framebuffer *tmp = new_state; new_state = local_framebuffer; local_framebuffer = tmp; } bool STMClient::process_network_input( void ) { network->recv(); /* Now give hints to the overlays */ overlays.get_notification_engine().server_heard( network->get_latest_remote_state().timestamp ); overlays.get_prediction_engine().set_local_frame_acked( network->get_sent_state_acked() ); overlays.get_prediction_engine().set_send_interval( network->send_interval() ); overlays.get_prediction_engine().set_local_frame_late_acked( network->get_latest_remote_state().state.get_echo_ack() ); return true; } bool STMClient::process_user_input( int fd ) { const int buf_size = 16384; char buf[ buf_size ]; /* fill buffer if possible */ ssize_t bytes_read = read( fd, buf, buf_size ); if ( bytes_read == 0 ) { /* EOF */ return false; } else if ( bytes_read < 0 ) { perror( "read" ); return false; } if ( !network->shutdown_in_progress() ) { overlays.get_prediction_engine().set_local_frame_sent( network->get_sent_state_last() ); for ( int i = 0; i < bytes_read; i++ ) { char the_byte = buf[ i ]; overlays.get_prediction_engine().new_user_byte( the_byte, *local_framebuffer ); if ( quit_sequence_started ) { if ( the_byte == '.' ) { /* Quit sequence is Ctrl-^ . */ if ( network->has_remote_addr() && (!network->shutdown_in_progress()) ) { overlays.get_notification_engine().set_notification_string( wstring( L"Exiting on user request..." ), true ); network->start_shutdown(); return true; } else { return false; } } else if ( the_byte == '^' ) { /* Emulation sequence to type Ctrl-^ is Ctrl-^ ^ */ network->get_current_state().push_back( Parser::UserByte( 0x1E ) ); } else { /* Ctrl-^ followed by anything other than . and ^ gets sent literally */ network->get_current_state().push_back( Parser::UserByte( 0x1E ) ); network->get_current_state().push_back( Parser::UserByte( the_byte ) ); } quit_sequence_started = false; continue; } quit_sequence_started = (the_byte == 0x1E); if ( quit_sequence_started ) { continue; } if ( the_byte == 0x0C ) { /* Ctrl-L */ repaint_requested = true; } network->get_current_state().push_back( Parser::UserByte( the_byte ) ); } } return true; } bool STMClient::process_resize( void ) { /* get new size */ if ( ioctl( STDIN_FILENO, TIOCGWINSZ, &window_size ) < 0 ) { perror( "ioctl TIOCGWINSZ" ); return false; } /* tell remote emulator */ Parser::Resize res( window_size.ws_col, window_size.ws_row ); if ( !network->shutdown_in_progress() ) { network->get_current_state().push_back( res ); } /* note remote emulator will probably reply with its own Resize to adjust our state */ /* tell prediction engine */ overlays.get_prediction_engine().reset(); return true; } void STMClient::main( void ) { /* initialize signal handling and structures */ main_init(); /* prepare to poll for events */ struct pollfd pollfds[ 3 ]; pollfds[ 0 ].fd = network->fd(); pollfds[ 0 ].events = POLLIN; pollfds[ 1 ].fd = STDIN_FILENO; pollfds[ 1 ].events = POLLIN; pollfds[ 2 ].fd = signal_fd; pollfds[ 2 ].events = POLLIN; while ( 1 ) { try { output_new_frame(); int wait_time = min( network->wait_time(), overlays.wait_time() ); /* Handle startup "Connecting..." message */ if ( still_connecting() ) { wait_time = min( 250, wait_time ); } int active_fds = poll( pollfds, 3, wait_time ); if ( active_fds < 0 && errno == EINTR ) { continue; } else if ( active_fds < 0 ) { perror( "poll" ); break; } if ( pollfds[ 0 ].revents & POLLIN ) { /* packet received from the network */ if ( !process_network_input() ) { return; } } if ( pollfds[ 1 ].revents & POLLIN ) { /* input from the user needs to be fed to the network */ if ( !process_user_input( pollfds[ 1 ].fd ) ) { if ( !network->has_remote_addr() ) { break; } else if ( !network->shutdown_in_progress() ) { overlays.get_notification_engine().set_notification_string( wstring( L"Exiting..." ), true ); network->start_shutdown(); } } } if ( pollfds[ 2 ].revents & POLLIN ) { int signo = sigfd_read(); if ( signo == SIGWINCH ) { /* resize */ if ( !process_resize() ) { return; } } else if ( signo > 0 ) { /* shutdown signal */ if ( !network->has_remote_addr() ) { break; } else if ( !network->shutdown_in_progress() ) { overlays.get_notification_engine().set_notification_string( wstring( L"Signal received, shutting down..." ), true ); network->start_shutdown(); } } } if ( (pollfds[ 0 ].revents) & (POLLERR | POLLHUP | POLLNVAL) ) { /* network problem */ break; } if ( (pollfds[ 1 ].revents) & (POLLERR | POLLHUP | POLLNVAL) ) { /* user problem */ if ( !network->has_remote_addr() ) { break; } else if ( !network->shutdown_in_progress() ) { overlays.get_notification_engine().set_notification_string( wstring( L"Exiting..." ), true ); network->start_shutdown(); } } /* quit if our shutdown has been acknowledged */ if ( network->shutdown_in_progress() && network->shutdown_acknowledged() ) { clean_shutdown = true; break; } /* quit after shutdown acknowledgement timeout */ if ( network->shutdown_in_progress() && network->shutdown_ack_timed_out() ) { break; } /* quit if we received and acknowledged a shutdown request */ if ( network->counterparty_shutdown_ack_sent() ) { clean_shutdown = true; break; } /* write diagnostic message if can't reach server */ if ( still_connecting() && (!network->shutdown_in_progress()) && (timestamp() - network->get_latest_remote_state().timestamp > 250) ) { if ( timestamp() - network->get_latest_remote_state().timestamp > 15000 ) { if ( !network->shutdown_in_progress() ) { network->start_shutdown(); } } overlays.get_notification_engine().set_notification_string( connecting_notification ); } else if ( (network->get_remote_state_num() != 0) && (overlays.get_notification_engine().get_notification_string() == connecting_notification) ) { overlays.get_notification_engine().set_notification_string( L"" ); } network->tick(); } catch ( Network::NetworkException e ) { if ( !network->shutdown_in_progress() ) { wchar_t tmp[ 128 ]; swprintf( tmp, 128, L"%s: %s", e.function.c_str(), strerror( e.the_errno ) ); overlays.get_notification_engine().set_notification_string( wstring( tmp ) ); } struct timespec req; req.tv_sec = 0; req.tv_nsec = 200000000; /* 0.2 sec */ nanosleep( &req, NULL ); } catch ( Crypto::CryptoException e ) { if ( e.fatal ) { throw; } else { wchar_t tmp[ 128 ]; swprintf( tmp, 128, L"Crypto exception: %s", e.text.c_str() ); overlays.get_notification_engine().set_notification_string( wstring( tmp ) ); } } } }
gpl-3.0
toidi/hypertable
src/cc/Tools/merge_diff/merge_diff.cc
3290
/** * Copyright (C) 2007-2012 Hypertable, Inc. * * This file is part of Hypertable. * * Hypertable is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 3 of * the License. * * Hypertable is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include "Common/Compat.h" #include <fstream> #include <iostream> #include <string> #include "Common/System.h" #include "Common/Usage.h" using namespace Hypertable; using namespace std; namespace { const char *usage[] = { "usage: merge_diff <file-a> <file-b>", "", " This program performs a diff of two sorted files. The files must be", " sorted as if they had been created with the following commands:", "", " $ LC_ALL=C sort <input-a> > <file-a>", " $ LC_ALL=C sort <input-b> > <file-b>", "", " The output is indeterminate if the files are not properly sorted. ", "", (const char *)0 }; } int main(int argc, char **argv) { const char *file_a=0, *file_b=0; std::ifstream in_a; std::ifstream in_b; string line_a, line_b; int state = 0; int cmpval; bool a_cached = false; bool b_cached = false; System::initialize(argv[0]); for (int i=1; i<argc; i++) { if (argv[i][0] == '-') Usage::dump_and_exit(usage); else if (file_a == 0) file_a = argv[i]; else if (file_b == 0) file_b = argv[i]; else Usage::dump_and_exit(usage); } if (file_b == 0) Usage::dump_and_exit(usage); in_a.open(file_a, ifstream::in); in_b.open(file_b, ifstream::in); while (in_a.good()) { if (!in_b.good()) { if (state == 2) cout << "---" << endl; if (a_cached) { cout << "< " << line_a << endl; a_cached = false; } while (in_a.good()) { if (getline(in_a, line_a)) cout << "< " << line_a << endl; } break; } if (!a_cached && !getline(in_a, line_a)) continue; if (!b_cached && !getline(in_b, line_b)) { a_cached = true; continue; } if ((cmpval = strcmp(line_a.c_str(), line_b.c_str())) < 0) { a_cached = false; b_cached = true; if (state == 2) cout << "---" << endl; state = 1; cout << "< " << line_a << endl; } else if (cmpval > 0) { a_cached = true; b_cached = false; if (state == 1) cout << "---" << endl; state = 2; cout << "> " << line_b << endl; } else a_cached = b_cached = false; } if (in_b.good()) { if (state == 1) cout << "---" << endl; if (b_cached) { cout << "> " << line_b << endl; b_cached = false; } while (in_b.good()) { if (getline(in_b, line_b)) cout << "> " << line_b << endl; } } in_a.close(); in_b.close(); }
gpl-3.0
bcdev/beam
beam-core/src/test/java/org/esa/beam/framework/dataop/projection/SinusoidalTest.java
2925
/* * Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.beam.framework.dataop.projection; import org.geotools.parameter.ParameterGroup; import org.opengis.referencing.operation.MathTransform; import java.util.ArrayList; import java.util.List; /** * Test data is taken from General Cartographic Transformation Package (GCTP). * It can be retrieved from: ftp://edcftp.cr.usgs.gov/pub/software/gctpc/ */ public final class SinusoidalTest extends AbstractProjectionTest<Sinusoidal.Provider> { @Override protected Sinusoidal.Provider createProvider() { return new Sinusoidal.Provider(); } @Override public MathTransform createMathTransform(Sinusoidal.Provider provider) { final ParameterGroup params = new ParameterGroup(provider.getParameters()); params.parameter("semi_major").setValue(6370997.0); params.parameter("semi_minor").setValue(6370997.0); params.parameter("central_meridian").setValue(30.0); params.parameter("false_easting").setValue(0.0); params.parameter("false_northing").setValue(0.0); return provider.createMathTransform(params); } @Override protected List<ProjTestData> createTestData() { List<ProjTestData> dataList = new ArrayList<ProjTestData>(13); dataList.add(new ProjTestData(-180.0, -87.5, 727537.84417, -9729551.49991)); dataList.add(new ProjTestData(-180.0, -59.5, 8465349.66961, -6616095.01994)); dataList.add(new ProjTestData(-173.0, -45.5, 12236190.25202, -5059366.77995)); dataList.add(new ProjTestData(-75.0, -35.0, -9563978.40140, -3891820.59996)); dataList.add(new ProjTestData(-8.5, 45.5, -3000594.42486, 5059366.77995)); dataList.add(new ProjTestData(5.5, -38.5, -2132039.38258, -4281002.65996)); dataList.add(new ProjTestData(33.5, -28.0, 343627.36306, -3113456.47997)); dataList.add(new ProjTestData(96.5, -21.0, 6903322.31757, -2335092.35998)); dataList.add(new ProjTestData(103.5, -7.0, 8111904.27468, -778364.11999)); dataList.add(new ProjTestData(163.0, -63.0, 6714028.40048, -7005277.07993)); dataList.add(new ProjTestData(177.0, 87.5, 712987.08729, 9729551.49991)); return dataList; } }
gpl-3.0
Jonnyfriday/JDweather
webpage/v13/config.php
2192
<!DOCTYPE html> <html> <head> <title>Configuration Page</title> <link rel="stylesheet" href="stylesheet_conf.css"> <script> function myFunction() { alert("Make sure DHT11 sensor is connected by the following:\n Ground \n Power: 3v \n Data: GPIO 4"); var getInput = document.getElementById('tcon').value; localStorage.setItem("storageName",getInput); } function myFunction2() { var getInput = document.getElementById('tdis').value; localStorage.setItem("storageName",getInput); } function myFunction3() { alert("Make sure BMP180 sensor is connected by the following:\n Ground \n Power: 5v \n SCL: GPIO 3 \n SDA: GPIO 2"); var getInput = document.getElementById('pcon').value; localStorage.setItem("storageName2",getInput); } function myFunction4() { var getInput = document.getElementById('pdis').value; localStorage.setItem("storageName2",getInput); } function myFunction5() { alert("Make sure sensor is connected by the following:\n Power: 3.3v \n Data GPIO 18"); var getInput = document.getElementById('wcon').value; localStorage.setItem("storageName3",getInput); } function myFunction6() { var getInput = document.getElementById('wdis').value; localStorage.setItem("storageName3",getInput); } </script> </head> <body> <div id="title"> JD Weather Station Configuration Tool </div> <div id="sensors"> <br><br> Temperature / Humidity <br><br> <button id="tcon" value="temp_connected" onclick="myFunction()">Add Sensor</button> <button id="tdis" value="temp_disconnected" onclick="myFunction2()">Remove Sensor</button> <br><br><br> Pressure <span id="padding"> <br><br> <button id="pcon" value="press_connected" onclick="myFunction3()">Add Sensor</button> <button id="pdis" value="press_disconnected" onclick="myFunction4()">Remove Sensor</button> <br><br><br><br> Wind Speed / Direction <span id="padding"> <br><br> <button id="wcon" value="wind_connected" onclick="myFunction5()">Add Sensor</button> <button id="wdis" value="wind_disconnected" onclick="myFunction6()">Remove Sensor</button> </span> </div> <a href="index.php">Home</a> </body> </html>
gpl-3.0
tumbl3w33d/ansible
lib/ansible/modules/cloud/amazon/route53_health_check.py
13007
#!/usr/bin/python # This file is part of Ansible # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: route53_health_check short_description: Add or delete health-checks in Amazons Route53 DNS service description: - Creates and deletes DNS Health checks in Amazons Route53 service. - Only the port, resource_path, string_match and request_interval are considered when updating existing health-checks. version_added: "2.0" options: state: description: - Specifies the action to take. required: true choices: [ 'present', 'absent' ] type: str default: 'present' ip_address: description: - IP address of the end-point to check. Either this or I(fqdn) has to be provided. type: str port: description: - The port on the endpoint on which you want Amazon Route 53 to perform health checks. Required for TCP checks. type: int type: description: - The type of health check that you want to create, which indicates how Amazon Route 53 determines whether an endpoint is healthy. required: true choices: [ 'HTTP', 'HTTPS', 'HTTP_STR_MATCH', 'HTTPS_STR_MATCH', 'TCP' ] type: str resource_path: description: - The path that you want Amazon Route 53 to request when performing health checks. The path can be any value for which your endpoint will return an HTTP status code of 2xx or 3xx when the endpoint is healthy, for example the file /docs/route53-health-check.html. - Required for all checks except TCP. - The path must begin with a / - Maximum 255 characters. type: str fqdn: description: - Domain name of the endpoint to check. Either this or I(ip_address) has to be provided. When both are given the `fqdn` is used in the `Host:` header of the HTTP request. type: str string_match: description: - If the check type is HTTP_STR_MATCH or HTTP_STR_MATCH, the string that you want Amazon Route 53 to search for in the response body from the specified resource. If the string appears in the first 5120 bytes of the response body, Amazon Route 53 considers the resource healthy. type: str request_interval: description: - The number of seconds between the time that Amazon Route 53 gets a response from your endpoint and the time that it sends the next health-check request. required: true default: 30 choices: [ 10, 30 ] type: int failure_threshold: description: - The number of consecutive health checks that an endpoint must pass or fail for Amazon Route 53 to change the current status of the endpoint from unhealthy to healthy or vice versa. required: true default: 3 choices: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] type: int author: "zimbatm (@zimbatm)" extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Create a health-check for host1.example.com and use it in record - route53_health_check: state: present fqdn: host1.example.com type: HTTP_STR_MATCH resource_path: / string_match: "Hello" request_interval: 10 failure_threshold: 2 register: my_health_check - route53: action: create zone: "example.com" type: CNAME record: "www.example.com" value: host1.example.com ttl: 30 # Routing policy identifier: "host1@www" weight: 100 health_check: "{{ my_health_check.health_check.id }}" # Delete health-check - route53_health_check: state: absent fqdn: host1.example.com ''' import uuid try: import boto import boto.ec2 from boto import route53 from boto.route53 import Route53Connection, exception from boto.route53.healthcheck import HealthCheck HAS_BOTO = True except ImportError: HAS_BOTO = False # import module snippets from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import ec2_argument_spec, get_aws_connection_info # Things that can't get changed: # protocol # ip_address or domain # request_interval # string_match if not previously enabled def find_health_check(conn, wanted): """Searches for health checks that have the exact same set of immutable values""" results = conn.get_list_health_checks() while True: for check in results.HealthChecks: config = check.HealthCheckConfig if ( config.get('IPAddress') == wanted.ip_addr and config.get('FullyQualifiedDomainName') == wanted.fqdn and config.get('Type') == wanted.hc_type and config.get('RequestInterval') == str(wanted.request_interval) and config.get('Port') == str(wanted.port) ): return check if (results.IsTruncated == 'true'): results = conn.get_list_health_checks(marker=results.NextMarker) else: return None def to_health_check(config): return HealthCheck( config.get('IPAddress'), int(config.get('Port')), config.get('Type'), config.get('ResourcePath'), fqdn=config.get('FullyQualifiedDomainName'), string_match=config.get('SearchString'), request_interval=int(config.get('RequestInterval')), failure_threshold=int(config.get('FailureThreshold')), ) def health_check_diff(a, b): a = a.__dict__ b = b.__dict__ if a == b: return {} diff = {} for key in set(a.keys()) | set(b.keys()): if a.get(key) != b.get(key): diff[key] = b.get(key) return diff def to_template_params(health_check): params = { 'ip_addr_part': '', 'port': health_check.port, 'type': health_check.hc_type, 'resource_path_part': '', 'fqdn_part': '', 'string_match_part': '', 'request_interval': health_check.request_interval, 'failure_threshold': health_check.failure_threshold, } if health_check.ip_addr: params['ip_addr_part'] = HealthCheck.XMLIpAddrPart % {'ip_addr': health_check.ip_addr} if health_check.resource_path: params['resource_path_part'] = XMLResourcePathPart % {'resource_path': health_check.resource_path} if health_check.fqdn: params['fqdn_part'] = HealthCheck.XMLFQDNPart % {'fqdn': health_check.fqdn} if health_check.string_match: params['string_match_part'] = HealthCheck.XMLStringMatchPart % {'string_match': health_check.string_match} return params XMLResourcePathPart = """<ResourcePath>%(resource_path)s</ResourcePath>""" POSTXMLBody = """ <CreateHealthCheckRequest xmlns="%(xmlns)s"> <CallerReference>%(caller_ref)s</CallerReference> <HealthCheckConfig> %(ip_addr_part)s <Port>%(port)s</Port> <Type>%(type)s</Type> %(resource_path_part)s %(fqdn_part)s %(string_match_part)s <RequestInterval>%(request_interval)s</RequestInterval> <FailureThreshold>%(failure_threshold)s</FailureThreshold> </HealthCheckConfig> </CreateHealthCheckRequest> """ UPDATEHCXMLBody = """ <UpdateHealthCheckRequest xmlns="%(xmlns)s"> <HealthCheckVersion>%(health_check_version)s</HealthCheckVersion> %(ip_addr_part)s <Port>%(port)s</Port> %(resource_path_part)s %(fqdn_part)s %(string_match_part)s <FailureThreshold>%(failure_threshold)i</FailureThreshold> </UpdateHealthCheckRequest> """ def create_health_check(conn, health_check, caller_ref=None): if caller_ref is None: caller_ref = str(uuid.uuid4()) uri = '/%s/healthcheck' % conn.Version params = to_template_params(health_check) params.update(xmlns=conn.XMLNameSpace, caller_ref=caller_ref) xml_body = POSTXMLBody % params response = conn.make_request('POST', uri, {'Content-Type': 'text/xml'}, xml_body) body = response.read() boto.log.debug(body) if response.status == 201: e = boto.jsonresponse.Element() h = boto.jsonresponse.XmlHandler(e, None) h.parse(body) return e else: raise exception.DNSServerError(response.status, response.reason, body) def update_health_check(conn, health_check_id, health_check_version, health_check): uri = '/%s/healthcheck/%s' % (conn.Version, health_check_id) params = to_template_params(health_check) params.update( xmlns=conn.XMLNameSpace, health_check_version=health_check_version, ) xml_body = UPDATEHCXMLBody % params response = conn.make_request('POST', uri, {'Content-Type': 'text/xml'}, xml_body) body = response.read() boto.log.debug(body) if response.status not in (200, 204): raise exception.DNSServerError(response.status, response.reason, body) e = boto.jsonresponse.Element() h = boto.jsonresponse.XmlHandler(e, None) h.parse(body) return e def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( state=dict(choices=['present', 'absent'], default='present'), ip_address=dict(), port=dict(type='int'), type=dict(required=True, choices=['HTTP', 'HTTPS', 'HTTP_STR_MATCH', 'HTTPS_STR_MATCH', 'TCP']), resource_path=dict(), fqdn=dict(), string_match=dict(), request_interval=dict(type='int', choices=[10, 30], default=30), failure_threshold=dict(type='int', choices=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], default=3), ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto 2.27.0+ required for this module') state_in = module.params.get('state') ip_addr_in = module.params.get('ip_address') port_in = module.params.get('port') type_in = module.params.get('type') resource_path_in = module.params.get('resource_path') fqdn_in = module.params.get('fqdn') string_match_in = module.params.get('string_match') request_interval_in = module.params.get('request_interval') failure_threshold_in = module.params.get('failure_threshold') if ip_addr_in is None and fqdn_in is None: module.fail_json(msg="parameter 'ip_address' or 'fqdn' is required") # Default port if port_in is None: if type_in in ['HTTP', 'HTTP_STR_MATCH']: port_in = 80 elif type_in in ['HTTPS', 'HTTPS_STR_MATCH']: port_in = 443 else: module.fail_json(msg="parameter 'port' is required for 'type' TCP") # string_match in relation with type if type_in in ['HTTP_STR_MATCH', 'HTTPS_STR_MATCH']: if string_match_in is None: module.fail_json(msg="parameter 'string_match' is required for the HTTP(S)_STR_MATCH types") elif len(string_match_in) > 255: module.fail_json(msg="parameter 'string_match' is limited to 255 characters max") elif string_match_in: module.fail_json(msg="parameter 'string_match' argument is only for the HTTP(S)_STR_MATCH types") region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module) # connect to the route53 endpoint try: conn = Route53Connection(**aws_connect_kwargs) except boto.exception.BotoServerError as e: module.fail_json(msg=e.error_message) changed = False action = None check_id = None wanted_config = HealthCheck(ip_addr_in, port_in, type_in, resource_path_in, fqdn_in, string_match_in, request_interval_in, failure_threshold_in) existing_check = find_health_check(conn, wanted_config) if existing_check: check_id = existing_check.Id existing_config = to_health_check(existing_check.HealthCheckConfig) if state_in == 'present': if existing_check is None: action = "create" check_id = create_health_check(conn, wanted_config).HealthCheck.Id changed = True else: diff = health_check_diff(existing_config, wanted_config) if diff: action = "update" update_health_check(conn, existing_check.Id, int(existing_check.HealthCheckVersion), wanted_config) changed = True elif state_in == 'absent': if check_id: action = "delete" conn.delete_health_check(check_id) changed = True else: module.fail_json(msg="Logic Error: Unknown state") module.exit_json(changed=changed, health_check=dict(id=check_id), action=action) if __name__ == '__main__': main()
gpl-3.0
atgeirr/opm-common
src/opm/output/eclipse/AggregateAquiferData.cpp
27487
/* Copyright (c) 2021 Equinor ASA This file is part of the Open Porous Media project (OPM). OPM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OPM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OPM. If not, see <http://www.gnu.org/licenses/>. */ #include <opm/output/eclipse/AggregateAquiferData.hpp> #include <opm/output/eclipse/InteHEAD.hpp> #include <opm/output/eclipse/WindowedArray.hpp> #include <opm/output/eclipse/ActiveIndexByColumns.hpp> #include <opm/output/eclipse/VectorItems/aquifer.hpp> #include <opm/parser/eclipse/EclipseState/EclipseState.hpp> #include <opm/parser/eclipse/EclipseState/Aquifer/Aquancon.hpp> #include <opm/parser/eclipse/EclipseState/Aquifer/AquiferConfig.hpp> #include <opm/parser/eclipse/EclipseState/Aquifer/AquiferCT.hpp> #include <opm/parser/eclipse/EclipseState/Aquifer/Aquifetp.hpp> #include <opm/parser/eclipse/EclipseState/Grid/EclipseGrid.hpp> #include <opm/parser/eclipse/EclipseState/Schedule/SummaryState.hpp> #include <opm/parser/eclipse/EclipseState/Tables/FlatTable.hpp> #include <opm/parser/eclipse/Units/UnitSystem.hpp> #include <opm/common/OpmLog/OpmLog.hpp> #include <fmt/format.h> #include <array> #include <cstddef> #include <numeric> #include <stdexcept> #include <string> #include <vector> namespace VI = Opm::RestartIO::Helpers::VectorItems; namespace { double getSummaryVariable(const Opm::SummaryState& summaryState, const std::string& variable, const int aquiferID) { const auto key = fmt::format("{}:{}", variable, aquiferID); return summaryState.get(key, 0.0); } template <typename AquiferCallBack> void CarterTracyAquiferLoop(const Opm::AquiferConfig& aqConfig, AquiferCallBack&& aquiferOp) { for (const auto& aqData : aqConfig.ct()) { aquiferOp(aqData); } } template <typename AquiferCallBack> void FetkovichAquiferLoop(const Opm::AquiferConfig& aqConfig, AquiferCallBack&& aquiferOp) { for (const auto& aqData : aqConfig.fetp()) { aquiferOp(aqData); } } template <typename AquiferCallBack> void numericAquiferLoop(const Opm::AquiferConfig& aqConfig, AquiferCallBack&& aquiferOp) { if (! aqConfig.hasNumericalAquifer()) { return; } for (const auto& [aquiferID, aquifer] : aqConfig.numericalAquifers().aquifers()) { const auto numCells = aquifer.numCells(); for (auto cellIndex = 0*numCells; cellIndex < numCells; ++cellIndex) { const auto* aqCell = aquifer.getCellPrt(cellIndex); aquiferOp(static_cast<int>(aquiferID), cellIndex, *aqCell); } } } template <typename ConnectionCallBack> void analyticAquiferConnectionLoop(const Opm::AquiferConfig& aqConfig, ConnectionCallBack&& connectionOp) { for (const auto& [aquiferID, connections] : aqConfig.connections().data()) { const auto tot_influx = std::accumulate(connections.begin(), connections.end(), 0.0, [](const double t, const Opm::Aquancon::AquancCell& connection) -> double { return t + connection.influx_coeff; }); auto connectionID = std::size_t{0}; for (const auto& connection : connections) { connectionOp(aquiferID, connectionID++, tot_influx, connection); } } } namespace IntegerAnalyticAquifer { Opm::RestartIO::Helpers::WindowedArray<int> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<int>; return WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.maxAquiferID) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numIntAquiferElem) } }; } namespace CarterTracy { template <typename IAaqArray> void staticContrib(const Opm::AquiferCT::AQUCT_data& aquifer, const int numActiveConn, IAaqArray& iaaq) { using Ix = VI::IAnalyticAquifer::index; iaaq[Ix::NumAquiferConn] = numActiveConn; iaaq[Ix::WatPropTable] = aquifer.pvttableID; // One-based (=AQUCT(10)) iaaq[Ix::CTInfluenceFunction] = aquifer.inftableID; iaaq[Ix::TypeRelated1] = VI::IAnalyticAquifer::Value::ModelType::CarterTracy; iaaq[Ix::Unknown_1] = 1; // Not characterised; =1 in all cases seen thus far. } } // CarterTracy namespace Fetkovich { template <typename IAaqArray> void staticContrib(const Opm::Aquifetp::AQUFETP_data& aquifer, const int numActiveConn, IAaqArray& iaaq) { using Ix = VI::IAnalyticAquifer::index; iaaq[Ix::NumAquiferConn] = numActiveConn; iaaq[Ix::WatPropTable] = aquifer.pvttableID; // One-based (=AQUFETP(7)) iaaq[Ix::TypeRelated1] = VI::IAnalyticAquifer::Value::ModelType::Fetkovich; iaaq[Ix::Unknown_1] = 1; // Not characterised; =1 in all cases seen thus far. } } // Fetkovich } // IntegerAnalyticAquifer namespace IntegerNumericAquifer { Opm::RestartIO::Helpers::WindowedArray<int> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<int>; return WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.numNumericAquiferRecords) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numNumericAquiferIntElem) } }; } template <typename IAqnArray> void staticContrib(const Opm::NumericalAquiferCell& aqCell, const int aquiferID, IAqnArray& iaqn) { using Ix = VI::INumericAquifer::index; iaqn[Ix::AquiferID] = aquiferID; iaqn[Ix::Cell_I] = static_cast<int>(aqCell.I) + 1; iaqn[Ix::Cell_J] = static_cast<int>(aqCell.J) + 1; iaqn[Ix::Cell_K] = static_cast<int>(aqCell.K) + 1; iaqn[Ix::PVTTableID] = aqCell.pvttable; iaqn[Ix::SatFuncID] = aqCell.sattable; } } // IntegerNumericAquifer namespace IntegerAnalyticAquiferConn { std::vector<Opm::RestartIO::Helpers::WindowedArray<int>> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<int>; return std::vector<WA>(aqDims.maxAquiferID, WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.maxNumActiveAquiferConn) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numIntConnElem) } }); } int eclipseFaceDirection(const Opm::FaceDir::DirEnum faceDir) { using FDValue = VI::IAnalyticAquiferConn::Value::FaceDirection; switch (faceDir) { case Opm::FaceDir::DirEnum::XMinus: return FDValue::IMinus; case Opm::FaceDir::DirEnum::XPlus: return FDValue::IPlus; case Opm::FaceDir::DirEnum::YMinus: return FDValue::JMinus; case Opm::FaceDir::DirEnum::YPlus: return FDValue::JPlus; case Opm::FaceDir::DirEnum::ZMinus: return FDValue::KMinus; case Opm::FaceDir::DirEnum::ZPlus: return FDValue::KPlus; } throw std::invalid_argument { fmt::format("Unknown Face Direction {}", static_cast<int>(faceDir)) }; } template <typename ICAqArray> void staticContrib(const Opm::Aquancon::AquancCell& connection, const Opm::EclipseGrid& grid, const Opm::ActiveIndexByColumns& map, ICAqArray& icaq) { using Ix = VI::IAnalyticAquiferConn::index; const auto ijk = grid.getIJK(connection.global_index); icaq[Ix::Index_I] = ijk[0] + 1; icaq[Ix::Index_J] = ijk[1] + 1; icaq[Ix::Index_K] = ijk[2] + 1; icaq[Ix::ActiveIndex] = map.getColumnarActiveIndex(grid.activeIndex(connection.global_index)) + 1; icaq[Ix::FaceDirection] = eclipseFaceDirection(connection.face_dir); } } // IntegerAnalyticAquiferConn namespace SinglePrecAnalyticAquifer { Opm::RestartIO::Helpers::WindowedArray<float> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<float>; return WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.maxAquiferID) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numRealAquiferElem) } }; } namespace CarterTracy { template <typename SAaqArray> void staticContrib(const Opm::AquiferCT::AQUCT_data& aquifer, const Opm::data::AquiferData& aquData, const Opm::UnitSystem& usys, SAaqArray& saaq) { using M = Opm::UnitSystem::measure; using Ix = VI::SAnalyticAquifer::index; auto cvrt = [&usys](const M unit, const double x) -> float { return static_cast<float>(usys.from_si(unit, x)); }; // Unit hack: *to_si()* here since we don't have a compressibility unit. saaq[Ix::Compressibility] = static_cast<float>(usys.to_si(M::pressure, aquifer.total_compr)); saaq[Ix::CTRadius] = cvrt(M::length, aquifer.inner_radius); saaq[Ix::CTPermeability] = cvrt(M::permeability, aquifer.permeability); saaq[Ix::CTPorosity] = cvrt(M::identity, aquifer.porosity); saaq[Ix::InitPressure] = cvrt(M::pressure, aquData.initPressure); saaq[Ix::DatumDepth] = cvrt(M::length, aquifer.datum_depth); saaq[Ix::CTThickness] = cvrt(M::length, aquifer.thickness); saaq[Ix::CTAngle] = cvrt(M::identity, aquifer.angle_fraction); if (const auto* aquCT = aquData.typeData.get<Opm::data::AquiferType::CarterTracy>(); aquCT != nullptr) { saaq[Ix::CTWatMassDensity] = cvrt(M::density, aquCT->waterDensity); saaq[Ix::CTWatViscosity] = cvrt(M::viscosity, aquCT->waterViscosity); } } } // CarterTracy namespace Fetkovich { template <typename SAaqArray> void staticContrib(const Opm::Aquifetp::AQUFETP_data& aquifer, const Opm::data::AquiferData& aquData, const Opm::UnitSystem& usys, SAaqArray& saaq) { using M = Opm::UnitSystem::measure; using Ix = VI::SAnalyticAquifer::index; auto cvrt = [&usys](const M unit, const double x) -> float { return static_cast<float>(usys.from_si(unit, x)); }; // Unit hack: *to_si()* here since we don't have a compressibility unit. saaq[Ix::Compressibility] = static_cast<float>(usys.to_si(M::pressure, aquifer.total_compr)); saaq[Ix::FetInitVol] = cvrt(M::liquid_surface_volume, aquifer.initial_watvolume); saaq[Ix::FetProdIndex] = cvrt(M::liquid_productivity_index, aquifer.prod_index); saaq[Ix::InitPressure] = cvrt(M::pressure, aquData.initPressure); saaq[Ix::DatumDepth] = cvrt(M::length, aquifer.datum_depth); if (const auto* aquFet = aquData.typeData.get<Opm::data::AquiferType::Fetkovich>(); aquFet != nullptr) { saaq[Ix::FetTimeConstant] = cvrt(M::time, aquFet->timeConstant); } else { saaq[Ix::FetTimeConstant] = cvrt(M::time, aquifer.timeConstant()); } } } // Fetkovich } // SinglePrecAnalyticAquifer namespace SinglePrecAnalyticAquiferConn { std::vector<Opm::RestartIO::Helpers::WindowedArray<float>> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<float>; return std::vector<WA>(aqDims.maxAquiferID, WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.maxNumActiveAquiferConn) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numRealConnElem) } }); } template <typename SCAqArray> void staticContrib(const Opm::Aquancon::AquancCell& connection, const double tot_influx, SCAqArray& scaq) { using Ix = VI::SAnalyticAquiferConn::index; auto make_ratio = [tot_influx](const double x) -> float { return static_cast<float>(x / tot_influx); }; scaq[Ix::InfluxFraction] = make_ratio(connection.influx_coeff); scaq[Ix::FaceAreaToInfluxCoeff] = make_ratio(connection.effective_facearea); } } // SingleAnalyticAquiferConn namespace DoublePrecAnalyticAquifer { double totalInfluxCoefficient(const Opm::UnitSystem& usys, const double tot_influx) { using M = Opm::UnitSystem::measure; return usys.from_si(M::length, usys.from_si(M::length, tot_influx)); } Opm::RestartIO::Helpers::WindowedArray<double> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<double>; return WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.maxAquiferID) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numDoubAquiferElem) } }; } namespace Common { template <typename SummaryVariable, typename XAaqArray> void dynamicContrib(SummaryVariable&& summaryVariable, const double tot_influx, const Opm::UnitSystem& usys, XAaqArray& xaaq) { using Ix = VI::XAnalyticAquifer::index; xaaq[Ix::FlowRate] = summaryVariable("AAQR"); xaaq[Ix::Pressure] = summaryVariable("AAQP"); xaaq[Ix::ProdVolume] = summaryVariable("AAQT"); xaaq[Ix::TotalInfluxCoeff] = totalInfluxCoefficient(usys, tot_influx); } } // Common namespace CarterTracy { template <typename SummaryVariable, typename XAaqArray> void dynamicContrib(SummaryVariable&& summaryVariable, const Opm::data::AquiferData& aquData, const double tot_influx, const Opm::UnitSystem& usys, XAaqArray& xaaq) { using M = Opm::UnitSystem::measure; using Ix = VI::XAnalyticAquifer::index; Common::dynamicContrib(std::forward<SummaryVariable>(summaryVariable), tot_influx, usys, xaaq); const auto* aquCT = aquData.typeData.get<Opm::data::AquiferType::CarterTracy>(); const auto Tc = aquCT->timeConstant; const auto beta = aquCT->influxConstant; // Note: *to_si()* here since this is a *reciprocal* time constant xaaq[Ix::CTRecipTimeConst] = usys.to_si(M::time, 1.0 / Tc); // Note: *to_si()* for the pressure unit here since 'beta' // is total influx (volume) per unit pressure drop. xaaq[Ix::CTInfluxConstant] = usys.from_si(M::volume, usys.to_si(M::pressure, beta)); xaaq[Ix::CTDimensionLessTime] = summaryVariable("AAQTD"); xaaq[Ix::CTDimensionLessPressure] = summaryVariable("AAQPD"); } } // CarterTracy namespace Fetkovich { template <typename SummaryVariable, typename XAaqArray> void dynamicContrib(SummaryVariable&& summaryVariable, const double tot_influx, const Opm::UnitSystem& usys, XAaqArray& xaaq) { Common::dynamicContrib(std::forward<SummaryVariable>(summaryVariable), tot_influx, usys, xaaq); } } // Fetkovich } // DoublePrecAnalyticAquifer namespace DoublePrecNumericAquifer { Opm::RestartIO::Helpers::WindowedArray<double> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<double>; return WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.numNumericAquiferRecords) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numNumericAquiferDoubleElem) } }; } template <typename SummaryVariable, typename RAqnArray> void dynamicContrib(const Opm::NumericalAquiferCell& aqCell, const Opm::data::AquiferData* aqData, const std::size_t cellIndex, SummaryVariable&& summaryVariable, const Opm::UnitSystem& usys, RAqnArray& raqn) { using M = Opm::UnitSystem::measure; using Ix = VI::RNumericAquifer::index; raqn[Ix::Area] = usys.from_si(M::length, usys.from_si(M::length, aqCell.area)); raqn[Ix::Length] = usys.from_si(M::length, aqCell.length); raqn[Ix::Porosity] = aqCell.porosity; raqn[Ix::Permeability] = usys.from_si(M::permeability, aqCell.permeability); raqn[Ix::Depth] = usys.from_si(M::length, aqCell.depth); const auto* aquNum = (aqData != nullptr) ? aqData->typeData.get<Opm::data::AquiferType::Numerical>() : nullptr; if (aquNum != nullptr) { raqn[Ix::Pressure] = usys.from_si(M::pressure, aquNum->initPressure[cellIndex]); } else if (aqCell.init_pressure.has_value()) { raqn[Ix::Pressure] = usys.from_si(M::pressure, aqCell.init_pressure.value()); } raqn[Ix::Unknown_1] = 1.0; // Unknown item. 1.0 in all cases so far. raqn[Ix::Unknown_2] = 1.0; // Unknown item. 1.0 in all cases so far. raqn[Ix::Unknown_3] = 1.0; // Unknown item. 1.0 in all cases so far. raqn[Ix::PoreVolume] = usys.from_si(M::volume, aqCell.poreVolume()); raqn[Ix::FlowRate] = summaryVariable("ANQR"); raqn[Ix::ProdVolume] = summaryVariable("ANQT"); raqn[Ix::DynPressure] = summaryVariable("ANQP"); } } // IntegerNumericAquifer namespace DoublePrecAnalyticAquiferConn { std::vector<Opm::RestartIO::Helpers::WindowedArray<double>> allocate(const Opm::RestartIO::InteHEAD::AquiferDims& aqDims) { using WA = Opm::RestartIO::Helpers::WindowedArray<double>; return std::vector<WA>(aqDims.maxAquiferID, WA { WA::NumWindows{ static_cast<WA::Idx>(aqDims.maxNumActiveAquiferConn) }, WA::WindowSize{ static_cast<WA::Idx>(aqDims.numDoubConnElem) } }); } } // SingleAnalyticAquiferConn } // Anonymous Opm::RestartIO::Helpers::AggregateAquiferData:: AggregateAquiferData(const InteHEAD::AquiferDims& aqDims, const AquiferConfig& aqConfig, const EclipseGrid& grid) : maxActiveAnalyticAquiferID_ { aqDims.maxAquiferID } , numActiveConn_ ( aqDims.maxAquiferID, 0 ) , totalInflux_ ( aqDims.maxAquiferID, 0.0 ) , integerAnalyticAq_ { IntegerAnalyticAquifer:: allocate(aqDims) } , singleprecAnalyticAq_ { SinglePrecAnalyticAquifer:: allocate(aqDims) } , doubleprecAnalyticAq_ { DoublePrecAnalyticAquifer:: allocate(aqDims) } , integerNumericAq_ { IntegerNumericAquifer:: allocate(aqDims) } , doubleprecNumericAq_ { DoublePrecNumericAquifer:: allocate(aqDims) } , integerAnalyticAquiferConn_ { IntegerAnalyticAquiferConn:: allocate(aqDims) } , singleprecAnalyticAquiferConn_{ SinglePrecAnalyticAquiferConn::allocate(aqDims) } , doubleprecAnalyticAquiferConn_{ DoublePrecAnalyticAquiferConn::allocate(aqDims) } { if (! aqConfig.hasAnalyticalAquifer()) { return; } const auto map = buildColumnarActiveIndexMappingTables(grid); // Aquifer connections do not change in SCHEDULE. Leverage that // property to compute static connection information exactly once. analyticAquiferConnectionLoop(aqConfig, [this, &grid, &map] (const std::size_t aquiferID, const std::size_t connectionID, const double tot_influx, const Aquancon::AquancCell& connection) -> void { const auto aquIndex = static_cast<WindowedArray<int>::Idx>(aquiferID - 1); // Note: ACAQ intentionally omitted here. This array is not fully characterised. auto icaq = this->integerAnalyticAquiferConn_ [aquIndex][connectionID]; auto scaq = this->singleprecAnalyticAquiferConn_[aquIndex][connectionID]; this->numActiveConn_[aquIndex] += 1; this->totalInflux_ [aquIndex] = tot_influx; IntegerAnalyticAquiferConn::staticContrib(connection, grid, map, icaq); SinglePrecAnalyticAquiferConn::staticContrib(connection, tot_influx, scaq); }); } void Opm::RestartIO::Helpers::AggregateAquiferData:: captureDynamicdAquiferData(const AquiferConfig& aqConfig, const data::Aquifers& aquData, const SummaryState& summaryState, const UnitSystem& usys) { FetkovichAquiferLoop(aqConfig, [this, &summaryState, &aquData, &usys] (const Aquifetp::AQUFETP_data& aquifer) { const auto aquIndex = static_cast<WindowedArray<int>::Idx>(aquifer.aquiferID - 1); auto iaaq = this->integerAnalyticAq_[aquIndex]; const auto nActiveConn = this->numActiveConn_[aquIndex]; IntegerAnalyticAquifer::Fetkovich::staticContrib(aquifer, nActiveConn, iaaq); auto xaqPos = aquData.find(aquifer.aquiferID); if ((xaqPos != aquData.end()) && xaqPos->second.typeData.is<data::AquiferType::Fetkovich>()) { const auto& aquFetPData = xaqPos->second; auto saaq = this->singleprecAnalyticAq_[aquIndex]; SinglePrecAnalyticAquifer::Fetkovich::staticContrib(aquifer, aquFetPData, usys, saaq); } auto xaaq = this->doubleprecAnalyticAq_[aquIndex]; const auto tot_influx = this->totalInflux_[aquIndex]; auto sumVar = [&summaryState, &aquifer](const std::string& vector) { return getSummaryVariable(summaryState, vector, aquifer.aquiferID); }; DoublePrecAnalyticAquifer::Fetkovich::dynamicContrib(sumVar, tot_influx, usys, xaaq); }); CarterTracyAquiferLoop(aqConfig, [this, &summaryState, &aquData, &usys] (const AquiferCT::AQUCT_data& aquifer) { const auto aquIndex = static_cast<WindowedArray<int>::Idx>(aquifer.aquiferID - 1); auto iaaq = this->integerAnalyticAq_[aquIndex]; const auto nActiveConn = this->numActiveConn_[aquIndex]; IntegerAnalyticAquifer::CarterTracy::staticContrib(aquifer, nActiveConn, iaaq); auto xaqPos = aquData.find(aquifer.aquiferID); if ((xaqPos != aquData.end()) && xaqPos->second.typeData.is<data::AquiferType::CarterTracy>()) { const auto& aquCTData = xaqPos->second; auto saaq = this->singleprecAnalyticAq_[aquIndex]; SinglePrecAnalyticAquifer::CarterTracy:: staticContrib(aquifer, aquCTData, usys, saaq); auto xaaq = this->doubleprecAnalyticAq_[aquIndex]; const auto tot_influx = this->totalInflux_[aquIndex]; auto sumVar = [&summaryState, &aquifer](const std::string& vector) { return getSummaryVariable(summaryState, vector, aquifer.aquiferID); }; DoublePrecAnalyticAquifer::CarterTracy::dynamicContrib(sumVar, aquCTData, tot_influx, usys, xaaq); } }); numericAquiferLoop(aqConfig, [this, &summaryState, &aquData, &usys] (const int aquiferID, const std::size_t cellIndex, const NumericalAquiferCell& aqCell) { auto iaqn = this->integerNumericAq_[aqCell.record_id]; IntegerNumericAquifer::staticContrib(aqCell, aquiferID, iaqn); const auto isNewID = cellIndex == std::size_t{0}; auto aquNum = aquData.find(aquiferID); const auto* aquiferData = (aquNum != aquData.end()) ? &aquNum->second : nullptr; auto raqn = this->doubleprecNumericAq_[aqCell.record_id]; auto sumVar = [&summaryState, aquiferID, isNewID](const std::string& vector) { return !isNewID ? 0.0 : getSummaryVariable(summaryState, vector, aquiferID); }; DoublePrecNumericAquifer::dynamicContrib(aqCell, aquiferData, cellIndex, sumVar, usys, raqn); }); }
gpl-3.0
cchampet/TuttleOFX
libraries/tuttle/src/tuttle/common/ofx/core.cpp
2992
#include "core.hpp" #include <ofxImageEffect.h> #include <boost/lexical_cast.hpp> namespace tuttle { namespace ofx { std::string mapStatusToString( const OfxStatus stat ) { switch( stat ) { case kOfxStatOK: return "kOfxStatOK"; case kOfxStatFailed: return "kOfxStatFailed"; case kOfxStatErrFatal: return "kOfxStatErrFatal"; case kOfxStatErrUnknown: return "kOfxStatErrUnknown"; case kOfxStatErrMissingHostFeature: return "kOfxStatErrMissingHostFeature"; case kOfxStatErrUnsupported: return "kOfxStatErrUnsupported"; case kOfxStatErrExists: return "kOfxStatErrExists"; case kOfxStatErrFormat: return "kOfxStatErrFormat"; case kOfxStatErrMemory: return "kOfxStatErrMemory"; case kOfxStatErrBadHandle: return "kOfxStatErrBadHandle"; case kOfxStatErrBadIndex: return "kOfxStatErrBadIndex"; case kOfxStatErrValue: return "kOfxStatErrValue"; case kOfxStatReplyYes: return "kOfxStatReplyYes"; case kOfxStatReplyNo: return "kOfxStatReplyNo"; case kOfxStatReplyDefault: return "kOfxStatReplyDefault"; case kOfxStatErrImageFormat: return "kOfxStatErrImageFormat"; } return "UNKNOWN STATUS CODE: " + boost::lexical_cast<std::string>( stat ); } } } std::ostream& operator<<( std::ostream& os, const OfxPlugin& v ) { os << "OfxPlugin {" << std::endl; os << " pluginApi" << v.pluginApi << std::endl; os << " apiVersion" << v.apiVersion << std::endl; os << " pluginIdentifier" << v.pluginIdentifier << std::endl; os << " pluginVersionMajor" << v.pluginVersionMajor << std::endl; os << " pluginVersionMinor" << v.pluginVersionMinor << std::endl; os << "}" << std::endl; return os; } /* typedef struct OfxRangeI { int min, max; } OfxRangeI; typedef struct OfxRangeD { double min, max; } OfxRangeD; typedef struct OfxPointI { int x, y; } OfxPointI; typedef struct OfxPointD { double x, y; } OfxPointD; typedef struct OfxRectI { int x1, y1, x2, y2; } OfxRectI; typedef struct OfxRectD { double x1, y1, x2, y2; } OfxRectD; typedef struct OfxRGBAColourB { unsigned char r, g, b, a; }OfxRGBAColourB; typedef struct OfxRGBAColourS { unsigned short r, g, b, a; }OfxRGBAColourS; typedef struct OfxRGBAColourF { float r, g, b, a; }OfxRGBAColourF; typedef struct OfxRGBAColourD { double r, g, b, a; }OfxRGBAColourD; struct OfxRGBColourB { unsigned char r, g, b; }; struct OfxRGBColourS { unsigned short r, g, b; }; struct OfxRGBColourF { float r, g, b; }; struct OfxRGBColourD { double r, g, b; }; struct Ofx3DPointI { int x, y, z; }; struct Ofx3DPointD { double x, y, z; }; typedef struct OfxYUVAColourB { unsigned char y, u, v, a; }OfxYUVAColourB; typedef struct OfxYUVAColourS { unsigned short y, u, v, a; }OfxYUVAColourS; typedef struct OfxYUVAColourF { float y, u, v, a; }OfxYUVAColourF; */
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Lower_Jeuno/npcs/Guttrix.lua
4107
----------------------------------- -- Area: Lower Jeuno -- NPC: Guttrix -- Starts and Finishes Quest: The Goblin Tailor -- @zone 245 -- !pos -36.010 4.499 -139.714 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); --[[----------------------------------------------- Description: rse = race, { [1] body, [2] hands, [3] legs, [4] feet } --]]----------------------------------------------- local rse_map = { 1,{12654,12761,12871,13015}, -- Male Hume 2,{12655,12762,12872,13016}, -- Female Hume 3,{12656,12763,12873,13017}, -- Male Elvaan 4,{12657,12764,12874,13018}, -- Female Elvaan 5,{12658,12765,12875,13019}, -- Male Taru-Taru 6,{12658,12765,12875,13019}, -- Female Taru-Taru 7,{12659,12766,12876,13020}, -- Mithra 8,{12660,12767,12877,13021}};-- Galka function hasRSE(player) local rse = 0; local race = player:getRace(); for raceindex = 1, #rse_map, 2 do if (race == rse_map[raceindex]) then --matched race for rseindex = 1, #rse_map[raceindex + 1], 1 do --loop rse for this race if (player:hasItem(rse_map[raceindex+1][rseindex])) then rse = rse + (2 ^ (rseindex - 1)); end end end end return rse; end; function getRSE(player, option) local race = player:getRace(); for raceindex = 1, #rse_map, 2 do if (race == rse_map[raceindex]) then --matched race return rse_map[raceindex+1][option]; end end return -1; end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local pFame = player:getFameLevel(JEUNO); local pRace = player:getRace(); local pLevel = player:getMainLvl(); local questStatus = player:getQuestStatus(JEUNO,THE_GOBLIN_TAILOR); local rseGear = hasRSE(player); local rseRace = VanadielRSERace(); local rseLocation = VanadielRSELocation(); if (pLevel >= 10 and pFame >= 3) then if (rseGear < 15 ) then if (questStatus == QUEST_AVAILABLE) then player:startEvent(0x2720,rseLocation,rseRace); elseif (questStatus >= QUEST_ACCEPTED and player:hasKeyItem(MAGICAL_PATTERN) and rseRace == pRace) then player:startEvent(0x2722,rseGear); else player:startEvent(0x2721,rseLocation,rseRace); end else player:startEvent(0x2723); end else player:startEvent(0x2724); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local questStatus = player:getQuestStatus(JEUNO,THE_GOBLIN_TAILOR); if (csid == 0x2720) then player:addQuest(JEUNO,THE_GOBLIN_TAILOR); elseif (csid == 0x2722 and option >= 1 and option <= 4) then local rseGear = getRSE(player,option); if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,rseGear); else if (questStatus == QUEST_ACCEPTED) then player:addFame(JEUNO, 30); player:completeQuest(JEUNO,THE_GOBLIN_TAILOR); end player:delKeyItem(MAGICAL_PATTERN); player:addItem(rseGear); player:messageSpecial(ITEM_OBTAINED,rseGear); end end end;
gpl-3.0
muxiaobai/SSH
SSH/src/main/java/Util/SendEmailUtil.java
2453
package Util; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import Model.Email; public class SendEmailUtil { public static final String EMAIL_FROM = "zpf12345678910@qq.com"; public static final String EMAIL_FROMHOST = "smtp.qq.com"; public static final String EMAIL_FROMPORT = "465"; public static final String EMAIL_FROMPASSWORD = "wiqrwybnkgjibaha"; public static final String EMAIL_SUBJECT = "wiqrwybnkgjibaha"; public static void sendEmail(Email email) { Properties prop = new Properties(); prop.setProperty("mail.smtp.host", (email.getFromHost()==null||"".equals(email.getFromHost())) ? EMAIL_FROMHOST : email.getFromHost()); prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.setProperty("mail.smtp.socketFactory.fallback", "false"); prop.setProperty("mail.smtp.port", (email.getFromPort()==null||"".equals(email.getFromPort())) ? EMAIL_FROMPORT : email.getFromPort()); prop.setProperty("mail.smtp.socketFactory.port", (email.getFromPort()==null||"".equals(email.getFromPort())) ? EMAIL_FROMPORT : email.getFromPort()); prop.setProperty("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(prop, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication((email.getFrom()==null||"".equals(email.getFrom())) ? EMAIL_FROM : email.getFrom(), (email.getFromPassword()==null||"".equals(email.getFromPassword())) ? EMAIL_FROMPASSWORD : email.getFromPassword()); } }); Message message = new MimeMessage(session); try { message.setRecipient(Message.RecipientType.TO, new InternetAddress(email.getTo())); message.setFrom(new InternetAddress((email.getFrom()==null||"".equals(email.getFrom())) ? EMAIL_FROM : email.getFrom())); message.setText(email.getContent()); message.setSubject((email.getSubject()==null||"".equals(email.getSubject()))?EMAIL_SUBJECT:email.getSubject()); message.setSentDate((email.getSendDate()==null||"".equals(email.getSendDate()))?new Date():email.getSendDate()); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } } }
gpl-3.0
HeavensSword/darkstar
scripts/globals/items/tavnazian_taco.lua
1521
----------------------------------------- -- ID: 5174 -- Item: tavnazian_taco -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Magic 20 -- Dexterity 4 -- Agility 4 -- Vitality 6 -- Charisma 4 -- Defense % 25 -- HP Recovered While Healing 1 -- MP Recovered While Healing 1 -- Defense Cap 150 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5174); end; function onEffectGain(target, effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_DEX, 4); target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, 6); target:addMod(MOD_CHR, 4); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 150); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_DEX, 4); target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, 6); target:delMod(MOD_CHR, 4); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 150); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
leejir/darkforce
third_party/boost/boost/mpl/aux_/numeric_op.hpp
5827
#if !defined(BOOST_PP_IS_ITERATING) ///// header body // NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION! // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: numeric_op.hpp 86249 2013-10-11 23:22:36Z skelly $ // $Date: 2013-10-12 07:22:36 +0800 (周六, 12 十月 2013) $ // $Revision: 86249 $ #if !defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/numeric_cast.hpp> # include <boost/mpl/apply_wrap.hpp> # include <boost/mpl/if.hpp> # include <boost/mpl/tag.hpp> # include <boost/mpl/aux_/numeric_cast_utils.hpp> # include <boost/mpl/aux_/na.hpp> # include <boost/mpl/aux_/na_spec.hpp> # include <boost/mpl/aux_/lambda_support.hpp> # include <boost/mpl/aux_/value_wknd.hpp> #endif #include <boost/mpl/aux_/config/static_constant.hpp> #if defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ || defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/limits/arity.hpp> # include <boost/mpl/aux_/preprocessor/partial_spec_params.hpp> # include <boost/mpl/aux_/preprocessor/def_params_tail.hpp> # include <boost/mpl/aux_/preprocessor/repeat.hpp> # include <boost/mpl/aux_/preprocessor/ext_params.hpp> # include <boost/mpl/aux_/preprocessor/params.hpp> # include <boost/mpl/aux_/preprocessor/enum.hpp> # include <boost/mpl/aux_/preprocessor/add.hpp> # include <boost/mpl/aux_/preprocessor/sub.hpp> # include <boost/mpl/aux_/config/ctps.hpp> # include <boost/mpl/aux_/config/msvc.hpp> # include <boost/mpl/aux_/config/workaround.hpp> # include <boost/preprocessor/dec.hpp> # include <boost/preprocessor/inc.hpp> # include <boost/preprocessor/iterate.hpp> # include <boost/preprocessor/cat.hpp> #if !defined(AUX778076_OP_ARITY) # define AUX778076_OP_ARITY BOOST_MPL_LIMIT_METAFUNCTION_ARITY #endif #if !defined(AUX778076_OP_IMPL_NAME) # define AUX778076_OP_IMPL_NAME BOOST_PP_CAT(AUX778076_OP_PREFIX,_impl) #endif #if !defined(AUX778076_OP_TAG_NAME) # define AUX778076_OP_TAG_NAME BOOST_PP_CAT(AUX778076_OP_PREFIX,_tag) #endif namespace boost { namespace mpl { template< typename Tag1 , typename Tag2 > struct AUX778076_OP_IMPL_NAME : if_c< ( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1) > BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2) ) , aux::cast2nd_impl< AUX778076_OP_IMPL_NAME<Tag1,Tag1>,Tag1,Tag2 > , aux::cast1st_impl< AUX778076_OP_IMPL_NAME<Tag2,Tag2>,Tag1,Tag2 > >::type { }; /// for Digital Mars C++/compilers with no CTPS/TTP support template<> struct AUX778076_OP_IMPL_NAME<na,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename Tag > struct AUX778076_OP_IMPL_NAME<na,Tag> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename Tag > struct AUX778076_OP_IMPL_NAME<Tag,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename T > struct AUX778076_OP_TAG_NAME { typedef typename T::tag type; }; #if AUX778076_OP_ARITY != 2 # define AUX778076_OP_RIGHT_OPERAND(unused, i, N) , BOOST_PP_CAT(N, BOOST_MPL_PP_ADD(i, 2))> # define AUX778076_OP_N_CALLS(i, N) \ BOOST_MPL_PP_REPEAT( BOOST_PP_DEC(i), BOOST_MPL_PP_REPEAT_IDENTITY_FUNC, AUX778076_OP_NAME< ) \ N1 BOOST_MPL_PP_REPEAT( BOOST_MPL_PP_SUB(i, 1), AUX778076_OP_RIGHT_OPERAND, N ) \ /**/ template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) BOOST_MPL_PP_DEF_PARAMS_TAIL(2, typename N, na) > struct AUX778076_OP_NAME : AUX778076_OP_N_CALLS(AUX778076_OP_ARITY, N) { BOOST_MPL_AUX_LAMBDA_SUPPORT( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARAMS(AUX778076_OP_ARITY, N) ) ) }; #define BOOST_PP_ITERATION_PARAMS_1 \ (3,( BOOST_PP_DEC(AUX778076_OP_ARITY), 2, <boost/mpl/aux_/numeric_op.hpp> )) #include BOOST_PP_ITERATE() # undef AUX778076_OP_N_CALLS # undef AUX778076_OP_RIGHT_OPERAND #else // AUX778076_OP_ARITY == 2 template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) > struct AUX778076_OP_NAME #endif : AUX778076_OP_IMPL_NAME< typename AUX778076_OP_TAG_NAME<N1>::type , typename AUX778076_OP_TAG_NAME<N2>::type >::template apply<N1,N2>::type { #if AUX778076_OP_ARITY != 2 BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(2, N, na) ) ) #else BOOST_MPL_AUX_LAMBDA_SUPPORT(2, AUX778076_OP_NAME, (N1, N2)) #endif }; BOOST_MPL_AUX_NA_SPEC2(2, AUX778076_OP_ARITY, AUX778076_OP_NAME) }} #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS ///// iteration, depth == 1 // For gcc 4.4 compatability, we must include the // BOOST_PP_ITERATION_DEPTH test inside an #else clause. #else // BOOST_PP_IS_ITERATING #if BOOST_PP_ITERATION_DEPTH() == 1 # define i_ BOOST_PP_FRAME_ITERATION(1) template< BOOST_MPL_PP_PARAMS(i_, typename N) > struct AUX778076_OP_NAME<BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(i_, N, na)> #if i_ != 2 : AUX778076_OP_N_CALLS(i_, N) { BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(i_, N, na) ) ) }; #endif # undef i_ #endif // BOOST_PP_ITERATION_DEPTH() #endif // BOOST_PP_IS_ITERATING
gpl-3.0
calipzo/NFirmwareEditor
src/NCore/UI/WindowBase.cs
2791
using System; using System.ComponentModel; using System.Windows.Forms; namespace NCore.UI { public class WindowBase : Form { private IContainer components; public LocalizationExtender MainLocalizationExtender; public WindowBase() { InitializeComponent(); if (ApplicationService.IsIconAvailable) Icon = ApplicationService.ApplicationIcon; InfoBox = new InfoBox(this); Load += WindowBase_Load; } protected InfoBox InfoBox { get; private set; } protected void LocalizeSelf() { var localizableControls = MainLocalizationExtender.GetLocalizableControls(); #if DEBUG LocalizationManager.Instance.RegisterLocalizationKeyValue(localizableControls); #endif var localizationDictionary = LocalizationManager.Instance.GetLocalizationDictionary(); if (localizationDictionary == null || localizationDictionary.Count == 0) return; foreach (var kvp in localizableControls) { var control = kvp.Key; var key = kvp.Value; if (localizationDictionary.ContainsKey(key)) { control.Text = localizationDictionary[key]; } } OnLocalization(); } protected virtual void OnLocalization() { } private void WindowBase_Load(object sender, EventArgs e) { LocalizeSelf(); } protected bool IgnoreFirstInstanceMessages { get; set; } protected void ShowFromTray() { if (Opacity <= 0) Opacity = 1; Visible = true; ShowInTaskbar = true; Show(); WindowState = FormWindowState.Normal; NativeMethods.SetForegroundWindow(Handle); } protected void HideToTray() { Visible = false; ShowInTaskbar = false; Hide(); } protected override void WndProc(ref Message m) { if (!IgnoreFirstInstanceMessages && m.Msg == CrossApplicationSynchronizer.ShowFirstInstanceMessage) { ShowFromTray(); } base.WndProc(ref m); } protected internal void UpdateUI(Action action, bool supressExceptions = true) { if (!supressExceptions) { Invoke(action); } else { try { Invoke(action); } catch (Exception) { // Ignore } } } internal T UpdateUI<T>(Func<T> action) { var result = default(T); Invoke(new Action(() => result = action())); return result; } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.MainLocalizationExtender = new NCore.UI.LocalizationExtender(this.components); this.SuspendLayout(); // // WindowBase // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.ClientSize = new System.Drawing.Size(284, 261); this.MainLocalizationExtender.SetKey(this, ""); this.Name = "WindowBase"; this.ResumeLayout(false); } } }
gpl-3.0
jenarroyo/mahara-repo
htdocs/lib/dwoo/mahara/plugins/function.mahara_pagelinks.php
3146
<?php /** * Dwoo {mahara_pagelinks} function pluging * * appends an 'offset=n' parameter to the url to get the url for a different page * @param integer $limit number of items per page * @param integer $offset offset of first data item on this page * @param integer $count total number of items * @param string $url where to get results from * @param string $assign the template var to assign the result to * @return string * * THIS IS DEPRECATED. Pagination is done differently almost everywhere else * (e.g. find friends). One place this is being used is the admin user search. * Hopefully that can be converted away soon. */ function Dwoo_Plugin_mahara_pagelinks(Dwoo $dwoo, $offset, $limit, $count, $url, $assign='') { $offset = param_integer('offset', 0); $limit = intval($limit); $count = intval($count); $url = hsc($url); $id = substr(md5(microtime()), 0, 4); $output = '<div class="pagination" id="' . $id . '">'; if ($limit <= $count) { $pages = ceil($count / $limit); $page = $offset / $limit; $last = $pages - 1; $next = min($last, $page + 1); $prev = max(0, $page - 1); // Build a list of what pagenumbers will be put between the previous/next links $pagenumbers = array(0, $prev, $page, $next, $last); $pagenumbers = array_unique($pagenumbers); // Build the first/previous links $isfirst = $page == 0; $output .= mahara_pagelink('first', $url, 0, '&laquo; ' . get_string('first'), get_string('firstpage'), $isfirst); $output .= mahara_pagelink('prev', $url, $limit * $prev, '&larr; ' . get_string('previous'), get_string('prevpage'), $isfirst); // Build the pagenumbers in the middle foreach ($pagenumbers as $k => $i) { if ($k != 0 && $prevpagenum < $i - 1) { $output .= '…'; } if ($i == $page) { $output .= '<span class="selected">' . ($i + 1) . '</span>'; } else { $output .= mahara_pagelink('', $url, $limit * $i, $i + 1, '', false); } $prevpagenum = $i; } // Build the next/last links $islast = $page == $last; $output .= mahara_pagelink('next', $url, $limit * $next, get_string('next') . ' &rarr;', get_string('nextpage'), $islast); $output .= mahara_pagelink('last', $url, $limit * $last, get_string('last') . ' &raquo;', get_string('lastpage'), $islast); } // Close the container div $output .= '</div>'; if (!empty($assign)) { $dwoo->assignInScope($output, $assign); return; } return $output; } function mahara_pagelink($class, $url, $offset, $text, $title, $disabled=false) { $return = '<span class="pagination'; $return .= ($class) ? " $class" : ''; if ($disabled) { $return .= ' disabled">' . $text . '</span>'; } else { $return .= '">' . '<a href="' . $url . '&offset=' . $offset . '" title="' . $title . '">' . $text . '</a></span>'; } return $return; }
gpl-3.0
PeterAldur/WurmAssistant3
src/Apps/WurmAssistant/WurmAssistant3.Contracts/AreaConfig.cs
615
using Ninject; namespace AldursLab.WurmAssistant3 { /// <summary> /// This interface can be used to mark a single public class within an Area. /// It can be used to define custom binding logic for this Area. /// </summary> public abstract class AreaConfig { /// <summary> /// Implements custom Kernel configuration for this area. /// Note, that execution order between Areas is by default arbitrary, unless explicitly staged at the Core. /// </summary> /// <param name="kernel"></param> public abstract void Configure(IKernel kernel); } }
gpl-3.0
mario6829/AliceO2
Detectors/ITSMFT/ITS/macros/EVE/DisplayEventsComp.C
17337
/// \file DisplayEvents.C /// \brief Simple macro to display ITS digits, clusters and tracks #if !defined(__CLING__) || defined(__ROOTCLING__) #include <iostream> #include <array> #include <algorithm> #include <fstream> #include <TFile.h> #include <TTree.h> #include <TEveManager.h> #include <TEveBrowser.h> #include <TGButton.h> #include <TGNumberEntry.h> #include <TGFrame.h> #include <TGTab.h> #include <TGLCameraOverlay.h> #include <TEveFrameBox.h> #include <TEveQuadSet.h> #include <TEveTrans.h> #include <TEvePointSet.h> #include <TEveTrackPropagator.h> #include <TEveTrack.h> #include <TEveEventManager.h> #include <TEveScene.h> #include "EventVisualisationView/MultiView.h" #include "ITSMFTReconstruction/ChipMappingITS.h" #include "ITSMFTReconstruction/DigitPixelReader.h" #include "ITSMFTReconstruction/RawPixelReader.h" #include "ITSMFTBase/SegmentationAlpide.h" #include "DataFormatsITSMFT/Digit.h" #include "ITSBase/GeometryTGeo.h" #include "DataFormatsITSMFT/CompCluster.h" #include "DataFormatsITSMFT/TopologyDictionary.h" #include "DataFormatsITSMFT/ROFRecord.h" #include "DataFormatsITS/TrackITS.h" #include "DetectorsCommonDataFormats/DetectorNameConf.h" #endif using namespace o2::itsmft; extern TEveManager* gEve; static TEveScene* chipScene; static TGNumberEntry* gEntry; static TGNumberEntry* gChipID; class Data { public: void loadTF(int tf) { if (mClusTree) mClusTree->GetEntry(tf); if (mTracTree) mTracTree->GetEntry(tf); } void loadData(int entry); void displayData(int entry, int chip); int getLastEvent() const { return mLastEvent; } void setRawPixelReader(std::string input, int tf) { auto reader = new RawPixelReader<ChipMappingITS>(); reader->openInput(input); // Skip to the TimeFrame = tf // ??? mPixelReader = reader; mPixelReader->setDecodeNextAuto(false); } void setDigitPixelReader(std::string input, int tf) { auto reader = new DigitPixelReader(); reader->openInput(input, o2::detectors::DetID("ITS")); reader->init(); // Skip to the TimeFrame = tf do { reader->readNextEntry(); } while (tf--); mPixelReader = reader; mPixelReader->setDecodeNextAuto(false); } void setClusTree(TTree* t); void setTracTree(TTree* t); private: // Data loading members int mLastEvent = 0; PixelReader* mPixelReader = nullptr; ChipPixelData mChipData; std::vector<Digit> mDigits; std::vector<CompClusterExt>* mClusterBuffer = nullptr; gsl::span<CompClusterExt> mClusters; std::vector<o2::itsmft::ROFRecord>* mClustersROF = nullptr; std::vector<o2::its::TrackITS>* mTrackBuffer = nullptr; std::vector<int>* mClIdxBuffer = nullptr; gsl::span<o2::its::TrackITS> mTracks; std::vector<o2::itsmft::ROFRecord>* mTracksROF = nullptr; void loadDigits(); void loadDigits(int entry); void loadClusters(int entry); void loadTracks(int entry); TTree* mClusTree = nullptr; TTree* mTracTree = nullptr; // TEve-related members TEveElementList* mEvent = nullptr; TEveElementList* mChip = nullptr; TEveElement* getEveChipDigits(int chip); TEveElement* getEveChipClusters(int chip); TEveElement* getEveClusters(); TEveElement* getEveTracks(); } evdata; o2::itsmft::TopologyDictionary dict; void Data::loadDigits() { mPixelReader->decodeNextTrigger(); auto ir = mPixelReader->getInteractionRecord(); std::cout << "orbit/crossing: " << ' ' << ir.orbit << '/' << ir.bc << '\n'; while (mPixelReader->getNextChipData(mChipData)) { auto chipID = mChipData.getChipID(); auto pixels = mChipData.getData(); for (auto& pixel : pixels) { auto col = pixel.getCol(); auto row = pixel.getRowDirect(); mDigits.emplace_back(chipID, row, col, 0); } } std::cout << "Number of ITSDigits: " << mDigits.size() << '\n'; } void Data::loadDigits(int entry) { if (mPixelReader == nullptr) return; mDigits.clear(); for (; mLastEvent < entry; mLastEvent++) { mPixelReader->decodeNextTrigger(); while (mPixelReader->getNextChipData(mChipData)) { } } mLastEvent++; loadDigits(); } void Data::setClusTree(TTree* tree) { if (tree == nullptr) { std::cerr << "No tree for clusters !\n"; return; } tree->SetBranchAddress("ITSClusterComp", &mClusterBuffer); tree->SetBranchAddress("ITSClustersROF", &mClustersROF); mClusTree = tree; } void Data::loadClusters(int entry) { if (mClusTree == nullptr) return; int first = 0, last = mClusterBuffer->size(); if (!mClustersROF->empty()) { auto rof = (*mClustersROF)[entry]; auto ir = rof.getBCData(); std::cout << "Orbit: " << ir.orbit << " BC: " << ir.bc << '\n'; first = rof.getFirstEntry(); last = first + rof.getNEntries(); } mClusters = gsl::make_span(&(*mClusterBuffer)[first], last - first); std::cout << "Number of ITSClusters: " << mClusters.size() << '\n'; } void Data::setTracTree(TTree* tree) { if (tree == nullptr) { std::cerr << "No tree for tracks !\n"; return; } tree->SetBranchAddress("ITSTrack", &mTrackBuffer); tree->SetBranchAddress("ITSTrackClusIdx", &mClIdxBuffer); tree->SetBranchAddress("ITSTracksROF", &mTracksROF); mTracTree = tree; } void Data::loadTracks(int entry) { static int lastLoaded = -1; if (mTracTree == nullptr) return; int first = 0, last = mTrackBuffer->size(); if (!mTracksROF->empty()) { auto rof = (*mTracksROF)[entry]; first = rof.getFirstEntry(); last = first + rof.getNEntries(); } mTracks = gsl::make_span(&(*mTrackBuffer)[first], last - first); std::cout << "Number of ITSTracks: " << mTracks.size() << '\n'; } void Data::loadData(int entry) { loadDigits(entry); loadClusters(entry); loadTracks(entry); } constexpr float sizey = SegmentationAlpide::ActiveMatrixSizeRows; constexpr float sizex = SegmentationAlpide::ActiveMatrixSizeCols; constexpr float dy = SegmentationAlpide::PitchRow; constexpr float dx = SegmentationAlpide::PitchCol; constexpr float gap = 1e-4; // For a better visualization of pixels TEveElement* Data::getEveChipDigits(int chip) { TEveFrameBox* box = new TEveFrameBox(); box->SetAAQuadXY(0, 0, 0, sizex, sizey); box->SetFrameColor(kGray); // Digits TEveQuadSet* qdigi = new TEveQuadSet("digits"); qdigi->SetOwnIds(kTRUE); qdigi->SetFrame(box); qdigi->Reset(TEveQuadSet::kQT_RectangleXY, kFALSE, 32); auto gman = o2::its::GeometryTGeo::Instance(); std::vector<int> occup(gman->getNumberOfChips()); for (const auto& d : mDigits) { auto id = d.getChipIndex(); occup[id]++; if (id != chip) continue; int row = d.getRow(); int col = d.getColumn(); int charge = d.getCharge(); qdigi->AddQuad(col * dx + gap, row * dy + gap, 0., dx - 2 * gap, dy - 2 * gap); qdigi->QuadValue(charge); } qdigi->RefitPlex(); TEveTrans& t = qdigi->RefMainTrans(); t.RotateLF(1, 3, 0.5 * TMath::Pi()); t.SetPos(0, 0, 0); auto most = std::distance(occup.begin(), std::max_element(occup.begin(), occup.end())); if (occup[most] > 0) { std::cout << "Most occupied chip: " << most << " (" << occup[most] << " digits)\n"; } if (occup[chip] > 0) { std::cout << "Chip " << chip << " number of digits " << occup[chip] << '\n'; return qdigi; } delete qdigi; return nullptr; } TEveElement* Data::getEveChipClusters(int chip) { TEveFrameBox* box = new TEveFrameBox(); box->SetAAQuadXY(0, 0, 0, sizex, sizey); box->SetFrameColor(kGray); // Clusters TEveQuadSet* qclus = new TEveQuadSet("clusters"); qclus->SetOwnIds(kTRUE); qclus->SetFrame(box); int ncl = 0; qclus->Reset(TEveQuadSet::kQT_LineXYFixedZ, kFALSE, 32); for (const auto& c : mClusters) { auto id = c.getSensorID(); if (id != chip) continue; ncl++; auto pattern = dict.getPattern(c.getPatternID()); int row = c.getRow(); int col = c.getCol(); int len = pattern.getColumnSpan(); int wid = pattern.getRowSpan(); qclus->AddLine(col * dx, row * dy, len * dx, 0.); qclus->AddLine(col * dx, row * dy, 0., wid * dy); qclus->AddLine((col + len) * dx, row * dy, 0., wid * dy); qclus->AddLine(col * dx, (row + wid) * dy, len * dx, 0.); } qclus->RefitPlex(); TEveTrans& ct = qclus->RefMainTrans(); ct.RotateLF(1, 3, 0.5 * TMath::Pi()); ct.SetPos(0, 0, 0); if (ncl > 0) { std::cout << "Chip " << chip << " number of clusters " << ncl << '\n'; return qclus; } delete qclus; return nullptr; } TEveElement* Data::getEveClusters() { if (mClusters.empty()) return nullptr; auto gman = o2::its::GeometryTGeo::Instance(); TEvePointSet* clusters = new TEvePointSet("clusters"); clusters->SetMarkerColor(kBlue); for (const auto& c : mClusters) { auto locC = dict.getClusterCoordinates(c); auto id = c.getSensorID(); const auto gloC = gman->getMatrixL2G(id) * locC; clusters->SetNextPoint(gloC.X(), gloC.Y(), gloC.Z()); } return clusters; } TEveElement* Data::getEveTracks() { if (mTracks.empty()) return nullptr; auto gman = o2::its::GeometryTGeo::Instance(); TEveTrackList* tracks = new TEveTrackList("tracks"); auto prop = tracks->GetPropagator(); prop->SetMagField(0.5); prop->SetMaxR(50.); for (const auto& rec : mTracks) { std::array<float, 3> p; rec.getPxPyPzGlo(p); std::array<float, 3> v; rec.getXYZGlo(v); TEveRecTrackD t; t.fP = {p[0], p[1], p[2]}; t.fV = {v[0], v[1], v[2]}; //t.fV = {v[0] - p[0] / p[1] * v[1], 0, v[2] - p[2] / p[1] * v[1]}; t.fSign = (rec.getSign() < 0) ? -1 : 1; TEveTrack* track = new TEveTrack(&t, prop); track->SetLineColor(kMagenta); tracks->AddElement(track); if (mClusters.empty()) continue; TEvePointSet* tpoints = new TEvePointSet("tclusters"); tpoints->SetMarkerColor(kGreen); int nc = rec.getNumberOfClusters(); int idxRef = rec.getFirstClusterEntry(); while (nc--) { Int_t idx = (*mClIdxBuffer)[idxRef + nc]; const CompClusterExt& c = (*mClusterBuffer)[idx]; auto locC = dict.getClusterCoordinates(c); auto id = c.getSensorID(); const auto gloC = gman->getMatrixL2G(id) * locC; tpoints->SetNextPoint(gloC.X(), gloC.Y(), gloC.Z()); } track->AddElement(tpoints); } tracks->MakeTracks(); return tracks; } void Data::displayData(int entry, int chip) { std::string ename("Event #"); ename += std::to_string(entry); // Chip display auto chipDigits = getEveChipDigits(chip); auto chipClusters = getEveChipClusters(chip); delete mChip; mChip = nullptr; if (chipDigits || chipClusters) { std::string cname(ename + " ALPIDE chip #"); cname += std::to_string(chip); mChip = new TEveElementList(cname.c_str()); if (chipDigits) { mChip->AddElement(chipDigits); } if (chipClusters) { mChip->AddElement(chipClusters); } gEve->AddElement(mChip, chipScene); } // Event display auto clusters = getEveClusters(); auto tracks = getEveTracks(); delete mEvent; mEvent = nullptr; if (clusters || tracks) { mEvent = new TEveElementList(ename.c_str()); if (clusters) mEvent->AddElement(clusters); if (tracks) mEvent->AddElement(tracks); auto multi = o2::event_visualisation::MultiView::getInstance(); multi->registerEvent(mEvent); } gEve->Redraw3D(kFALSE); } void load(int entry, int chip) { int lastEvent = evdata.getLastEvent(); if (lastEvent > entry) { std::cerr << "\nERROR: Cannot stay or go back over events. Please increase the event number !\n\n"; gEntry->SetIntNumber(lastEvent - 1); return; } gEntry->SetIntNumber(entry); gChipID->SetIntNumber(chip); std::cout << "\n*** Event #" << entry << " ***\n"; evdata.loadData(entry); evdata.displayData(entry, chip); } void load(int tf, int trigger, int chip) { evdata.loadTF(tf); load(trigger, chip); } void init(int tf, int trigger, int chip, std::string digifile = "itsdigits.root", bool rawdata = false, std::string clusfile = "o2clus_its.root", std::string tracfile = "o2trac_its.root", std::string inputGeom = "") { dict.readFromFile(o2::base::DetectorNameConf::getAlpideClusterDictionaryFileName(o2::detectors::DetID::ITS)); TEveManager::Create(kTRUE, "V"); TEveBrowser* browser = gEve->GetBrowser(); // Geometry o2::base::GeometryManager::loadGeometry(inputGeom); auto gman = o2::its::GeometryTGeo::Instance(); gman->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::T2L, o2::math_utils::TransformType::T2GRot, o2::math_utils::TransformType::L2G)); // Chip View browser->GetTabRight()->SetText("Chip View"); auto chipView = gEve->GetDefaultViewer(); chipView->SetName("Chip Viewer"); chipView->DestroyElements(); chipScene = gEve->SpawnNewScene("Chip View", "Chip view desciption"); chipView->AddScene(chipScene); TGLViewer* v = gEve->GetDefaultGLViewer(); v->SetCurrentCamera(TGLViewer::kCameraOrthoZOY); TGLCameraOverlay* co = v->GetCameraOverlay(); co->SetShowOrthographic(kTRUE); co->SetOrthographicMode(TGLCameraOverlay::kGridFront); // Event View auto multi = o2::event_visualisation::MultiView::getInstance(); multi->drawGeometryForDetector("ITS"); gEve->AddEvent(new TEveEventManager()); // Event navigation browser->StartEmbedding(TRootBrowser::kBottom); auto frame = new TGMainFrame(gClient->GetRoot(), 1000, 600, kVerticalFrame); auto h = new TGHorizontalFrame(frame); auto b = new TGTextButton(h, "PrevEvnt", "prev()"); h->AddFrame(b); gEntry = new TGNumberEntry(h, 0, 7, -1, TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative, TGNumberFormat::kNELLimitMinMax, 0, 1000000); gEntry->Connect("ValueSet(Long_t)", 0, 0, "load()"); h->AddFrame(gEntry); b = new TGTextButton(h, "NextEvnt", "next()"); h->AddFrame(b); frame->AddFrame(h); // Chip navigation h = new TGHorizontalFrame(frame); b = new TGTextButton(h, "PrevChip", "prevChip()"); h->AddFrame(b); gChipID = new TGNumberEntry(h, 0, 5, -1, TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative, TGNumberFormat::kNELLimitMinMax, 0, gman->getNumberOfChips()); gChipID->Connect("ValueSet(Long_t)", 0, 0, "loadChip()"); h->AddFrame(gChipID); b = new TGTextButton(h, "NextChip", "nextChip()"); h->AddFrame(b); frame->AddFrame(h); frame->MapSubwindows(); frame->MapWindow(); browser->StopEmbedding("Navigator"); TFile* file; // Data sources if (rawdata) { std::ifstream* rawfile = new std::ifstream(digifile.data(), std::ifstream::binary); if (rawfile->good()) { delete rawfile; std::cout << "Running with raw digits...\n"; evdata.setRawPixelReader(digifile.data(), tf); } else std::cerr << "\nERROR: Cannot open file: " << digifile << "\n\n"; } else { file = TFile::Open(digifile.data()); if (file && gFile->IsOpen()) { file->Close(); std::cout << "Running with MC digits...\n"; evdata.setDigitPixelReader(digifile.data(), tf); //evdata.setDigiTree((TTree*)gFile->Get("o2sim")); } else std::cerr << "\nERROR: Cannot open file: " << digifile << "\n\n"; } file = TFile::Open(clusfile.data()); if (file && gFile->IsOpen()) evdata.setClusTree((TTree*)gFile->Get("o2sim")); else std::cerr << "ERROR: Cannot open file: " << clusfile << "\n\n"; file = TFile::Open(tracfile.data()); if (file && gFile->IsOpen()) evdata.setTracTree((TTree*)gFile->Get("o2sim")); else std::cerr << "\nERROR: Cannot open file: " << tracfile << "\n\n"; std::cout << "\n **** Navigation over events and chips ****\n"; std::cout << " load(event, chip) \t jump to the specified event and chip\n"; std::cout << " next() \t\t load next event \n"; std::cout << " prev() \t\t load previous event \n"; std::cout << " loadChip(chip) \t jump to the specified chip within the current event \n"; std::cout << " nextChip() \t\t load the next chip within the current event \n"; std::cout << " prevChip() \t\t load the previous chip within the current event \n"; evdata.loadTF(tf); load(trigger, chip); gEve->Redraw3D(kTRUE); } void load() { auto event = gEntry->GetNumberEntry()->GetIntNumber(); auto chip = gChipID->GetNumberEntry()->GetIntNumber(); load(event, chip); } void next() { auto event = gEntry->GetNumberEntry()->GetIntNumber(); event++; auto chip = gChipID->GetNumberEntry()->GetIntNumber(); load(event, chip); } void prev() { auto event = gEntry->GetNumberEntry()->GetIntNumber(); event--; auto chip = gChipID->GetNumberEntry()->GetIntNumber(); load(event, chip); } void loadChip() { auto event = gEntry->GetNumberEntry()->GetIntNumber(); auto chip = gChipID->GetNumberEntry()->GetIntNumber(); evdata.displayData(event, chip); } void loadChip(int chip) { gChipID->SetIntNumber(chip); loadChip(); } void nextChip() { auto chip = gChipID->GetNumberEntry()->GetIntNumber(); chip++; loadChip(chip); } void prevChip() { auto chip = gChipID->GetNumberEntry()->GetIntNumber(); chip--; loadChip(chip); } void DisplayEventsComp(int tf = 0, int trigger = 0, int chip = 7) { // A dummy function with the same name as this macro init(tf, trigger, chip); gEve->GetBrowser()->GetTabRight()->SetTab(1); }
gpl-3.0
kevinwiede/webspell-nerv
languages/hr/squads.php
2509
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = Array( /* do not edit above this line */ 'about'=>'opis', 'active'=>'aktivan', 'add_buddy'=>'dodaj na listu prijatelja', 'awards'=>'nagrade', 'back_buddy'=>'povratak na listu prijatelja', 'back_squad_overview'=>'povratak na pregled tima', 'challenge'=>'izazovi nas', 'contact'=>'Kontakt', 'email'=>'e-mail', 'ignore'=>'ignoriraj korisnika', 'inactive'=>'nije aktivan', 'member'=>'Član', 'members'=>'Članovi', 'messenger'=>'poruke', 'no_description'=>'nije dostupan opis', 'no_userpic'=>'Nije dostupna slika korisnika!', 'position'=>'Pozicija', 'results'=>'rezultati', 'show_details'=>'prikaži detalje', 'squad_plays'=>'Tim igra', 'squads'=>'timovi', 'status'=>'Status', 'town'=>'Grad', 'userpicture'=>'slika korisnika' ); ?>
gpl-3.0
komidore64/hammer-cli-sam
lib/hammer_cli_sam/repository.rb
683
module HammerCLISAM commands = %w( create delete update upload-content ) commands.each do |cmd| HammerCLI::MainCommand.find_subcommand('repository').subcommand_class.remove_subcommand(cmd) end module Repository class ListCommand < HammerCLIKatello::Repository::ListCommand include HammerCLISAM::ExcludeOptions exclude_options(:content_view, :library, :environment) end end HammerCLIKatello::Repository.subcommand!( HammerCLIKatello::Repository::ListCommand.command_name, HammerCLIKatello::Repository::ListCommand.desc, HammerCLISAM::Repository::ListCommand ) end
gpl-3.0
lukeIam/Vocaluxe
VocaluxeLib/Songs/CSongWriter.cs
10088
#region license // This file is part of Vocaluxe. // // Vocaluxe is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Vocaluxe is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using System.Collections.Generic; using System.IO; using VocaluxeLib.Log; namespace VocaluxeLib.Songs { public partial class CSong { private class CSongWriter { private readonly CSong _Song; private TextWriter _Tw; public CSongWriter(CSong song) { _Song = song; } private void _WriteHeaderEntry(string id, string value) { if (!String.IsNullOrEmpty(value)) _Tw.WriteLine("#" + id.ToUpper() + ":" + value); } private void _WriteHeaderEntry(string id, bool value) { if (value) _WriteHeaderEntry(id, "YES"); } private void _WriteHeaderEntry(string id, float value, float def = 0f) { if (Math.Abs(value - def) > 0.0001) _WriteHeaderEntry(id, value.ToInvariantString()); } private void _WriteHeaderEntry(string id, int value, int def = 0) { if (value != def) _WriteHeaderEntry(id, value.ToString()); } private void _WriteHeaderEntrys(string id, ICollection<string> value) { if (value == null || value.Count <= 0) return; foreach (String val in value) _WriteHeaderEntry(id, val); } private void _WriteHeader() { if (_Song.ManualEncoding) _WriteHeaderEntry("ENCODING", _Song.Encoding.GetEncodingName()); _WriteHeaderEntry("CREATOR", _Song.Creator); _WriteHeaderEntry("VERSION", _Song.Version); _WriteHeaderEntry("LENGTH", _Song.Length); _WriteHeaderEntry("SOURCE", _Song.Source); if (!String.IsNullOrEmpty(_Song._Comment)) { string comment = _Song._Comment.Replace("\r\n", "\n").Replace('\r', '\n'); char[] splitChar = {'\n'}; _WriteHeaderEntrys("COMMENT", comment.Split(splitChar)); } _WriteHeaderEntry("TITLE", _Song.Title); _WriteHeaderEntry("ARTIST", _Song.Artist); if (!_Song.Title.Equals(_Song.TitleSorting)) _WriteHeaderEntry("TITLE-ON-SORTING", _Song.TitleSorting); if (!_Song.Artist.Equals(_Song.ArtistSorting)) _WriteHeaderEntry("ARTIST-ON-SORTING", _Song.ArtistSorting); _WriteHeaderEntrys("EDITION", _Song.Editions); _WriteHeaderEntrys("GENRE", _Song.Genres); _WriteHeaderEntrys("LANGUAGE", _Song.Languages); _WriteHeaderEntry("ALBUM", _Song.Album); _WriteHeaderEntry("YEAR", _Song.Year); _WriteHeaderEntry("MP3", _Song.MP3FileName); _WriteHeaderEntry("COVER", _Song.CoverFileName); _WriteHeaderEntrys("BACKGROUND", _Song.BackgroundFileNames); _WriteHeaderEntry("VIDEO", _Song.VideoFileName); _WriteHeaderEntry("VIDEOGAP", _Song.VideoGap); if (_Song.VideoAspect != EAspect.Crop) _WriteHeaderEntry("VIDEOASPECT", _Song.VideoAspect.ToString()); _WriteHeaderEntry("RELATIVE", _Song.Relative); _WriteHeaderEntry("BPM", _Song.BPM / _BPMFactor); _WriteHeaderEntry("GAP", (int)(_Song.Gap * 1000f)); if (_Song.Preview.Source == EDataSource.Tag) _WriteHeaderEntry("PREVIEWSTART", _Song.Preview.StartTime); _WriteHeaderEntry("START", _Song.Start); _WriteHeaderEntry("END", (int)(_Song.Finish * 1000f)); if (_Song.ShortEnd.Source == EDataSource.Tag) _WriteHeaderEntry("ENDSHORT", (int)(CBase.Game.GetTimeFromBeats(_Song.ShortEnd.EndBeat, _Song.BPM) + _Song.Gap) * 1000); if (!_Song._CalculateMedley) _WriteHeaderEntry("CALCMEDLEY", "OFF"); if (_Song.Medley.Source == EDataSource.Tag) { _WriteHeaderEntry("MEDLEYSTARTBEAT", _Song.Medley.StartBeat); _WriteHeaderEntry("MEDLEYENDBEAT", _Song.Medley.EndBeat); } for (int i = 0; i < _Song.Notes.VoiceCount; i++) { if (_Song.Notes.VoiceNames.IsSet(i)) _WriteHeaderEntry("P" + i, _Song.Notes.VoiceNames[i]); } foreach (string addLine in _Song.UnknownTags) _Tw.WriteLine(addLine); } /// <summary> /// Gets a good beat for a line break that is &gt;=firstPossibleBeat and &lt;firstNoteBeat /// Based on algorithm used by YASS: http://www.yass-along.com/errors.html /// </summary> /// <param name="firstPossibleBeat">First beat that is possible for a line break (equal (just after) previous line note end)</param> /// <param name="firstNoteBeat">First note beat on current line</param> /// <returns>A good beat for the line break</returns> private int _GetBreakBeat(int firstPossibleBeat, int firstNoteBeat) { int breakBeat; int diff = firstNoteBeat - firstPossibleBeat; float timeDiff = CBase.Game.GetTimeFromBeats(diff, _Song.BPM); if (timeDiff > 4f) breakBeat = firstPossibleBeat + (int)CBase.Game.GetBeatFromTime(2f, _Song.BPM, 0f); else if (timeDiff > 2f) breakBeat = firstPossibleBeat + (int)CBase.Game.GetBeatFromTime(1f, _Song.BPM, 0f); else if (diff < 2) breakBeat = firstPossibleBeat; else if (diff < 9) breakBeat = firstNoteBeat - 2; else if (diff < 13) breakBeat = firstNoteBeat - 3; else if (diff < 17) breakBeat = firstNoteBeat - 4; else breakBeat = firstPossibleBeat + 12; return breakBeat; } private void _WriteNotes() { for (int i = 0; i < _Song.Notes.VoiceCount; i++) { CVoice voice = _Song.Notes.GetVoice(i); if (_Song.Notes.VoiceCount > 1) _Tw.WriteLine("P" + Math.Pow(2, i)); int currentBeat = 0; CSongLine lastLine = null; foreach (CSongLine line in voice.Lines) { if (lastLine != null) { string lineTxt = "- " + (_GetBreakBeat(lastLine.EndBeat + 1, line.FirstNoteBeat) - currentBeat); if (_Song.Relative) { lineTxt += " " + (line.FirstNoteBeat - currentBeat); currentBeat = line.FirstNoteBeat; } _Tw.WriteLine(lineTxt); } foreach (CSongNote note in line.Notes) { string tag; switch (note.Type) { case ENoteType.Normal: tag = ":"; break; case ENoteType.Golden: tag = "*"; break; case ENoteType.Freestyle: tag = "F"; break; default: throw new NotImplementedException("Note type " + note.Type); } _Tw.WriteLine(tag + " " + (note.StartBeat - currentBeat) + " " + note.Duration + " " + note.Tone + " " + note.Text); } lastLine = line; } } _Tw.WriteLine("E"); } public bool SaveFile(string filePath) { try { _Tw = new StreamWriter(filePath, false, _Song.Encoding); _WriteHeader(); _WriteNotes(); } catch (UnauthorizedAccessException) { CLog.Error("Cannot write " + filePath + ". Directory might be readonly or requires admin rights."); return false; } catch (Exception e) { CLog.Error("Unhandled exception while writing " + filePath + ": " + e); return false; } finally { if (_Tw != null) _Tw.Dispose(); } return true; } } } }
gpl-3.0
remytms/Distribution
main/core/Entity/Widget/WidgetHomeTabConfig.php
4067
<?php /* * This file is part of the Claroline Connect package. * * (c) Claroline Consortium <consortium@claroline.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Claroline\CoreBundle\Entity\Widget; use Claroline\CoreBundle\Entity\Home\HomeTab; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\SerializedName; /** * @ORM\Entity(repositoryClass="Claroline\CoreBundle\Repository\WidgetHomeTabConfigRepository") * @ORM\Table( * name="claro_widget_home_tab_config" * ) */ class WidgetHomeTabConfig { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") * @Groups({"api_widget"}) * @SerializedName("id") */ protected $id; /** * @ORM\ManyToOne( * targetEntity="Claroline\CoreBundle\Entity\Widget\WidgetInstance" * ) * @ORM\JoinColumn(name="widget_instance_id", onDelete="CASCADE", nullable=true) * @Groups({"api_widget"}) * @SerializedName("widgetInstance") */ protected $widgetInstance; /** * @ORM\ManyToOne( * targetEntity="Claroline\CoreBundle\Entity\Home\HomeTab", * inversedBy="widgetHomeTabConfigs" * ) * @ORM\JoinColumn(name="home_tab_id", onDelete="CASCADE", nullable=false) * @Groups({"api_widget"}) * @SerializedName("homeTab") */ protected $homeTab; /** * @ORM\ManyToOne( * targetEntity="Claroline\CoreBundle\Entity\User" * ) * @ORM\JoinColumn(name="user_id", nullable=true, onDelete="CASCADE") */ protected $user; /** * @ORM\ManyToOne( * targetEntity="Claroline\CoreBundle\Entity\Workspace\Workspace" * ) * @ORM\JoinColumn(name="workspace_id", nullable=true, onDelete="CASCADE") */ protected $workspace; /** * @ORM\Column(name="widget_order", type="integer") * @Groups({"api_widget"}) * @SerializedName("order") */ protected $widgetOrder; /** * @ORM\Column() * @Groups({"api_widget"}) * @SerializedName("type") */ protected $type; /** * @ORM\Column(type="boolean", name="is_visible") * @Groups({"api_widget"}) * @SerializedName("visible") */ protected $visible = true; /** * @ORM\Column(type="boolean", name="is_locked") * @Groups({"api_widget"}) * @SerializedName("locked") */ protected $locked = false; public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getWidgetInstance() { return $this->widgetInstance; } public function setWidgetInstance(WidgetInstance $widgetInstance) { $this->widgetInstance = $widgetInstance; } public function getHomeTab() { return $this->homeTab; } public function setHomeTab(HomeTab $homeTab) { $this->homeTab = $homeTab; } public function getUser() { return $this->user; } public function setUser($user) { $this->user = $user; } public function getWorkspace() { return $this->workspace; } public function setWorkspace($workspace) { $this->workspace = $workspace; } public function getWidgetOrder() { return $this->widgetOrder; } public function setWidgetOrder($widgetOrder) { $this->widgetOrder = $widgetOrder; } public function getType() { return $this->type; } public function setType($type) { $this->type = $type; } public function isVisible() { return $this->visible; } public function setVisible($visible) { $this->visible = $visible; } public function isLocked() { return $this->locked; } public function setLocked($locked) { $this->locked = $locked; } }
gpl-3.0
Mihara/RasterPropMonitor
RasterPropMonitor/Core/FlyingCamera.cs
13628
/***************************************************************************** * RasterPropMonitor * ================= * Plugin for Kerbal Space Program * * by Mihara (Eugene Medvedev), MOARdV, and other contributors * * RasterPropMonitor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, revision * date 29 June 2007, or (at your option) any later version. * * RasterPropMonitor is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with RasterPropMonitor. If not, see <http://www.gnu.org/licenses/>. ****************************************************************************/ using System; using UnityEngine; // FIXME: This module turned into total spaghetti by now and needs some serious rethinking. namespace JSI { public class FlyingCamera { private readonly Vessel ourVessel; private readonly Part ourPart; private GameObject cameraTransform; private Part cameraPart; private readonly int fxCameraIndex = 6; private readonly string[] knownCameraNames = { "GalaxyCamera", "Camera ScaledSpace", "Camera VE Underlay", // Environmental Visual Enhancements plugin camera "Camera VE Overlay", // Environmental Visual Enhancements plugin camera "Camera 01", "Camera 00", "FXCamera" }; private readonly Camera[] cameraObject = { null, null, null, null, null, null, null }; private readonly float cameraAspect; private bool enabled; private bool isReferenceCamera, isReferenceClawCamera, isReferenceTransformCamera; private ModuleGrappleNode clawModule; private Part referencePart; private const string referenceCamera = "CurrentReferenceDockingPortCamera"; private readonly Quaternion referencePointRotation = Quaternion.Euler(-90, 0, 0); private float flickerChance; private int flickerMaxTime; private int flickerCounter; public float FOV { get; set; } public FlyingCamera(Part thatPart, float aspect) { ourVessel = thatPart.vessel; ourPart = thatPart; cameraAspect = aspect; } public void SetFlicker(float flicker, int flickerTime) { flickerChance = flicker; flickerMaxTime = flickerTime; flickerCounter = 0; } public bool PointCamera(string newCameraName, float initialFOV) { CleanupCameraObjects(); if (!string.IsNullOrEmpty(newCameraName)) { FOV = initialFOV; if (newCameraName == referenceCamera) { JUtil.LogMessage(this, "Tracking reference point docking port camera."); return PointToReferenceCamera(); } else { isReferenceClawCamera = false; return CreateCameraObjects(newCameraName); } } else { return false; } } private bool PointToReferenceCamera() { isReferenceCamera = true; referencePart = ourVessel.GetReferenceTransformPart(); ModuleDockingNode thatPort = null; ModuleGrappleNode thatClaw = null; if (referencePart != null) { foreach (PartModule thatModule in referencePart.Modules) { thatPort = thatModule as ModuleDockingNode; thatClaw = thatModule as ModuleGrappleNode; if (thatPort != null || thatClaw != null) { break; } } } if (thatPort != null) { if (!LocateCamera(referencePart, "dockingNode")) { cameraPart = thatPort.part; cameraTransform = ourVessel.ReferenceTransform.gameObject; isReferenceTransformCamera = true; } isReferenceClawCamera = false; return CreateCameraObjects(); } else if (thatClaw != null) { // Mihara: Dirty hack to get around the fact that claws have their reference transform inside the structure. if (LocateCamera(referencePart, "ArticulatedCap")) { isReferenceClawCamera = true; clawModule = thatClaw; } else { JUtil.LogMessage(this, "Claw was not a stock part. Falling back to reference transform position..."); cameraPart = thatClaw.part; cameraTransform = ourVessel.ReferenceTransform.gameObject; } return CreateCameraObjects(); } else { return false; } } private bool CreateCameraObjects(string newCameraName = null) { if (!string.IsNullOrEmpty(newCameraName)) { isReferenceCamera = false; isReferenceClawCamera = false; clawModule = null; // First, we search our own part for this camera transform, // only then we search all other parts of the vessel. if (!LocateCamera(ourPart, newCameraName)) { foreach (Part thatpart in ourVessel.parts) { if (LocateCamera(thatpart, newCameraName)) break; } } } if (cameraTransform != null) { for (int i = 0; i < knownCameraNames.Length; ++i) { CameraSetup(i, knownCameraNames[i]); } enabled = true; //JUtil.LogMessage(this, "Switched to camera \"{0}\".", cameraTransform.name); return true; } else { //JUtil.LogMessage(this, "Tried to switch to camera \"{0}\" but camera was not found.", newCameraName); return false; } } private void CleanupCameraObjects() { if (enabled) { for (int i = 0; i < cameraObject.Length; i++) { try { UnityEngine.Object.Destroy(cameraObject[i]); // Analysis disable once EmptyGeneralCatchClause } catch { // Yes, that's really what it's supposed to be doing. } finally { cameraObject[i] = null; } } enabled = false; //JUtil.LogMessage(this, "Turning camera off."); } cameraPart = null; cameraTransform = null; } private bool LocateCamera(Part thatpart, string transformName) { Transform location = thatpart.FindModelTransform(transformName); if (location != null) { cameraTransform = location.gameObject; cameraPart = thatpart; return true; } return false; } private void CameraSetup(int index, string sourceName) { Camera sourceCam = JUtil.GetCameraByName(sourceName); if (sourceCam != null) { var cameraBody = new GameObject(); cameraBody.name = typeof(RasterPropMonitor).Name + index + cameraBody.GetInstanceID(); cameraObject[index] = cameraBody.AddComponent<Camera>(); // Just in case to support JSITransparentPod. cameraObject[index].cullingMask &= ~(1 << 16 | 1 << 20); cameraObject[index].CopyFrom(sourceCam); cameraObject[index].enabled = false; cameraObject[index].aspect = cameraAspect; // Minor hack to bring the near clip plane for the "up close" // cameras drastically closer to where the cameras notionally // are. Experimentally, these two cameras have N/F of 0.4 / 300.0, // or 750:1 Far/Near ratio. Changing this to 8192:1 brings the // near plane to 37cm or so, which hopefully is close enough to // see nearby details without creating z-fighting artifacts. if (index == 5 || index == 6) { cameraObject[index].nearClipPlane = cameraObject[index].farClipPlane / 8192.0f; } } } public Quaternion CameraRotation(float yawOffset = 0.0f, float pitchOffset = 0.0f) { Quaternion rotation = cameraTransform.transform.rotation; if (isReferenceTransformCamera) { rotation *= referencePointRotation; } Quaternion offset = Quaternion.Euler(new Vector3(pitchOffset, yawOffset, 0.0f)); return rotation * offset; } public Transform GetTransform() { return cameraTransform.transform; } public Vector3 GetTransformForward() { return isReferenceTransformCamera ? cameraTransform.transform.up : cameraTransform.transform.forward; } public bool Render(RenderTexture screen, float yawOffset, float pitchOffset) { if (isReferenceCamera && ourVessel.GetReferenceTransformPart() != referencePart) { CleanupCameraObjects(); PointToReferenceCamera(); } if (isReferenceClawCamera && clawModule.state != "Ready") { return false; } if (!enabled) return false; if (cameraPart == null || cameraPart.vessel != FlightGlobals.ActiveVessel || cameraTransform == null || cameraTransform.transform == null) { CleanupCameraObjects(); return false; } // Randomized camera flicker. if (flickerChance > 0 && flickerCounter == 0) { if (flickerChance > UnityEngine.Random.Range(0f, 1000f)) { flickerCounter = UnityEngine.Random.Range(1, flickerMaxTime); } } if (flickerCounter > 0) { flickerCounter--; return false; } Quaternion rotation = cameraTransform.transform.rotation; if (isReferenceTransformCamera) { // Reference transforms of docking ports have the wrong orientation, so need an extra rotation applied before that. rotation *= referencePointRotation; } Quaternion offset = Quaternion.Euler(new Vector3(pitchOffset, yawOffset, 0.0f)); rotation = rotation * offset; // This is a hack - FXCamera isn't always available, so I need to add and remove it in flight. // I don't know if there's a callback I can use to find when it's added, so brute force it for now. bool fxCameraExists = JUtil.DoesCameraExist(knownCameraNames[fxCameraIndex]); if (cameraObject[fxCameraIndex] == null) { if (fxCameraExists) { CameraSetup(fxCameraIndex, knownCameraNames[fxCameraIndex]); } } else if (!fxCameraExists) { try { UnityEngine.Object.Destroy(cameraObject[fxCameraIndex]); // Analysis disable once EmptyGeneralCatchClause } catch { // Yes, that's really what it's supposed to be doing. } finally { cameraObject[fxCameraIndex] = null; } } for (int i = 0; i < cameraObject.Length; i++) { if (cameraObject[i] != null) { // ScaledSpace camera and its derived cameras from Visual Enhancements mod are special - they don't move. if (i >= 3) { cameraObject[i].transform.position = cameraTransform.transform.position; } cameraObject[i].targetTexture = screen; cameraObject[i].transform.rotation = rotation; cameraObject[i].fieldOfView = FOV; cameraObject[i].Render(); } } return true; } } }
gpl-3.0
robacklin/sigrok
pulseview/pv/data/segment.cpp
2544
/* * This file is part of the PulseView project. * * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "segment.hpp" #include <assert.h> #include <stdlib.h> #include <string.h> using std::lock_guard; using std::recursive_mutex; namespace pv { namespace data { Segment::Segment(uint64_t samplerate, unsigned int unit_size) : sample_count_(0), start_time_(0), samplerate_(samplerate), capacity_(0), unit_size_(unit_size) { lock_guard<recursive_mutex> lock(mutex_); assert(unit_size_ > 0); } Segment::~Segment() { lock_guard<recursive_mutex> lock(mutex_); } uint64_t Segment::get_sample_count() const { lock_guard<recursive_mutex> lock(mutex_); return sample_count_; } double Segment::start_time() const { return start_time_; } double Segment::samplerate() const { return samplerate_; } void Segment::set_samplerate(double samplerate) { samplerate_ = samplerate; } unsigned int Segment::unit_size() const { return unit_size_; } void Segment::set_capacity(const uint64_t new_capacity) { lock_guard<recursive_mutex> lock(mutex_); assert(capacity_ >= sample_count_); if (new_capacity > capacity_) { capacity_ = new_capacity; data_.resize((new_capacity * unit_size_) + sizeof(uint64_t)); } } uint64_t Segment::capacity() const { lock_guard<recursive_mutex> lock(mutex_); return data_.size(); } void Segment::append_data(void *data, uint64_t samples) { lock_guard<recursive_mutex> lock(mutex_); assert(capacity_ >= sample_count_); // Ensure there's enough capacity to copy. const uint64_t free_space = capacity_ - sample_count_; if (free_space < samples) { set_capacity(sample_count_ + samples); } memcpy((uint8_t*)data_.data() + sample_count_ * unit_size_, data, samples * unit_size_); sample_count_ += samples; } } // namespace data } // namespace pv
gpl-3.0
matso165/islands-of-tribes
StoneAge/server/node_modules/mathjs/lib/version.js
145
module.exports = '3.9.1'; // Note: This file is automatically generated when building math.js. // Changes made in this file will be overwritten.
gpl-3.0
bserdar/lightblue-core
crud/src/main/java/com/redhat/lightblue/crud/validator/EnumChecker.java
2531
/* Copyright 2013 Red Hat, Inc. and/or its affiliates. This file is part of lightblue. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.redhat.lightblue.crud.validator; import java.util.Set; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.redhat.lightblue.crud.ConstraintValidator; import com.redhat.lightblue.crud.CrudConstants; import com.redhat.lightblue.crud.FieldConstraintValueChecker; import com.redhat.lightblue.metadata.Enum; import com.redhat.lightblue.metadata.FieldConstraint; import com.redhat.lightblue.metadata.FieldTreeNode; import com.redhat.lightblue.metadata.constraints.EnumConstraint; import com.redhat.lightblue.util.Error; import com.redhat.lightblue.util.JsonDoc; import com.redhat.lightblue.util.Path; public class EnumChecker implements FieldConstraintValueChecker { @Override public void checkConstraint(ConstraintValidator validator, FieldTreeNode fieldMetadata, Path fieldMetadataPath, FieldConstraint constraint, Path valuePath, JsonDoc doc, JsonNode fieldValue) { if (fieldValue != null && !(fieldValue instanceof NullNode)) { String name = ((EnumConstraint) constraint).getName(); Set<String> values = null; if (name != null) { // find value set for this enum Enum e = validator.getEntityMetadata().getEntityInfo().getEnums().getEnum(name); if (e != null) { values = e.getValues(); } } if (null == values || !values.contains(fieldValue.asText())) { validator.addDocError(Error.get(CrudConstants.ERR_INVALID_ENUM, fieldValue.asText())); } } } }
gpl-3.0
erh3cq/hyperspy
hyperspy/samfire_utils/strategy.py
18093
# -*- coding: utf-8 -*- # Copyright 2007-2021 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # HyperSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HyperSpy. If not, see <http://www.gnu.org/licenses/>. import numpy as np def make_sure_ind(inds, req_len=None): """Given an object, constructs a tuple of floats the required length. Either removes items that cannot be cast as floats, or adds the last valid item until the required length is reached. Parameters ---------- inds : sequence the sequence to be constructed into tuple of floats req_len : {None, number} The required length of the output Returns ------- indices : tuple of floats """ try: number = len(inds) # for error catching val = () for i in inds: try: val = val + (float(i),) except TypeError: pass number = len(val) except TypeError: val = (float(inds),) number = len(val) if req_len: if req_len < number: val = val[:req_len] else: val = val + tuple([val[-1] for _ in range(number, req_len)]) return val def nearest_indices(shape, ind, radii): """Returns the slices to slice a given size array to get the required size rectangle around the given index. Deals nicely with boundaries. Parameters ---------- shape : tuple the shape of the original (large) array ind : tuple the index of interest in the large array (centre) radii : tuple of floats the distances of interests in all dimensions around the centre index. Returns ------- slices : tuple of slices The slices to slice the large array to get the required region. center : tuple of ints The index of the original centre (ind) position in the new (sliced) array. """ par = () center = () for cent, i in enumerate(ind): top = min(i + radii[cent] + 1, shape[cent]) bot = max(0, i - radii[cent]) center = center + (int(i - bot),) par = par + (slice(int(bot), int(top)),) return par, center class SamfireStrategy(object): """A SAMFire strategy base class. """ samf = None close_plot = None name = "" def update(self, ind, isgood): """Updates the database and marker with the given pixel results Parameters ---------- ind : tuple the index with new results isgood : bool if the fit was successful. """ count = self.samf.count if isgood: self._update_marker(ind) self._update_database(ind, count) def __repr__(self): return self.name def remove(self): """Removes this strategy from its SAMFire """ self.samf.strategies.remove(self) class LocalStrategy(SamfireStrategy): """A SAMFire strategy that operates in "pixel space" - i.e calculates the starting point estimates based on the local averages of the pixels. Requires some weighting method (e.g. reduced chi-squared). """ _radii = None _radii_changed = True _untruncated = None _mask_all = None _weight = None _samf = None def __init__(self, name): self.name = name self.decay_function = lambda x: np.exp(-x) @property def samf(self): """The SAMFire that owns this strategy. """ return self._samf @samf.setter def samf(self, value): if value is not None and self.weight is not None: self._weight.model = value.model self._samf = value @property def weight(self): """A Weight object, able to assign significance weights to separate pixels or maps, given the model. """ return self._weight @weight.setter def weight(self, value): if self._weight is not None: self._weight.model = None self._weight = value if value is not None and self.samf is not None: value.model = self.samf.model def clean(self): """Purges the currently saved values. """ self._untruncated = None self._mask_all = None self._radii_changed = True @property def radii(self): """A tuple of >=0 floats that show the "radii of relevance" """ return self._radii @radii.setter def radii(self, value): m_sh = None if self.samf is not None: m_sh = len(self.samf.metadata.marker.shape) value = make_sure_ind(value, m_sh) if value != self._radii: self._radii_changed = True self._radii = value def _update_database(self, ind, count): """Dummy method for compatibility """ pass def refresh(self, overwrite, given_pixels=None): """Refreshes the marker - recalculates with the current values from scratch. Parameters ---------- overwrite : Bool If True, all but the given_pixels will be recalculated. Used when part of already calculated results has to be refreshed. If False, only use pixels with marker == -scale (by default -1) to propagate to pixels with marker >= 0. This allows "ignoring" pixels with marker < -scale (e.g. -2). given_pixels : boolean numpy array Pixels with True value are assumed as correctly calculated. """ marker = self.samf.metadata.marker shape = marker.shape scale = self.samf._scale if overwrite: if given_pixels is None: calc_pixels = marker < 0 else: calc_pixels = given_pixels todo_pixels = np.logical_not(calc_pixels) else: calc_pixels = marker == -scale todo_pixels = marker >= 0 if given_pixels is not None: calc_pixels = np.logical_and(calc_pixels, given_pixels) todo_pixels = np.logical_or( todo_pixels, np.logical_xor( marker == - scale, calc_pixels)) done_number = np.sum(calc_pixels) todo_number = np.sum(todo_pixels) marker[todo_pixels] = 0. marker[calc_pixels] = -scale weights_all = self.decay_function(self.weight.map(calc_pixels)) if done_number <= todo_number: # most efficient to propagate FROM fitted pixels ind_list = np.where(calc_pixels) for iindex in range(ind_list[0].size): ind = [one_list[iindex] for one_list in ind_list] distances, slices, _, mask = self._get_distance_array( shape, ind) mask = np.logical_and(mask, todo_pixels[slices]) weight = weights_all[tuple(ind)] distance_f = self.decay_function(distances) marker[slices][mask] += weight * distance_f[mask] else: # most efficient to propagate TO unknown pixels ind_list = np.where(todo_pixels) for iindex in range(ind_list[0].size): ind = [one_list[iindex] for one_list in ind_list] distances, slices, centre, mask = self._get_distance_array( shape, ind) mask = np.logical_and(mask, calc_pixels[slices]) weight = weights_all[slices] distance_f = self.decay_function(distances) marker[tuple(ind)] = np.sum(weight[mask] * distance_f[mask]) def _get_distance_array(self, shape, ind): """Calculatex the array of distances (withing radii) from the given pixel. Deals with borders well. Parameters ---------- shape : tuple the shape of the original array ind : tuple the index to calculate the distances from Returns ------- ans : numpy array the array of distances slices : tuple of slices slices to slice the original marker to get the correct part of the array centre : tuple the centre index in the sliced array mask : boolean numpy array a binary mask for the values to consider """ radii = make_sure_ind(self.radii, len(ind)) # This should be unnecessary....................... if self._untruncated is not None and self._untruncated.ndim != len( ind): self._untruncated = None self._mask_all = None if self._radii_changed or \ self._untruncated is None or \ self._mask_all is None: par = [] for radius in radii: radius_top = np.ceil(radius) par.append(np.abs(np.arange(-radius_top, radius_top + 1))) meshg = np.array(np.meshgrid(*par, indexing='ij')) self._untruncated = np.sqrt(np.sum(meshg ** 2.0, axis=0)) distance_mask = np.array( [c / float(radii[i]) for i, c in enumerate(meshg)]) self._mask_all = np.sum(distance_mask ** 2.0, axis=0) self._radii_changed = False slices_return, centre = nearest_indices(shape, ind, np.ceil(radii)) slices_temp = () for radius, cent, _slice in zip(np.ceil(radii), centre, slices_return): slices_temp += (slice(int(radius - cent), int(_slice.stop - _slice.start + radius - cent)),) ans = self._untruncated[slices_temp].copy() mask = self._mask_all[slices_temp].copy() # don't give values outside the radius - less prone to mistakes ans[mask > 1.0] = np.nan mask_to_send = mask <= 1.0 # within radius # don't want to add anything to the pixel itself mask_to_send[centre] = False return ans, slices_return, centre, mask_to_send def _update_marker(self, ind): """Updates the marker with the spatially decaying envelope around calculated pixels. Parameters ---------- ind : tuple the index of the pixel to "spread" the envelope around. """ marker = self.samf.metadata.marker shape = marker.shape distances, slices, _, mask = self._get_distance_array(shape, ind) mask = np.logical_and(mask, marker[slices] >= 0) weight = self.decay_function(self.weight.function(ind)) distance_f = self.decay_function(distances) marker[slices][mask] += weight * distance_f[mask] scale = self.samf._scale for i in self.samf.running_pixels: marker[i] = 0 marker[ind] = -scale def values(self, ind): """Returns the current starting value estimates for the given pixel. Calculated as the weighted local average. Only returns components that are active, and parameters that are free. Parameters ---------- ind : tuple the index of the pixel of interest. Returns ------- values : dict A dictionary of estimates, structured as {component_name: {parameter_name: value, ...}, ...} for active components and free parameters. """ marker = self.samf.metadata.marker shape = marker.shape model = self.samf.model distances, slices, _, mask_dist = self._get_distance_array( shape, ind) # only use pixels that are calculated and "active" mask_dist_calc = np.logical_and( mask_dist, marker[slices] == - self.samf._scale) distance_f = self.decay_function(distances) weights_values = self.decay_function( self.weight.map( mask_dist_calc, slices)) ans = {} for component in model: if component.active_is_multidimensional: mask = np.logical_and( component._active_array[slices], mask_dist_calc) else: if component.active: mask = mask_dist_calc else: # not multidim and not active, skip continue comp_dict = {} weight = distance_f[mask] * weights_values[mask] if weight.size: # should never happen that np.sum(weight) == 0 for par in component.parameters: if par.free: comp_dict[par.name] = np.average( par.map[slices][mask]['values'], weights=weight, axis=0) ans[component.name] = comp_dict return ans def plot(self, fig=None): """Plots the current marker in a flat image Parameters ---------- fig : {Image, None} if an already plotted image, then updates. Otherwise creates a new one. Returns ------- fig: Image the resulting image. If passed again, will be updated (computationally cheaper operation). """ marker = self.samf.metadata.marker.copy() if marker.ndim > 2: marker = np.sum( marker, tuple([i for i in range(0, marker.ndim - 2)])) elif marker.ndim < 2: marker = np.atleast_2d(marker) from hyperspy.signals import Signal2D if not isinstance( fig, Signal2D) or fig._plot.signal_plot.figure is None: fig = Signal2D(marker) fig.plot() self.close_plot = fig._plot.signal_plot.close else: fig.data = marker fig._plot.signal_plot.update() return fig class GlobalStrategy(SamfireStrategy): """A SAMFire strategy that operates in "parameter space" - i.e the pixel positions are not important, and only parameter value distributions are segmented to be used as starting point estimators. """ segmenter = None _saved_values = None def clean(self): """Purges the currently saved values (not the database). """ self._saved_values = None def __init__(self, name): self.name = name def refresh(self, overwrite, given_pixels=None): """Refreshes the database (i.e. constructs it again from scratch) """ scale = self.samf._scale mark = self.samf.metadata.marker mark = np.where(np.isnan(mark), np.inf, mark) if overwrite: if given_pixels is None: good_pixels = mark < 0 else: good_pixels = given_pixels self.samf.metadata.marker[good_pixels] = -scale else: good_pixels = mark < 0 if given_pixels is not None: good_pixels = np.logical_and(good_pixels, given_pixels) self.samf.metadata.marker[~good_pixels] = scale self._update_database(None, 0) # to force to update def _update_marker(self, ind): """Updates the SAMFire marker in the given pixel """ scale = self.samf._scale self.samf.metadata.marker[ind] = -scale def _package_values(self): """Packages he current values to be sent to the segmenter """ model = self.samf.model mask_calc = self.samf.metadata.marker < 0 ans = {} for component in model: if component.active_is_multidimensional: mask = np.logical_and(component._active_array, mask_calc) else: if component.active: mask = mask_calc else: # not multidim and not active, skip continue component_dict = {} for par in component.parameters: if par.free: # only keeps active values and ravels component_dict[par.name] = par.map[mask]['values'] ans[component.name] = component_dict return ans def _update_database(self, ind, count): """ Updates the database with current values """ if not count % self.samf.update_every: self._saved_values = None self.segmenter.update(self._package_values()) def values(self, ind=None): """Returns the saved most frequent values that should be used for prediction """ if self._saved_values is None: self._saved_values = self.segmenter.most_frequent() return self._saved_values def plot(self, fig=None): """Plots the current database of histograms Parameters ---------- fig: {None, HistogramTilePlot} If given updates the plot. """ from hyperspy.drawing.tiles import HistogramTilePlot kwargs = {'color': '#4C72B0'} dbase = self.segmenter.database if dbase is None or not len(dbase): return fig if not isinstance(fig, HistogramTilePlot): fig = HistogramTilePlot() fig.plot(dbase, **kwargs) self.close_plot = fig.close else: fig.update(dbase, **kwargs) return fig
gpl-3.0
webSPELL/webSPELL
install/languages/de/step1.php
2421
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = Array( 'agree'=>'Ich bin einverstanden', 'agree_not'=>'Ich bin nicht einverstanden', 'gpl_info'=>'Um diese webSPELL Version auf deinem Server zu installieren, musst du die<br /><a href="http://www.gnu.org/licenses/licenses.html" target="_blank">GNU GENERAL PUBLIC LICENCE</a> akzeptieren <small>(<a href="http://www.gnu.de/documents/gpl.de.html" target="_blank">inoffizielle deutsche Übersetzung</a>)</small>', 'licence'=>'Lizenzvereinbarung', 'more_info'=>'Du erhälst weitere Informationen auf der <a href="http://www.webspell.org/index.php?site=license" target="_blank">webSPELL Seite</a>', 'please_select'=>'Bitte auswählen', 'version'=>'Version' ); ?>
gpl-3.0
tk8226/YamiPortAIO-v2
Core/Champion Ports/Ekko/TheEkko/Commons/ComboSystem/Skill.cs
8896
using System; using LeagueSharp; using LeagueSharp.Common; using EloBuddy; using LeagueSharp.Common; namespace TheEkko.ComboSystem { abstract class Skill : IComparable<Skill> { public bool ComboEnabled = true, LaneclearEnabled = false, HarassEnabled = false; // If this skill should be used in Combo, ... private float _castTime; private string _castName; private Spell _castSpell; protected const float SafeCastMaxTime = 0.5f; public Spell Spell { get; private set; } protected ComboProvider Provider { get; private set; } protected IMainContext Context { get; private set; } protected bool UseManaManager = true; public bool SwitchClearToHarassOnTarget = true; protected Skill(Spell spell) { Spell = spell; UseManaManager = spell.Instance.SData.ManaCostArray.MaxOrDefault((value) => value) > 0; //Console.WriteLine(spell.Instance.SData.ManaCostArray.MaxOrDefault((value) => value) + " MAX VALUE"); } /// <summary> /// The safe cast mechanism is used to set a skill "on cooldown" even though the server hasn't even sent the cooldown update. /// Results in less ability spam, (faster execution ?) and it's easier to debug /// </summary> protected bool SafeCast(Action spellCastAction, string name = "") { if (string.IsNullOrEmpty(name)) name = Spell.Instance.Name; if (HasBeenSafeCast(name)) return false; _castTime = Game.Time; _castName = name; _castSpell = Spell; spellCastAction(); return true; } /// <summary> /// The safe cast mechanism is used to set a skill "on cooldown" even though the server hasn't even sent the cooldown update. /// Results in less ability spam, (faster execution ?) and it's easier to debug /// </summary> protected bool SafeCast(Spell spell, Action spellCastAction, string name = "") { if (string.IsNullOrEmpty(name)) name = spell.Instance.Name; if (HasBeenSafeCast(name)) return false; _castTime = Game.Time; _castName = name; _castSpell = spell; spellCastAction(); return true; } /// <summary> /// Add Initialisation logic in sub class. Called by ComboProvider.SetActive(skill) /// </summary> /// <param name="combo"></param> public virtual void Initialize(IMainContext context, ComboProvider combo) { Provider = combo; Context = context; } public virtual void SetEnabled(Orbwalking.OrbwalkingMode mode, bool enabled) { //Console.WriteLine(GetType().Name+": "+mode+" enabled: "+enabled); switch (mode) { case Orbwalking.OrbwalkingMode.Combo: ComboEnabled = enabled; break; case Orbwalking.OrbwalkingMode.LaneClear: LaneclearEnabled = enabled; break; case Orbwalking.OrbwalkingMode.Mixed: HarassEnabled = enabled; break; } } public bool GetEnabled(Orbwalking.OrbwalkingMode mode) { switch (mode) { case Orbwalking.OrbwalkingMode.Combo: return ComboEnabled; case Orbwalking.OrbwalkingMode.LaneClear: return LaneclearEnabled; case Orbwalking.OrbwalkingMode.Mixed: return HarassEnabled; } return false; } public virtual void Update(Orbwalking.OrbwalkingMode mode, IMainContext context, ComboProvider combo, AIHeroClient target) { if (mode == Orbwalking.OrbwalkingMode.None) return; if (mode == Orbwalking.OrbwalkingMode.LaneClear && SwitchClearToHarassOnTarget && target != null && HarassEnabled) mode = Orbwalking.OrbwalkingMode.Mixed; if (UseManaManager && !ManaManager.CanUseMana(mode)) return; switch (mode) { case Orbwalking.OrbwalkingMode.Combo: if (ComboEnabled) Combo(context, combo, target); break; case Orbwalking.OrbwalkingMode.LaneClear: if (LaneclearEnabled) LaneClear(context, combo, target); break; case Orbwalking.OrbwalkingMode.Mixed: if (HarassEnabled) Harass(context, combo, target); break; } } public abstract void Cast(AIHeroClient target, bool force = false, HitChance minChance = HitChance.Low); public virtual void Combo(IMainContext context, ComboProvider combo, AIHeroClient target) { Cast(target); } public virtual void LaneClear(IMainContext context, ComboProvider combo, AIHeroClient target) { } public virtual void Harass(IMainContext context, ComboProvider combo, AIHeroClient target) { Cast(target); } public virtual void Gapcloser(IMainContext context, ComboProvider combo, ActiveGapcloser gapcloser) { } public virtual void Interruptable(IMainContext context, ComboProvider combo, AIHeroClient sender, ComboProvider.InterruptableSpell interruptableSpell) { } public virtual float GetDamage(AIHeroClient enemy) { return Spell.Instance.State == SpellState.Ready ? (float)ObjectManager.Player.GetSpellDamage(enemy, Spell.Slot) : 0f; } /// <summary> /// If this returns true an other skill of the same or lower priority can't grab control. If this skill /// has control but this return false, the control will be terminated. /// </summary> /// <returns></returns> public virtual bool NeedsControl() { return false; } public abstract int GetPriority(); /// <summary> /// Gets called if some other skill wants total control OR this skill doesn't need control even though it has it. /// </summary> /// <returns></returns> public virtual bool TryTerminate(IMainContext context) { return true; } /// <summary> /// If the spell seems available. SafeCast compatible /// </summary> /// <returns></returns> public virtual bool CanBeCast() { return Spell.Instance.State == SpellState.Ready && !HasBeenSafeCast(); } /// <summary> /// If the spell as been cast. SafeCast compatible /// </summary> /// <param name="name"></param> /// <returns></returns> public bool HasBeenSafeCast(string name) { //Todo: I think this is nidalee/elise/jayce incompatible return (_castName == name && Game.Time - _castTime < SafeCastMaxTime) || (Spell.Instance.State != SpellState.Ready) || (_castSpell != null && Spell.Instance.Name != _castName); //bug: != ready was == cooldown, had to change cuz bug ... same with method below, and removed _castSpell != null && check before that } /// <summary> /// If the spell as been cast. SafeCast compatible /// </summary> /// <param name="name"></param> /// <returns></returns> public bool HasBeenSafeCast() { //Todo: I think this is nidalee/elise/jayce incompatible return (_castName == Spell.Instance.Name && Game.Time - _castTime < SafeCastMaxTime) || (Spell.Instance.State != SpellState.Ready) || (_castSpell != null && Spell.Instance.Name != _castName); } /// <summary> /// If the spell as been cast. SafeCast compatible /// </summary> /// <param name="name"></param> /// <param name="castTime"></param> /// <returns></returns> public bool IsInSafeCast(string name, float castTime = SafeCastMaxTime) { return (!string.IsNullOrEmpty(_castName) && _castName != name) || Game.Time - _castTime < castTime; } /// <summary> /// If the spell as been cast. SafeCast compatible /// </summary> /// <param name="name"></param> /// <param name="castTime"></param> /// <returns></returns> public bool IsInSafeCast(float castTime = SafeCastMaxTime) { return Game.Time - _castTime < castTime; } public int CompareTo(Skill obj) { return obj.GetPriority() - GetPriority(); } } }
gpl-3.0
splintor/tdesktop
Telegram/SourceFiles/pspecific_linux.cpp
19464
/* This file is part of Telegram Desktop, the official desktop version of Telegram messaging app, see https://telegram.org Telegram Desktop is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2016 John Preston, https://desktop.telegram.org */ #include "stdafx.h" #include "pspecific.h" #include "platform/linux/linux_libs.h" #include "lang.h" #include "application.h" #include "mainwidget.h" #include "localstorage.h" #include <sys/stat.h> #include <sys/types.h> #include <cstdlib> #include <unistd.h> #include <dirent.h> #include <pwd.h> #include <iostream> using namespace Platform; namespace { QByteArray escapeShell(const QByteArray &str) { QByteArray result; const char *b = str.constData(), *e = str.constEnd(); for (const char *ch = b; ch != e; ++ch) { if (*ch == ' ' || *ch == '"' || *ch == '\'' || *ch == '\\') { if (result.isEmpty()) { result.reserve(str.size() * 2); } if (ch > b) { result.append(b, ch - b); } result.append('\\'); b = ch; } } if (result.isEmpty()) return str; if (e > b) { result.append(b, e - b); } return result; } class _PsEventFilter : public QAbstractNativeEventFilter { public: _PsEventFilter() { } bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) { auto wnd = App::wnd(); if (!wnd) return false; return false; } }; _PsEventFilter *_psEventFilter = 0; }; namespace { QRect _monitorRect; uint64 _monitorLastGot = 0; } QRect psDesktopRect() { uint64 tnow = getms(); if (tnow > _monitorLastGot + 1000 || tnow < _monitorLastGot) { _monitorLastGot = tnow; _monitorRect = QApplication::desktop()->availableGeometry(App::wnd()); } return _monitorRect; } void psShowOverAll(QWidget *w, bool canFocus) { w->show(); } void psBringToBack(QWidget *w) { w->hide(); } QAbstractNativeEventFilter *psNativeEventFilter() { delete _psEventFilter; _psEventFilter = new _PsEventFilter(); return _psEventFilter; } void psWriteDump() { } QString demanglestr(const QString &mangled) { if (mangled.isEmpty()) return mangled; QByteArray cmd = ("c++filt -n " + mangled).toUtf8(); FILE *f = popen(cmd.constData(), "r"); if (!f) return "BAD_SYMBOL_" + mangled; QString result; char buffer[4096] = { 0 }; while (!feof(f)) { if (fgets(buffer, 4096, f) != NULL) { result += buffer; } } pclose(f); return result.trimmed(); } QStringList addr2linestr(uint64 *addresses, int count) { QStringList result; if (!count) return result; result.reserve(count); QByteArray cmd = "addr2line -e " + escapeShell(QFile::encodeName(cExeDir() + cExeName())); for (int i = 0; i < count; ++i) { if (addresses[i]) { cmd += qsl(" 0x%1").arg(addresses[i], 0, 16).toUtf8(); } } FILE *f = popen(cmd.constData(), "r"); QStringList addr2lineResult; if (f) { char buffer[4096] = {0}; while (!feof(f)) { if (fgets(buffer, 4096, f) != NULL) { addr2lineResult.push_back(QString::fromUtf8(buffer)); } } pclose(f); } for (int i = 0, j = 0; i < count; ++i) { if (addresses[i]) { if (j < addr2lineResult.size() && !addr2lineResult.at(j).isEmpty() && !addr2lineResult.at(j).startsWith(qstr("0x"))) { QString res = addr2lineResult.at(j).trimmed(); if (int index = res.indexOf(qstr("/Telegram/"))) { if (index > 0) { res = res.mid(index + qstr("/Telegram/").size()); } } result.push_back(res); } else { result.push_back(QString()); } ++j; } else { result.push_back(QString()); } } return result; } QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { QString initial = QString::fromUtf8(crashdump), result; QStringList lines = initial.split('\n'); result.reserve(initial.size()); int32 i = 0, l = lines.size(); while (i < l) { uint64 addresses[1024] = { 0 }; for (; i < l; ++i) { result.append(lines.at(i)).append('\n'); QString line = lines.at(i).trimmed(); if (line == qstr("Backtrace:")) { ++i; break; } } int32 start = i; for (; i < l; ++i) { QString line = lines.at(i).trimmed(); if (line.isEmpty()) break; QRegularExpressionMatch m1 = QRegularExpression(qsl("^(.+)\\(([^+]+)\\+([^\\)]+)\\)\\[(.+)\\]$")).match(line); QRegularExpressionMatch m2 = QRegularExpression(qsl("^(.+)\\[(.+)\\]$")).match(line); QString addrstr = m1.hasMatch() ? m1.captured(4) : (m2.hasMatch() ? m2.captured(2) : QString()); if (!addrstr.isEmpty()) { uint64 addr = addrstr.startsWith(qstr("0x")) ? addrstr.mid(2).toULongLong(0, 16) : addrstr.toULongLong(); if (addr > 1) { addresses[i - start] = addr; } } } QStringList addr2line = addr2linestr(addresses, i - start); for (i = start; i < l; ++i) { QString line = lines.at(i).trimmed(); if (line.isEmpty()) break; result.append(qsl("\n%1. ").arg(i - start)); if (line.startsWith(qstr("ERROR: "))) { result.append(line).append('\n'); continue; } if (line == qstr("[0x1]")) { result.append(qsl("(0x1 separator)\n")); continue; } QRegularExpressionMatch m1 = QRegularExpression(qsl("^(.+)\\(([^+]*)\\+([^\\)]+)\\)(.+)$")).match(line); QRegularExpressionMatch m2 = QRegularExpression(qsl("^(.+)\\[(.+)\\]$")).match(line); if (!m1.hasMatch() && !m2.hasMatch()) { result.append(qstr("BAD LINE: ")).append(line).append('\n'); continue; } if (m1.hasMatch()) { result.append(demanglestr(m1.captured(2))).append(qsl(" + ")).append(m1.captured(3)).append(qsl(" [")).append(m1.captured(1)).append(qsl("] ")); if (!addr2line.at(i - start).isEmpty() && addr2line.at(i - start) != qsl("??:0")) { result.append(qsl(" (")).append(addr2line.at(i - start)).append(qsl(")\n")); } else { result.append(m1.captured(4)).append(qsl(" (demangled)")).append('\n'); } } else { result.append('[').append(m2.captured(1)).append(']'); if (!addr2line.at(i - start).isEmpty() && addr2line.at(i - start) != qsl("??:0")) { result.append(qsl(" (")).append(addr2line.at(i - start)).append(qsl(")\n")); } else { result.append(' ').append(m2.captured(2)).append('\n'); } } } } return result; } bool _removeDirectory(const QString &path) { // from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c QByteArray pathRaw = QFile::encodeName(path); DIR *d = opendir(pathRaw.constData()); if (!d) return false; while (struct dirent *p = readdir(d)) { /* Skip the names "." and ".." as we don't want to recurse on them. */ if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue; QString fname = path + '/' + p->d_name; QByteArray fnameRaw = QFile::encodeName(fname); struct stat statbuf; if (!stat(fnameRaw.constData(), &statbuf)) { if (S_ISDIR(statbuf.st_mode)) { if (!_removeDirectory(fname)) { closedir(d); return false; } } else { if (unlink(fnameRaw.constData())) { closedir(d); return false; } } } } closedir(d); return !rmdir(pathRaw.constData()); } void psDeleteDir(const QString &dir) { _removeDirectory(dir); } namespace { uint64 _lastUserAction = 0; } void psUserActionDone() { _lastUserAction = getms(true); } bool psIdleSupported() { return false; } uint64 psIdleTime() { return getms(true) - _lastUserAction; } bool psSkipAudioNotify() { return false; } bool psSkipDesktopNotify() { return false; } void psActivateProcess(uint64 pid) { // objc_activateProgram(); } QString psCurrentCountry() { QString country;// = objc_currentCountry(); return country.isEmpty() ? QString::fromLatin1(DefaultCountry) : country; } QString psCurrentLanguage() { QString lng;// = objc_currentLang(); return lng.isEmpty() ? QString::fromLatin1(DefaultLanguage) : lng; } namespace { QString _psHomeDir() { struct passwd *pw = getpwuid(getuid()); return (pw && pw->pw_dir && strlen(pw->pw_dir)) ? (QFile::decodeName(pw->pw_dir) + '/') : QString(); } } QString psAppDataPath() { QString home(_psHomeDir()); return home.isEmpty() ? QString() : (home + qsl(".TelegramDesktop/")); } QString psDownloadPath() { return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + '/' + str_const_toString(AppName) + '/'; } QString psCurrentExeDirectory(int argc, char *argv[]) { QString first = argc ? QFile::decodeName(argv[0]) : QString(); if (!first.isEmpty()) { QFileInfo info(first); if (info.isSymLink()) { info = info.symLinkTarget(); } if (info.exists()) { return QDir(info.absolutePath()).absolutePath() + '/'; } } return QString(); } QString psCurrentExeName(int argc, char *argv[]) { QString first = argc ? QFile::decodeName(argv[0]) : QString(); if (!first.isEmpty()) { QFileInfo info(first); if (info.isSymLink()) { info = info.symLinkTarget(); } if (info.exists()) { return info.fileName(); } } return QString(); } void psDoCleanup() { try { psAutoStart(false, true); psSendToMenu(false, true); } catch (...) { } } int psCleanup() { psDoCleanup(); return 0; } void psDoFixPrevious() { } int psFixPrevious() { psDoFixPrevious(); return 0; } void psPostprocessFile(const QString &name) { } void psOpenFile(const QString &name, bool openWith) { QDesktopServices::openUrl(QUrl::fromLocalFile(name)); } void psShowInFolder(const QString &name) { Ui::hideLayer(true); system(("xdg-open " + escapeShell(QFile::encodeName(QFileInfo(name).absoluteDir().absolutePath()))).constData()); } namespace Platform { void start() { } void finish() { delete _psEventFilter; _psEventFilter = nullptr; } namespace ThirdParty { void start() { Libs::start(); MainWindow::LibsLoaded(); } void finish() { } } // namespace ThirdParty } // namespace Platform namespace { bool _psRunCommand(const QByteArray &command) { int result = system(command.constData()); if (result) { DEBUG_LOG(("App Error: command failed, code: %1, command (in utf8): %2").arg(result).arg(command.constData())); return false; } DEBUG_LOG(("App Info: command succeeded, command (in utf8): %1").arg(command.constData())); return true; } } void psRegisterCustomScheme() { #ifndef TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME QString home(_psHomeDir()); if (home.isEmpty() || cBetaVersion()) return; // don't update desktop file for beta version #ifndef TDESKTOP_DISABLE_DESKTOP_FILE_GENERATION DEBUG_LOG(("App Info: placing .desktop file")); if (QDir(home + qsl(".local/")).exists()) { QString apps = home + qsl(".local/share/applications/"); QString icons = home + qsl(".local/share/icons/"); if (!QDir(apps).exists()) QDir().mkpath(apps); if (!QDir(icons).exists()) QDir().mkpath(icons); QString path = cWorkingDir() + qsl("tdata/"), file = path + qsl("telegramdesktop.desktop"); QDir().mkpath(path); QFile f(file); if (f.open(QIODevice::WriteOnly)) { QString icon = icons + qsl("telegram.png"); if (!QFile(icon).exists()) { if (QFile(qsl(":/gui/art/icon256.png")).copy(icon)) { DEBUG_LOG(("App Info: Icon copied to 'tdata'")); } } QTextStream s(&f); s.setCodec("UTF-8"); s << "[Desktop Entry]\n"; s << "Encoding=UTF-8\n"; s << "Version=1.0\n"; s << "Name=Telegram Desktop\n"; s << "Comment=Official desktop version of Telegram messaging app\n"; s << "Exec=" << escapeShell(QFile::encodeName(cExeDir() + cExeName())) << " -- %u\n"; s << "Icon=telegram\n"; s << "Terminal=false\n"; s << "StartupWMClass=Telegram\n"; s << "Type=Application\n"; s << "Categories=Network;\n"; s << "MimeType=x-scheme-handler/tg;\n"; f.close(); if (_psRunCommand("desktop-file-install --dir=" + escapeShell(QFile::encodeName(home + qsl(".local/share/applications"))) + " --delete-original " + escapeShell(QFile::encodeName(file)))) { DEBUG_LOG(("App Info: removing old .desktop file")); QFile(qsl("%1.local/share/applications/telegram.desktop").arg(home)).remove(); _psRunCommand("update-desktop-database " + escapeShell(QFile::encodeName(home + qsl(".local/share/applications")))); _psRunCommand("xdg-mime default telegramdesktop.desktop x-scheme-handler/tg"); } } else { LOG(("App Error: Could not open '%1' for write").arg(file)); } } #endif // TDESKTOP_DISABLE_DESKTOP_FILE_GENERATION DEBUG_LOG(("App Info: registerting for Gnome")); if (_psRunCommand("gconftool-2 -t string -s /desktop/gnome/url-handlers/tg/command " + escapeShell(escapeShell(QFile::encodeName(cExeDir() + cExeName())) + " -- %s"))) { _psRunCommand("gconftool-2 -t bool -s /desktop/gnome/url-handlers/tg/needs_terminal false"); _psRunCommand("gconftool-2 -t bool -s /desktop/gnome/url-handlers/tg/enabled true"); } DEBUG_LOG(("App Info: placing .protocol file")); QString services; if (QDir(home + qsl(".kde4/")).exists()) { services = home + qsl(".kde4/share/kde4/services/"); } else if (QDir(home + qsl(".kde/")).exists()) { services = home + qsl(".kde/share/kde4/services/"); } if (!services.isEmpty()) { if (!QDir(services).exists()) QDir().mkpath(services); QString path = services, file = path + qsl("tg.protocol"); QFile f(file); if (f.open(QIODevice::WriteOnly)) { QTextStream s(&f); s.setCodec("UTF-8"); s << "[Protocol]\n"; s << "exec=" << QFile::decodeName(escapeShell(QFile::encodeName(cExeDir() + cExeName()))) << " -- %u\n"; s << "protocol=tg\n"; s << "input=none\n"; s << "output=none\n"; s << "helper=true\n"; s << "listing=false\n"; s << "reading=false\n"; s << "writing=false\n"; s << "makedir=false\n"; s << "deleting=false\n"; f.close(); } else { LOG(("App Error: Could not open '%1' for write").arg(file)); } } #endif } void psNewVersion() { psRegisterCustomScheme(); } bool _execUpdater(bool update = true, const QString &crashreport = QString()) { static const int MaxLen = 65536, MaxArgsCount = 128; char path[MaxLen] = {0}; QByteArray data(QFile::encodeName(cExeDir() + "Updater")); memcpy(path, data.constData(), data.size()); char *args[MaxArgsCount] = {0}, p_noupdate[] = "-noupdate", p_autostart[] = "-autostart", p_debug[] = "-debug", p_tosettings[] = "-tosettings", p_key[] = "-key", p_path[] = "-workpath", p_startintray[] = "-startintray", p_testmode[] = "-testmode", p_crashreport[] = "-crashreport"; char p_datafile[MaxLen] = {0}, p_pathbuf[MaxLen] = {0}, p_crashreportbuf[MaxLen] = {0}; int argIndex = 0; args[argIndex++] = path; if (!update) { args[argIndex++] = p_noupdate; args[argIndex++] = p_tosettings; } if (cLaunchMode() == LaunchModeAutoStart) args[argIndex++] = p_autostart; if (cDebug()) args[argIndex++] = p_debug; if (cStartInTray()) args[argIndex++] = p_startintray; if (cTestMode()) args[argIndex++] = p_testmode; if (cDataFile() != qsl("data")) { QByteArray dataf = QFile::encodeName(cDataFile()); if (dataf.size() < MaxLen) { memcpy(p_datafile, dataf.constData(), dataf.size()); args[argIndex++] = p_key; args[argIndex++] = p_datafile; } } QByteArray pathf = QFile::encodeName(cWorkingDir()); if (pathf.size() < MaxLen) { memcpy(p_pathbuf, pathf.constData(), pathf.size()); args[argIndex++] = p_path; args[argIndex++] = p_pathbuf; } if (!crashreport.isEmpty()) { QByteArray crashreportf = QFile::encodeName(crashreport); if (crashreportf.size() < MaxLen) { memcpy(p_crashreportbuf, crashreportf.constData(), crashreportf.size()); args[argIndex++] = p_crashreport; args[argIndex++] = p_crashreportbuf; } } Logs::closeMain(); SignalHandlers::finish(); pid_t pid = fork(); switch (pid) { case -1: return false; case 0: execv(path, args); return false; } return true; } void psExecUpdater() { if (!_execUpdater()) { psDeleteDir(cWorkingDir() + qsl("tupdates/temp")); } } void psExecTelegram(const QString &crashreport) { _execUpdater(false, crashreport); } bool psShowOpenWithMenu(int x, int y, const QString &file) { return false; } void psAutoStart(bool start, bool silent) { } void psSendToMenu(bool send, bool silent) { } void psUpdateOverlayed(QWidget *widget) { } bool linuxMoveFile(const char *from, const char *to) { FILE *ffrom = fopen(from, "rb"), *fto = fopen(to, "wb"); if (!ffrom) { if (fto) fclose(fto); return false; } if (!fto) { fclose(ffrom); return false; } static const int BufSize = 65536; char buf[BufSize]; while (size_t size = fread(buf, 1, BufSize, ffrom)) { fwrite(buf, 1, size, fto); } struct stat fst; // from http://stackoverflow.com/questions/5486774/keeping-fileowner-and-permissions-after-copying-file-in-c //let's say this wont fail since you already worked OK on that fp if (fstat(fileno(ffrom), &fst) != 0) { fclose(ffrom); fclose(fto); return false; } //update to the same uid/gid if (fchown(fileno(fto), fst.st_uid, fst.st_gid) != 0) { fclose(ffrom); fclose(fto); return false; } //update the permissions if (fchmod(fileno(fto), fst.st_mode) != 0) { fclose(ffrom); fclose(fto); return false; } fclose(ffrom); fclose(fto); if (unlink(from)) { return false; } return true; } bool psLaunchMaps(const LocationCoords &coords) { return false; }
gpl-3.0
gregrgay/booking
lib/Application/Reservation/Validation/ReservationRuleResult.php
1179
<?php /** Copyright 2011-2013 Nick Korbel This file is part of phpScheduleIt. phpScheduleIt is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. phpScheduleIt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with phpScheduleIt. If not, see <http://www.gnu.org/licenses/>. */ class ReservationRuleResult { private $_isValid; private $_errorMessage; /** * @param bool $isValid * @param string $errorMessage */ public function __construct($isValid = true, $errorMessage = null) { $this->_isValid = $isValid; $this->_errorMessage = $errorMessage; } /** * @return bool */ public function IsValid() { return $this->_isValid; } /** * @return string */ public function ErrorMessage() { return $this->_errorMessage; } } ?>
gpl-3.0
vanoudt/jethro-pmm
calls/call_service_comp_detail.class.php
671
<?php class Call_Service_Comp_Detail extends Call { function run() { $GLOBALS['system']->initErrorHandler(); $comp = $GLOBALS['system']->getDBObject('service_component', (int)$_REQUEST['id']); if ($comp) { if (!empty($_REQUEST['head'])) { ?> <html> <head> <title>Jethro PMM - Service Component Detail</title> <?php include 'templates/head.template.php'; ?> </head> <body> <div id="body"> <?php } include 'templates/service_component_detail.template.php'; if (!empty($_REQUEST['head'])) { ?> </div> </body> </html> <?php } } else { echo 'Component not found'; } } } ?>
gpl-3.0
dmlond/duke-data-service
spec/serializers/affiliation_serializer_spec.rb
618
require 'rails_helper' RSpec.describe AffiliationSerializer, type: :serializer do let(:resource) { FactoryBot.build(:affiliation) } let(:expected_attributes) {{ 'user' => { 'id' => resource.user.id, 'full_name' => resource.user.display_name, 'email' => resource.user.email } }} it_behaves_like 'a has_one association with', :project, ProjectPreviewSerializer it_behaves_like 'a has_one association with', :project_role, ProjectRolePreviewSerializer it_behaves_like 'a json serializer' do it { is_expected.to include(expected_attributes) } end end
gpl-3.0
amazinger2013/OpenSesame
extensions/automatic_backup/automatic_backup.py
3572
#-*- coding:utf-8 -*- """ This file is part of OpenSesame. OpenSesame is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenSesame is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenSesame. If not, see <http://www.gnu.org/licenses/>. """ import os import time from PyQt4 import QtGui, QtCore from libopensesame import debug, misc from libqtopensesame.misc import _ from libqtopensesame.extensions import base_extension from libqtopensesame.misc.config import cfg class automatic_backup(base_extension): """ desc: An extension that periodically saves the experiment. """ def activate(self): """ desc: Opens the autosave folder. """ if os.name == u"nt": os.startfile(self.autosave_folder) elif os.name == u"posix": misc.open_url(self.autosave_folder) def event_startup(self): """ desc: Initializes the extension on OpenSesame startup. """ # Create the autosave folder if it doesn't exist yet if not os.path.exists(os.path.join(self.main_window.home_folder, u".opensesame", u"backup")): os.mkdir(os.path.join(self.main_window.home_folder, u".opensesame", u"backup")) self.autosave_folder = os.path.join(self.main_window.home_folder, u".opensesame", u"backup") # Remove expired backups for path in os.listdir(self.autosave_folder): _path = os.path.join(self.autosave_folder, path) t = os.path.getctime(_path) age = (time.time() - t)/(60*60*24) if age > cfg.autosave_max_age: debug.msg(u"removing '%s'" % path) try: os.remove(_path) except: debug.msg(u"failed to remove '%s'" % path) self.start_autosave_timer() def event_run_experiment(self, fullscreen): """ desc: Suspend autosave timer when the experiment starts. """ if self.autosave_timer != None: debug.msg(u"stopping autosave timer") self.autosave_timer.stop() def event_end_experiment(self): """ desc: Resume autosave timer when the experiment ends. """ if self.autosave_timer != None: debug.msg(u"resuming autosave timer") self.autosave_timer.start() def start_autosave_timer(self): """ desc: Starts the autosave timer. """ if cfg.autosave_interval > 0: debug.msg(u"autosave interval = %d ms" % cfg.autosave_interval) self.autosave_timer = QtCore.QTimer() self.autosave_timer.setInterval(cfg.autosave_interval) self.autosave_timer.setSingleShot(True) self.autosave_timer.timeout.connect(self.autosave) self.autosave_timer.start() else: debug.msg(u"autosave disabled") self.autosave_timer = None def autosave(self): """ desc: Autosave the experiment if there are unsaved changes. """ if not self.main_window.unsaved_changes: self.set_status(u'No unsaved changes, skipping backup') autosave_path = u'' else: path = os.path.join(self.autosave_folder, u'%s.opensesame.tar.gz'% unicode(time.ctime()).replace(u':', u'_')) try: self.main_window.get_ready() self.experiment.save(path, overwrite=True, update_path=False) debug.msg(u"saving backup as %s" % path) except: self.set_status(_(u'Failed to save backup ...')) self.start_autosave_timer()
gpl-3.0
eschwert/DL-Learner
components-core/src/main/java/org/dllearner/algorithms/ocel/SubsumptionComparator.java
1827
/** * Copyright (C) 2007-2011, Jens Lehmann * * This file is part of DL-Learner. * * DL-Learner is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * DL-Learner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.dllearner.algorithms.ocel; import java.util.Comparator; import org.dllearner.core.AbstractReasonerComponent; import org.semanticweb.owlapi.model.OWLClassExpression; public class SubsumptionComparator implements Comparator<OWLClassExpression> { private AbstractReasonerComponent rs; public SubsumptionComparator(AbstractReasonerComponent rs) { this.rs = rs; } public int compare(ExampleBasedNode arg0, ExampleBasedNode arg1) { OWLClassExpression concept1 = arg0.getConcept(); OWLClassExpression concept2 = arg1.getConcept(); return compare(concept1, concept2); } public int compare(OWLClassExpression concept1, OWLClassExpression concept2) { // return true if concept1 is a super concept of concept2 boolean value1 = rs.isSuperClassOf(concept1, concept2); if(value1) return 1; boolean value2 = rs.isSuperClassOf(concept2, concept1); if(value2) return -1; // System.out.println("Incomparable: " + concept1 + " " + concept2); // both concepts are incomparable => order them syntactically return concept1.compareTo(concept2); } }
gpl-3.0
Elektro1776/latestEarthables
core/client/tmp/broccoli_persistent_filterbabel-output_path-1H0a5glP.tmp/ghost-admin/tests/unit/helpers/is-not-test.js
493
define('ghost-admin/tests/unit/helpers/is-not-test', ['exports', 'chai', 'mocha', 'ghost-admin/helpers/is-not'], function (exports, _chai, _mocha, _ghostAdminHelpersIsNot) { (0, _mocha.describe)('Unit: Helper: is-not', function () { // Replace this with your real tests. (0, _mocha.it)('works', function () { var result = (0, _ghostAdminHelpersIsNot.isNot)(false); (0, _chai.expect)(result).to.be.ok; }); }); }); /* jshint expr:true */
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/temp/src/minecraft/net/minecraft/client/renderer/vertex/VertexFormatElement.java
4127
package net.minecraft.client.renderer.vertex; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class VertexFormatElement { private static final Logger field_177381_a = LogManager.getLogger(); private final VertexFormatElement.EnumType field_177379_b; private final VertexFormatElement.EnumUsage field_177380_c; private final int field_177377_d; private final int field_177378_e; public VertexFormatElement(int p_i46096_1_, VertexFormatElement.EnumType p_i46096_2_, VertexFormatElement.EnumUsage p_i46096_3_, int p_i46096_4_) { if(this.func_177372_a(p_i46096_1_, p_i46096_3_)) { this.field_177380_c = p_i46096_3_; } else { field_177381_a.warn("Multiple vertex elements of the same type other than UVs are not supported. Forcing type to UV."); this.field_177380_c = VertexFormatElement.EnumUsage.UV; } this.field_177379_b = p_i46096_2_; this.field_177377_d = p_i46096_1_; this.field_177378_e = p_i46096_4_; } private final boolean func_177372_a(int p_177372_1_, VertexFormatElement.EnumUsage p_177372_2_) { return p_177372_1_ == 0 || p_177372_2_ == VertexFormatElement.EnumUsage.UV; } public final VertexFormatElement.EnumType func_177367_b() { return this.field_177379_b; } public final VertexFormatElement.EnumUsage func_177375_c() { return this.field_177380_c; } public final int func_177370_d() { return this.field_177378_e; } public final int func_177369_e() { return this.field_177377_d; } public String toString() { return this.field_177378_e + "," + this.field_177380_c.func_177384_a() + "," + this.field_177379_b.func_177396_b(); } public final int func_177368_f() { return this.field_177379_b.func_177395_a() * this.field_177378_e; } public final boolean func_177374_g() { return this.field_177380_c == VertexFormatElement.EnumUsage.POSITION; } public boolean equals(Object p_equals_1_) { if(this == p_equals_1_) { return true; } else if(p_equals_1_ != null && this.getClass() == p_equals_1_.getClass()) { VertexFormatElement vertexformatelement = (VertexFormatElement)p_equals_1_; return this.field_177378_e != vertexformatelement.field_177378_e?false:(this.field_177377_d != vertexformatelement.field_177377_d?false:(this.field_177379_b != vertexformatelement.field_177379_b?false:this.field_177380_c == vertexformatelement.field_177380_c)); } else { return false; } } public int hashCode() { int i = this.field_177379_b.hashCode(); i = 31 * i + this.field_177380_c.hashCode(); i = 31 * i + this.field_177377_d; i = 31 * i + this.field_177378_e; return i; } public static enum EnumType { FLOAT(4, "Float", 5126), UBYTE(1, "Unsigned Byte", 5121), BYTE(1, "Byte", 5120), USHORT(2, "Unsigned Short", 5123), SHORT(2, "Short", 5122), UINT(4, "Unsigned Int", 5125), INT(4, "Int", 5124); private final int field_177407_h; private final String field_177408_i; private final int field_177405_j; private EnumType(int p_i46095_3_, String p_i46095_4_, int p_i46095_5_) { this.field_177407_h = p_i46095_3_; this.field_177408_i = p_i46095_4_; this.field_177405_j = p_i46095_5_; } public int func_177395_a() { return this.field_177407_h; } public String func_177396_b() { return this.field_177408_i; } public int func_177397_c() { return this.field_177405_j; } } public static enum EnumUsage { POSITION("Position"), NORMAL("Normal"), COLOR("Vertex Color"), UV("UV"), MATRIX("Bone Matrix"), BLEND_WEIGHT("Blend Weight"), PADDING("Padding"); private final String field_177392_h; private EnumUsage(String p_i46094_3_) { this.field_177392_h = p_i46094_3_; } public String func_177384_a() { return this.field_177392_h; } } }
gpl-3.0
goldeneye-source/ges-legacy-code
game/ges/server/py/ge_pymodules.cpp
915
///////////// Copyright © 2009 LodleNet. All rights reserved. ///////////// // // Project : Server // File : ge_pymodules.cpp // Description : // [TODO: Write the purpose of ge_pymodules.cpp.] // // Created On: 9/1/2009 10:19:52 PM // Created By: Mark Chandler <mailto:mark@moddb.com> //////////////////////////////////////////////////////////////////////////// #include "ge_pyprecom.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define REG( Name ) extern PyObject* PyInit_##Name(); PyImport_AppendInittab( #Name , &PyInit_##Name ); extern "C" { void RegisterPythonModules() { REG( GEUtil ); REG( GEEntity ); REG( GEPlayer ); REG( GEGlobal ); REG( GEWeapon ); REG( GEAmmoCrate ); REG( GEGamePlay ); REG( GEMPGameRules ); REG( GEAi ); REG( GEAiConst ); REG( GEAiSched ); REG( GEAiTasks ); REG( GEAiCond ); } }
gpl-3.0
dicarve/s3st13
simbio2/simbio_UTILS/simbio_security.inc.php
2186
<?php /** * simbio_security class * A Collection of static function for web security * * Copyright (C) 2007,2008 Arie Nugraha (dicarve@yahoo.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ class simbio_security { /** * Static Method to redirect page to https equivalent * * @param integer $int_https_port * @return void */ public static function doCheckHttps($int_https_port) { $server_https_port = $_SERVER['SERVER_PORT']; if ($server_https_port != $int_https_port) { $host = $_SERVER['SERVER_NAME']; $https_url = 'https://'.$host.$_SERVER['PHP_SELF']; // send HTTP header header("location: $https_url"); } } /** * Static Method to completely destroy session and its cookies * * @param string $str_msg * @param boolean $bool_die * @return void */ public static function destroySessionCookie($str_msg, $str_session_name = '', $str_cookie_path = '/', $bool_die = false) { if (!$str_session_name) { $str_session_name = session_name(); } // deleting session browser cookie @setcookie($str_session_name, '', time()-86400, $str_cookie_path); // destroy all session $_SESSION = null; session_destroy(); if ($bool_die === true) { // shutdown current script die($str_msg); } else { if ($str_msg) { echo $str_msg; } } } } ?>
gpl-3.0
veger/ansible
lib/ansible/modules/files/unarchive.py
35080
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # Copyright: (c) 2013, Dylan Martin <dmartin@seattlecentral.edu> # Copyright: (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # Copyright: (c) 2016, Dag Wieers <dag@wieers.com> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: unarchive version_added: '1.4' short_description: Unpacks an archive after (optionally) copying it from the local machine. extends_documentation_fragment: [ decrypt, files ] description: - The C(unarchive) module unpacks an archive. - By default, it will copy the source file from the local system to the target before unpacking. - Set C(remote_src=yes) to unpack an archive which already exists on the target. - For Windows targets, use the M(win_unzip) module instead. - If checksum validation is desired, use M(get_url) or M(uri) instead to fetch the file and set C(remote_src=yes). options: src: description: - If C(remote_src=no) (default), local path to archive file to copy to the target server; can be absolute or relative. If C(remote_src=yes), path on the target server to existing archive file to unpack. - If C(remote_src=yes) and C(src) contains C(://), the remote machine will download the file from the URL first. (version_added 2.0). This is only for simple cases, for full download support use the M(get_url) module. required: true dest: description: - Remote absolute path where the archive should be unpacked. required: true copy: description: - If true, the file is copied from local 'master' to the target machine, otherwise, the plugin will look for src archive at the target machine. - This option has been deprecated in favor of C(remote_src). - This option is mutually exclusive with C(remote_src). type: 'bool' default: 'yes' creates: description: - If the specified absolute path (file or directory) already exists, this step will B(not) be run. version_added: "1.6" list_files: description: - If set to True, return the list of files that are contained in the tarball. type: 'bool' default: 'no' version_added: "2.0" exclude: description: - List the directory and file entries that you would like to exclude from the unarchive action. version_added: "2.1" keep_newer: description: - Do not replace existing files that are newer than files from the archive. type: 'bool' default: 'no' version_added: "2.1" extra_opts: description: - Specify additional options by passing in an array. default: "" version_added: "2.1" remote_src: description: - Set to C(yes) to indicate the archived file is already on the remote system and not local to the Ansible controller. - This option is mutually exclusive with C(copy). type: 'bool' default: 'no' version_added: "2.2" validate_certs: description: - This only applies if using a https URL as the source of the file. - This should only set to C(no) used on personally controlled sites using self-signed certificate. - Prior to 2.2 the code worked as if this was set to C(yes). type: 'bool' default: 'yes' version_added: "2.2" author: Michael DeHaan todo: - Re-implement tar support using native tarfile module. - Re-implement zip support using native zipfile module. notes: - Requires C(gtar)/C(unzip) command on target host. - Can handle I(.zip) files using C(unzip) as well as I(.tar), I(.tar.gz), I(.tar.bz2) and I(.tar.xz) files using C(gtar). - Uses gtar's C(--diff) arg to calculate if changed or not. If this C(arg) is not supported, it will always unpack the archive. - Existing files/directories in the destination which are not in the archive are not touched. This is the same behavior as a normal archive extraction. - Existing files/directories in the destination which are not in the archive are ignored for purposes of deciding if the archive should be unpacked or not. - For Windows targets, use the M(win_unzip) module instead. ''' EXAMPLES = r''' - name: Extract foo.tgz into /var/lib/foo unarchive: src: foo.tgz dest: /var/lib/foo - name: Unarchive a file that is already on the remote machine unarchive: src: /tmp/foo.zip dest: /usr/local/bin remote_src: yes - name: Unarchive a file that needs to be downloaded (added in 2.0) unarchive: src: https://example.com/example.zip dest: /usr/local/bin remote_src: yes - name: Unarchive a file with extra options unarchive: src: /tmp/foo.zip dest: /usr/local/bin extra_opts: - --transform - s/^xxx/yyy/ ''' import binascii import codecs import datetime import fnmatch import grp import os import platform import pwd import re import stat import time import traceback from zipfile import ZipFile, BadZipfile from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_file from ansible.module_utils._text import to_bytes, to_native, to_text try: # python 3.3+ from shlex import quote except ImportError: # older python from pipes import quote # String from tar that shows the tar contents are different from the # filesystem OWNER_DIFF_RE = re.compile(r': Uid differs$') GROUP_DIFF_RE = re.compile(r': Gid differs$') MODE_DIFF_RE = re.compile(r': Mode differs$') MOD_TIME_DIFF_RE = re.compile(r': Mod time differs$') # NEWER_DIFF_RE = re.compile(r' is newer or same age.$') EMPTY_FILE_RE = re.compile(r': : Warning: Cannot stat: No such file or directory$') MISSING_FILE_RE = re.compile(r': Warning: Cannot stat: No such file or directory$') ZIP_FILE_MODE_RE = re.compile(r'([r-][w-][SsTtx-]){3}') def crc32(path): ''' Return a CRC32 checksum of a file ''' return binascii.crc32(open(path, 'rb').read()) & 0xffffffff def shell_escape(string): ''' Quote meta-characters in the args for the unix shell ''' return re.sub(r'([^A-Za-z0-9_])', r'\\\1', string) class UnarchiveError(Exception): pass class ZipArchive(object): def __init__(self, src, dest, file_args, module): self.src = src self.dest = dest self.file_args = file_args self.opts = module.params['extra_opts'] self.module = module self.excludes = module.params['exclude'] self.includes = [] self.cmd_path = self.module.get_bin_path('unzip') self.zipinfocmd_path = self.module.get_bin_path('zipinfo') self._files_in_archive = [] self._infodict = dict() def _permstr_to_octal(self, modestr, umask): ''' Convert a Unix permission string (rw-r--r--) into a mode (0644) ''' revstr = modestr[::-1] mode = 0 for j in range(0, 3): for i in range(0, 3): if revstr[i + 3 * j] in ['r', 'w', 'x', 's', 't']: mode += 2 ** (i + 3 * j) # The unzip utility does not support setting the stST bits # if revstr[i + 3 * j] in ['s', 't', 'S', 'T' ]: # mode += 2 ** (9 + j) return (mode & ~umask) def _legacy_file_list(self, force_refresh=False): unzip_bin = self.module.get_bin_path('unzip') if not unzip_bin: raise UnarchiveError('Python Zipfile cannot read %s and unzip not found' % self.src) rc, out, err = self.module.run_command([unzip_bin, '-v', self.src]) if rc: raise UnarchiveError('Neither python zipfile nor unzip can read %s' % self.src) for line in out.splitlines()[3:-2]: fields = line.split(None, 7) self._files_in_archive.append(fields[7]) self._infodict[fields[7]] = int(fields[6]) def _crc32(self, path): if self._infodict: return self._infodict[path] try: archive = ZipFile(self.src) except BadZipfile as e: if e.args[0].lower().startswith('bad magic number'): # Python2.4 can't handle zipfiles with > 64K files. Try using # /usr/bin/unzip instead self._legacy_file_list() else: raise else: try: for item in archive.infolist(): self._infodict[item.filename] = int(item.CRC) except: archive.close() raise UnarchiveError('Unable to list files in the archive') return self._infodict[path] @property def files_in_archive(self, force_refresh=False): if self._files_in_archive and not force_refresh: return self._files_in_archive self._files_in_archive = [] try: archive = ZipFile(self.src) except BadZipfile as e: if e.args[0].lower().startswith('bad magic number'): # Python2.4 can't handle zipfiles with > 64K files. Try using # /usr/bin/unzip instead self._legacy_file_list(force_refresh) else: raise else: try: for member in archive.namelist(): exclude_flag = False if self.excludes: for exclude in self.excludes: if fnmatch.fnmatch(member, exclude): exclude_flag = True break if not exclude_flag: self._files_in_archive.append(to_native(member)) except: archive.close() raise UnarchiveError('Unable to list files in the archive') archive.close() return self._files_in_archive def is_unarchived(self): # BSD unzip doesn't support zipinfo listings with timestamp. cmd = [self.zipinfocmd_path, '-T', '-s', self.src] if self.excludes: cmd.extend(['-x', ] + self.excludes) rc, out, err = self.module.run_command(cmd) old_out = out diff = '' out = '' if rc == 0: unarchived = True else: unarchived = False # Get some information related to user/group ownership umask = os.umask(0) os.umask(umask) systemtype = platform.system() # Get current user and group information groups = os.getgroups() run_uid = os.getuid() run_gid = os.getgid() try: run_owner = pwd.getpwuid(run_uid).pw_name except (TypeError, KeyError): run_owner = run_uid try: run_group = grp.getgrgid(run_gid).gr_name except (KeyError, ValueError, OverflowError): run_group = run_gid # Get future user ownership fut_owner = fut_uid = None if self.file_args['owner']: try: tpw = pwd.getpwnam(self.file_args['owner']) except KeyError: try: tpw = pwd.getpwuid(self.file_args['owner']) except (TypeError, KeyError): tpw = pwd.getpwuid(run_uid) fut_owner = tpw.pw_name fut_uid = tpw.pw_uid else: try: fut_owner = run_owner except: pass fut_uid = run_uid # Get future group ownership fut_group = fut_gid = None if self.file_args['group']: try: tgr = grp.getgrnam(self.file_args['group']) except (ValueError, KeyError): try: tgr = grp.getgrgid(self.file_args['group']) except (KeyError, ValueError, OverflowError): tgr = grp.getgrgid(run_gid) fut_group = tgr.gr_name fut_gid = tgr.gr_gid else: try: fut_group = run_group except: pass fut_gid = run_gid for line in old_out.splitlines(): change = False pcs = line.split(None, 7) if len(pcs) != 8: # Too few fields... probably a piece of the header or footer continue # Check first and seventh field in order to skip header/footer if len(pcs[0]) != 7 and len(pcs[0]) != 10: continue if len(pcs[6]) != 15: continue # Possible entries: # -rw-rws--- 1.9 unx 2802 t- defX 11-Aug-91 13:48 perms.2660 # -rw-a-- 1.0 hpf 5358 Tl i4:3 4-Dec-91 11:33 longfilename.hpfs # -r--ahs 1.1 fat 4096 b- i4:2 14-Jul-91 12:58 EA DATA. SF # --w------- 1.0 mac 17357 bx i8:2 4-May-92 04:02 unzip.macr if pcs[0][0] not in 'dl-?' or not frozenset(pcs[0][1:]).issubset('rwxstah-'): continue ztype = pcs[0][0] permstr = pcs[0][1:] version = pcs[1] ostype = pcs[2] size = int(pcs[3]) path = to_text(pcs[7], errors='surrogate_or_strict') # Skip excluded files if path in self.excludes: out += 'Path %s is excluded on request\n' % path continue # Itemized change requires L for symlink if path[-1] == '/': if ztype != 'd': err += 'Path %s incorrectly tagged as "%s", but is a directory.\n' % (path, ztype) ftype = 'd' elif ztype == 'l': ftype = 'L' elif ztype == '-': ftype = 'f' elif ztype == '?': ftype = 'f' # Some files may be storing FAT permissions, not Unix permissions # For FAT permissions, we will use a base permissions set of 777 if the item is a directory or has the execute bit set. Otherwise, 666. # This permission will then be modified by the system UMask. # BSD always applies the Umask, even to Unix permissions. # For Unix style permissions on Linux or Mac, we want to use them directly. # So we set the UMask for this file to zero. That permission set will then be unchanged when calling _permstr_to_octal if len(permstr) == 6: if path[-1] == '/': permstr = 'rwxrwxrwx' elif permstr == 'rwx---': permstr = 'rwxrwxrwx' else: permstr = 'rw-rw-rw-' file_umask = umask elif 'bsd' in systemtype.lower(): file_umask = umask else: file_umask = 0 # Test string conformity if len(permstr) != 9 or not ZIP_FILE_MODE_RE.match(permstr): raise UnarchiveError('ZIP info perm format incorrect, %s' % permstr) # DEBUG # err += "%s%s %10d %s\n" % (ztype, permstr, size, path) dest = os.path.join(self.dest, path) try: st = os.lstat(dest) except: change = True self.includes.append(path) err += 'Path %s is missing\n' % path diff += '>%s++++++.?? %s\n' % (ftype, path) continue # Compare file types if ftype == 'd' and not stat.S_ISDIR(st.st_mode): change = True self.includes.append(path) err += 'File %s already exists, but not as a directory\n' % path diff += 'c%s++++++.?? %s\n' % (ftype, path) continue if ftype == 'f' and not stat.S_ISREG(st.st_mode): change = True unarchived = False self.includes.append(path) err += 'Directory %s already exists, but not as a regular file\n' % path diff += 'c%s++++++.?? %s\n' % (ftype, path) continue if ftype == 'L' and not stat.S_ISLNK(st.st_mode): change = True self.includes.append(path) err += 'Directory %s already exists, but not as a symlink\n' % path diff += 'c%s++++++.?? %s\n' % (ftype, path) continue itemized = list('.%s.......??' % ftype) # Note: this timestamp calculation has a rounding error # somewhere... unzip and this timestamp can be one second off # When that happens, we report a change and re-unzip the file dt_object = datetime.datetime(*(time.strptime(pcs[6], '%Y%m%d.%H%M%S')[0:6])) timestamp = time.mktime(dt_object.timetuple()) # Compare file timestamps if stat.S_ISREG(st.st_mode): if self.module.params['keep_newer']: if timestamp > st.st_mtime: change = True self.includes.append(path) err += 'File %s is older, replacing file\n' % path itemized[4] = 't' elif stat.S_ISREG(st.st_mode) and timestamp < st.st_mtime: # Add to excluded files, ignore other changes out += 'File %s is newer, excluding file\n' % path self.excludes.append(path) continue else: if timestamp != st.st_mtime: change = True self.includes.append(path) err += 'File %s differs in mtime (%f vs %f)\n' % (path, timestamp, st.st_mtime) itemized[4] = 't' # Compare file sizes if stat.S_ISREG(st.st_mode) and size != st.st_size: change = True err += 'File %s differs in size (%d vs %d)\n' % (path, size, st.st_size) itemized[3] = 's' # Compare file checksums if stat.S_ISREG(st.st_mode): crc = crc32(dest) if crc != self._crc32(path): change = True err += 'File %s differs in CRC32 checksum (0x%08x vs 0x%08x)\n' % (path, self._crc32(path), crc) itemized[2] = 'c' # Compare file permissions # Do not handle permissions of symlinks if ftype != 'L': # Use the new mode provided with the action, if there is one if self.file_args['mode']: if isinstance(self.file_args['mode'], int): mode = self.file_args['mode'] else: try: mode = int(self.file_args['mode'], 8) except Exception as e: try: mode = AnsibleModule._symbolic_mode_to_octal(st, self.file_args['mode']) except ValueError as e: self.module.fail_json(path=path, msg="%s" % to_native(e), exception=traceback.format_exc()) # Only special files require no umask-handling elif ztype == '?': mode = self._permstr_to_octal(permstr, 0) else: mode = self._permstr_to_octal(permstr, file_umask) if mode != stat.S_IMODE(st.st_mode): change = True itemized[5] = 'p' err += 'Path %s differs in permissions (%o vs %o)\n' % (path, mode, stat.S_IMODE(st.st_mode)) # Compare file user ownership owner = uid = None try: owner = pwd.getpwuid(st.st_uid).pw_name except (TypeError, KeyError): uid = st.st_uid # If we are not root and requested owner is not our user, fail if run_uid != 0 and (fut_owner != run_owner or fut_uid != run_uid): raise UnarchiveError('Cannot change ownership of %s to %s, as user %s' % (path, fut_owner, run_owner)) if owner and owner != fut_owner: change = True err += 'Path %s is owned by user %s, not by user %s as expected\n' % (path, owner, fut_owner) itemized[6] = 'o' elif uid and uid != fut_uid: change = True err += 'Path %s is owned by uid %s, not by uid %s as expected\n' % (path, uid, fut_uid) itemized[6] = 'o' # Compare file group ownership group = gid = None try: group = grp.getgrgid(st.st_gid).gr_name except (KeyError, ValueError, OverflowError): gid = st.st_gid if run_uid != 0 and fut_gid not in groups: raise UnarchiveError('Cannot change group ownership of %s to %s, as user %s' % (path, fut_group, run_owner)) if group and group != fut_group: change = True err += 'Path %s is owned by group %s, not by group %s as expected\n' % (path, group, fut_group) itemized[6] = 'g' elif gid and gid != fut_gid: change = True err += 'Path %s is owned by gid %s, not by gid %s as expected\n' % (path, gid, fut_gid) itemized[6] = 'g' # Register changed files and finalize diff output if change: if path not in self.includes: self.includes.append(path) diff += '%s %s\n' % (''.join(itemized), path) if self.includes: unarchived = False # DEBUG # out = old_out + out return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd, diff=diff) def unarchive(self): cmd = [self.cmd_path, '-o'] if self.opts: cmd.extend(self.opts) cmd.append(self.src) # NOTE: Including (changed) files as arguments is problematic (limits on command line/arguments) # if self.includes: # NOTE: Command unzip has this strange behaviour where it expects quoted filenames to also be escaped # cmd.extend(map(shell_escape, self.includes)) if self.excludes: cmd.extend(['-x'] + self.excludes) cmd.extend(['-d', self.dest]) rc, out, err = self.module.run_command(cmd) return dict(cmd=cmd, rc=rc, out=out, err=err) def can_handle_archive(self): if not self.cmd_path: return False, 'Command "unzip" not found.' cmd = [self.cmd_path, '-l', self.src] rc, out, err = self.module.run_command(cmd) if rc == 0: return True, None return False, 'Command "%s" could not handle archive.' % self.cmd_path class TgzArchive(object): def __init__(self, src, dest, file_args, module): self.src = src self.dest = dest self.file_args = file_args self.opts = module.params['extra_opts'] self.module = module if self.module.check_mode: self.module.exit_json(skipped=True, msg="remote module (%s) does not support check mode when using gtar" % self.module._name) self.excludes = [path.rstrip('/') for path in self.module.params['exclude']] # Prefer gtar (GNU tar) as it supports the compression options -z, -j and -J self.cmd_path = self.module.get_bin_path('gtar', None) if not self.cmd_path: # Fallback to tar self.cmd_path = self.module.get_bin_path('tar') self.zipflag = '-z' self._files_in_archive = [] if self.cmd_path: self.tar_type = self._get_tar_type() else: self.tar_type = None def _get_tar_type(self): cmd = [self.cmd_path, '--version'] (rc, out, err) = self.module.run_command(cmd) tar_type = None if out.startswith('bsdtar'): tar_type = 'bsd' elif out.startswith('tar') and 'GNU' in out: tar_type = 'gnu' return tar_type @property def files_in_archive(self, force_refresh=False): if self._files_in_archive and not force_refresh: return self._files_in_archive cmd = [self.cmd_path, '--list', '-C', self.dest] if self.zipflag: cmd.append(self.zipflag) if self.opts: cmd.extend(['--show-transformed-names'] + self.opts) if self.excludes: cmd.extend(['--exclude=' + f for f in self.excludes]) cmd.extend(['-f', self.src]) rc, out, err = self.module.run_command(cmd, cwd=self.dest, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')) if rc != 0: raise UnarchiveError('Unable to list files in the archive') for filename in out.splitlines(): # Compensate for locale-related problems in gtar output (octal unicode representation) #11348 # filename = filename.decode('string_escape') filename = to_native(codecs.escape_decode(filename)[0]) # We don't allow absolute filenames. If the user wants to unarchive rooted in "/" # they need to use "dest: '/'". This follows the defaults for gtar, pax, etc. # Allowing absolute filenames here also causes bugs: https://github.com/ansible/ansible/issues/21397 if filename.startswith('/'): filename = filename[1:] exclude_flag = False if self.excludes: for exclude in self.excludes: if fnmatch.fnmatch(filename, exclude): exclude_flag = True break if not exclude_flag: self._files_in_archive.append(to_native(filename)) return self._files_in_archive def is_unarchived(self): cmd = [self.cmd_path, '--diff', '-C', self.dest] if self.zipflag: cmd.append(self.zipflag) if self.opts: cmd.extend(['--show-transformed-names'] + self.opts) if self.file_args['owner']: cmd.append('--owner=' + quote(self.file_args['owner'])) if self.file_args['group']: cmd.append('--group=' + quote(self.file_args['group'])) if self.module.params['keep_newer']: cmd.append('--keep-newer-files') if self.excludes: cmd.extend(['--exclude=' + f for f in self.excludes]) cmd.extend(['-f', self.src]) rc, out, err = self.module.run_command(cmd, cwd=self.dest, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')) # Check whether the differences are in something that we're # setting anyway # What is different unarchived = True old_out = out out = '' run_uid = os.getuid() # When unarchiving as a user, or when owner/group/mode is supplied --diff is insufficient # Only way to be sure is to check request with what is on disk (as we do for zip) # Leave this up to set_fs_attributes_if_different() instead of inducing a (false) change for line in old_out.splitlines() + err.splitlines(): # FIXME: Remove the bogus lines from error-output as well ! # Ignore bogus errors on empty filenames (when using --split-component) if EMPTY_FILE_RE.search(line): continue if run_uid == 0 and not self.file_args['owner'] and OWNER_DIFF_RE.search(line): out += line + '\n' if run_uid == 0 and not self.file_args['group'] and GROUP_DIFF_RE.search(line): out += line + '\n' if not self.file_args['mode'] and MODE_DIFF_RE.search(line): out += line + '\n' if MOD_TIME_DIFF_RE.search(line): out += line + '\n' if MISSING_FILE_RE.search(line): out += line + '\n' if out: unarchived = False return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd) def unarchive(self): cmd = [self.cmd_path, '--extract', '-C', self.dest] if self.zipflag: cmd.append(self.zipflag) if self.opts: cmd.extend(['--show-transformed-names'] + self.opts) if self.file_args['owner']: cmd.append('--owner=' + quote(self.file_args['owner'])) if self.file_args['group']: cmd.append('--group=' + quote(self.file_args['group'])) if self.module.params['keep_newer']: cmd.append('--keep-newer-files') if self.excludes: cmd.extend(['--exclude=' + f for f in self.excludes]) cmd.extend(['-f', self.src]) rc, out, err = self.module.run_command(cmd, cwd=self.dest, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')) return dict(cmd=cmd, rc=rc, out=out, err=err) def can_handle_archive(self): if not self.cmd_path: return False, 'Commands "gtar" and "tar" not found.' if self.tar_type != 'gnu': return False, 'Command "%s" detected as tar type %s. GNU tar required.' % (self.cmd_path, self.tar_type) try: if self.files_in_archive: return True, None except UnarchiveError: return False, 'Command "%s" could not handle archive.' % self.cmd_path # Errors and no files in archive assume that we weren't able to # properly unarchive it return False, 'Command "%s" found no files in archive.' % self.cmd_path # Class to handle tar files that aren't compressed class TarArchive(TgzArchive): def __init__(self, src, dest, file_args, module): super(TarArchive, self).__init__(src, dest, file_args, module) # argument to tar self.zipflag = '' # Class to handle bzip2 compressed tar files class TarBzipArchive(TgzArchive): def __init__(self, src, dest, file_args, module): super(TarBzipArchive, self).__init__(src, dest, file_args, module) self.zipflag = '-j' # Class to handle xz compressed tar files class TarXzArchive(TgzArchive): def __init__(self, src, dest, file_args, module): super(TarXzArchive, self).__init__(src, dest, file_args, module) self.zipflag = '-J' # try handlers in order and return the one that works or bail if none work def pick_handler(src, dest, file_args, module): handlers = [ZipArchive, TgzArchive, TarArchive, TarBzipArchive, TarXzArchive] reasons = set() for handler in handlers: obj = handler(src, dest, file_args, module) (can_handle, reason) = obj.can_handle_archive() if can_handle: return obj reasons.add(reason) reason_msg = ' '.join(reasons) module.fail_json(msg='Failed to find handler for "%s". Make sure the required command to extract the file is installed. %s' % (src, reason_msg)) def main(): module = AnsibleModule( # not checking because of daisy chain to file module argument_spec=dict( src=dict(type='path', required=True), dest=dict(type='path', required=True), remote_src=dict(type='bool', default=False), creates=dict(type='path'), list_files=dict(type='bool', default=False), keep_newer=dict(type='bool', default=False), exclude=dict(type='list', default=[]), extra_opts=dict(type='list', default=[]), validate_certs=dict(type='bool', default=True), ), add_file_common_args=True, # check-mode only works for zip files, we cover that later supports_check_mode=True, ) src = module.params['src'] dest = module.params['dest'] remote_src = module.params['remote_src'] file_args = module.load_file_common_arguments(module.params) # did tar file arrive? if not os.path.exists(src): if not remote_src: module.fail_json(msg="Source '%s' failed to transfer" % src) # If remote_src=true, and src= contains ://, try and download the file to a temp directory. elif '://' in src: src = fetch_file(module, src) else: module.fail_json(msg="Source '%s' does not exist" % src) if not os.access(src, os.R_OK): module.fail_json(msg="Source '%s' not readable" % src) # skip working with 0 size archives try: if os.path.getsize(src) == 0: module.fail_json(msg="Invalid archive '%s', the file is 0 bytes" % src) except Exception as e: module.fail_json(msg="Source '%s' not readable, %s" % (src, to_native(e))) # is dest OK to receive tar file? if not os.path.isdir(dest): module.fail_json(msg="Destination '%s' is not a directory" % dest) handler = pick_handler(src, dest, file_args, module) res_args = dict(handler=handler.__class__.__name__, dest=dest, src=src) # do we need to do unpack? check_results = handler.is_unarchived() # DEBUG # res_args['check_results'] = check_results if module.check_mode: res_args['changed'] = not check_results['unarchived'] elif check_results['unarchived']: res_args['changed'] = False else: # do the unpack try: res_args['extract_results'] = handler.unarchive() if res_args['extract_results']['rc'] != 0: module.fail_json(msg="failed to unpack %s to %s" % (src, dest), **res_args) except IOError: module.fail_json(msg="failed to unpack %s to %s" % (src, dest), **res_args) else: res_args['changed'] = True # Get diff if required if check_results.get('diff', False): res_args['diff'] = {'prepared': check_results['diff']} # Run only if we found differences (idempotence) or diff was missing if res_args.get('diff', True) and not module.check_mode: # do we need to change perms? for filename in handler.files_in_archive: file_args['path'] = os.path.join(dest, filename) try: res_args['changed'] = module.set_fs_attributes_if_different(file_args, res_args['changed'], expand=False) except (IOError, OSError) as e: module.fail_json(msg="Unexpected error when accessing exploded file: %s" % to_native(e), **res_args) if module.params['list_files']: res_args['files'] = handler.files_in_archive module.exit_json(**res_args) if __name__ == '__main__': main()
gpl-3.0
adam111316/SickGear
sickbeard/providers/rsstorrent.py
4156
# Author: Mr_Orange # # This file is part of SickGear. # # SickGear is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SickGear is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickGear. If not, see <http://www.gnu.org/licenses/>. import re from . import generic from sickbeard import logger, tvcache from sickbeard.rssfeeds import RSSFeeds from sickbeard.exceptions import ex from lib.bencode import bdecode class TorrentRssProvider(generic.TorrentProvider): def __init__(self, name, url, cookies='', search_mode='eponly', search_fallback=False, enable_recentsearch=False, enable_backlog=False): generic.TorrentProvider.__init__(self, name) self.url = url.rstrip('/') self.cookies = cookies self.enable_recentsearch = enable_recentsearch self.enable_backlog = enable_backlog self.search_mode = search_mode self.search_fallback = search_fallback self.feeder = RSSFeeds(self) self.cache = TorrentRssCache(self) def image_name(self): return generic.GenericProvider.image_name(self, 'torrentrss') def config_str(self): return '%s|%s|%s|%d|%s|%d|%d|%d' % (self.name or '', self.url or '', self.cookies or '', self.enabled, self.search_mode or '', self.search_fallback, self.enable_recentsearch, self.enable_backlog) def _get_title_and_url(self, item): title, url = None, None if item.title: title = re.sub(r'\s+', '.', u'' + item.title) attempt_list = [lambda: item.torrent_magneturi, lambda: item.enclosures[0].href, lambda: item.link] for cur_attempt in attempt_list: try: url = cur_attempt() except: continue if title and url: break return title, url def validate_feed(self): success, err_msg = self._check_cookie() if not success: return success, err_msg try: items = self.get_cache_data() for item in items: title, url = self._get_title_and_url(item) if not (title and url): continue if url.startswith('magnet:'): if re.search('urn:btih:([0-9a-f]{32,40})', url): break else: torrent_file = self.get_url(url) try: bdecode(torrent_file) break except Exception: pass else: return False, '%s fetched RSS feed data: %s' % \ (('Fail to validate', 'No items found in the')[0 == len(items)], self.url) return True, None except Exception as e: return False, 'Error when trying to load RSS: ' + ex(e) def get_cache_data(self): logger.log(u'TorrentRssCache cache update URL: ' + self.url, logger.DEBUG) data = self.feeder.get_feed(self.url) return [] if not (data and 'entries' in data) else data.entries class TorrentRssCache(tvcache.TVCache): def __init__(self, provider): tvcache.TVCache.__init__(self, provider) self.minTime = 15 def _getRSSData(self): return self.provider.get_cache_data()
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/src/minecraft/net/minecraft/client/particle/ParticleSuspendedTown.java
2422
package net.minecraft.client.particle; import net.minecraft.world.World; public class ParticleSuspendedTown extends Particle { protected ParticleSuspendedTown(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double speedIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, speedIn); float f = this.rand.nextFloat() * 0.1F + 0.2F; this.particleRed = f; this.particleGreen = f; this.particleBlue = f; this.setParticleTextureIndex(0); this.setSize(0.02F, 0.02F); this.particleScale *= this.rand.nextFloat() * 0.6F + 0.5F; this.motionX *= 0.019999999552965164D; this.motionY *= 0.019999999552965164D; this.motionZ *= 0.019999999552965164D; this.particleMaxAge = (int)(20.0D / (Math.random() * 0.8D + 0.2D)); } public void moveEntity(double x, double y, double z) { this.setEntityBoundingBox(this.getEntityBoundingBox().offset(x, y, z)); this.resetPositionToBB(); } public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; this.moveEntity(this.motionX, this.motionY, this.motionZ); this.motionX *= 0.99D; this.motionY *= 0.99D; this.motionZ *= 0.99D; if (this.particleMaxAge-- <= 0) { this.setExpired(); } } public static class Factory implements IParticleFactory { public Particle getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { return new ParticleSuspendedTown(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); } } public static class HappyVillagerFactory implements IParticleFactory { public Particle getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { Particle particle = new ParticleSuspendedTown(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); particle.setParticleTextureIndex(82); particle.setRBGColorF(1.0F, 1.0F, 1.0F); return particle; } } }
gpl-3.0
ryzokuken/plots2
app/models/image.rb
2657
require 'open-uri' class Image < ActiveRecord::Base attr_accessible :uid, :notes, :title, :photo, :nid, :remote_url # has_many :comments, :dependent => :destroy # has_many :likes, :dependent => :destroy # has_many :tags, :dependent => :destroy belongs_to :user, foreign_key: :uid belongs_to :node, foreign_key: :nid has_attached_file :photo, styles: { thumb: '200x150>', medium: '500x375>', large: '800x600>' } # , #:url => "/system/images/photos/:id/:style/:basename.:extension", #:path => ":rails_root/public/system/images/photos/:id/:style/:basename.:extension" validates :uid, presence: :true validates :photo, presence: :true, unless: :remote_url_provided? do_not_validate_attachment_file_type :photo_file_name # disabling type validation as we support many more such as PDF, SVG, see /app/views/editor/rich.html.erb#L232 # validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'] # validates_attachment_content_type :photo_file_name, :content_type => %w(image/jpeg image/jpg image/png) # validates :title, :presence => :true, :format => {:with => /\A[a-zA-Z0-9\ -_]+\z/, :message => "Only letters, numbers, and spaces allowed"}, :length => { :maximum => 60 } before_validation :download_remote_image, if: :remote_url_provided? validates :remote_url, presence: true, if: :remote_url_provided? # , :message => "is invalid or inaccessible" # this message thing is old-style rails 2.3.x before_post_process :is_image? def is_image? (filetype == 'jpg' || filetype == 'jpeg' || filetype == 'gif' || filetype == 'png') end def filetype filename[-3..filename.length].downcase end def path(size = :medium) if is_image? size = :medium if size == :default else size = :original end absolute_uri + photo.url(size) end def filename photo_file_name end private def absolute_uri Rails.env == 'production' ? 'https://publiclab.org' : '' end # all subsequent code from http://trevorturk.com/2008/12/11/easy-upload-via-url-with-paperclip/ def remote_url_provided? !remote_url.blank? end def download_remote_image self.photo = do_download_remote_image puts remote_url puts 'finishes to do_download' self.remote_url = remote_url end def do_download_remote_image io = open(URI.parse(remote_url)) def io.original_filename base_uri.path.split('/').last end io.original_filename.blank? ? nil : io rescue # catch url errors with validations instead of exceptions (Errno:ENOENT, OpenURI:HTTPError, etc...) puts 'had to be rescued' end end
gpl-3.0
lizardsystem/flooding-lib
flooding_base/static/scripts/shared/overlaymanager.js
6270
console.log('loading overlaymanager ...'); var MAPOVERLAY= 1; var ANIMATEDMAPOVERLAY = 2; var MARKEROVERLAY = 3; var ANIMATEDMARKEROVERLAY = 4; var VECTOROVERLAY = 5; var WMSOVERLAY = 6; var ANIMATEDWMSOVERLAY = 7; var PYRAMIDOVERLAY = 8; var ANIMATEDPYRAMIDOVERLAY = 9; /******************Overlay Manager***********************/ //options: use overlay select, png prefix, maxFramesPreLoad var NOverlayManager = function(_map,options) { options = options || {}; this._map = _map; this.animationControl = new NAnimationControl(_map,this, null); this.overlay = {}; this.activeOverlay = null; this.prefixPngLocation = options.prefixPngLocation || ""; this.maxFramesPreLoad = options.maxFramesPreLoad || 60; this.opacity = 0.7; }; NOverlayManager.prototype.setMap = function(_map) { this._map = _map; }; /*** Sets the opacity of the layer. The parameter 'opacity' is a float between 0 and 1 ***/ NOverlayManager.prototype.setOpacity = function(opacity) { this.opacity = opacity; if (this.activeOverlay) { this.activeOverlay.setOpacity(opacity); } }; //ok, if statements are ok NOverlayManager.prototype.destroy = function() { this.clearAllOverlays(); if (this.useOverlaySelect) {this.overlaySelect.remove();} this.animationControl.remove(); for (var el in this) { delete this[el]; } }; /*** Returns the RawResultUrl of the activer layer ***/ NOverlayManager.prototype.getRawResultUrl = function() { if (this.activeOverlay !== null) { return this.activeOverlay.getRawResultUrl(); } else { return null; } }; NOverlayManager.prototype.hide = function() { //hide controls this.animationControl.hide(); //hide overlay if (this.activeOverlay) { this.activeOverlay.hide(true); } }; //TO DO, deze functie herschrijven NOverlayManager.prototype.show = function() { //if animation, show animation control if (this.activeOverlay) { if (is_animated_overlay(this.activeOverlay)) { this.animationControl.show(); this.showOverlay(this.animationControl.frameNr); } else { this.showOverlay(); } } }; /*** Adds an overlay and then initializes the overlay. The paramater 'callbackl' is a method the will be passed to the init method. ***/ NOverlayManager.prototype.addOverlay = function(overlay,callback){ callback = callback || function() {}; if (this.overlay[overlay.id]) { console.log("overlay "+ overlay.id+ "already exist" ); } else { this.overlay[overlay.id] = overlay; overlay.addOverlayToOverlaymanager(this); } overlay.init(callback); }; NOverlayManager.prototype.addAndSetActiveOverlay = function(overlay) { this.hideOverlay(); this.animationControl.stop(); if (overlay !== null) { //add overlay var this_ref = this; //a-synchrone this.addOverlay(overlay,function(){ this_ref.setActiveOverlay(overlay.id); }); return true; } else { console.log("error overlay is null" ); return false; } }; NOverlayManager.prototype.setActiveOverlay = function(id) { //kijk of overlay bestaat //to do: 0 verder en logisch invullen this.hideOverlay(); this.animationControl.stop(); if (this.overlay[id]) { this.activeOverlay = this.overlay[id]; console.log("set overlay to "+ id ); } else if (id === 0) { this.animationControl.hide(); return true; } else { console.log("cannot set overlay to "+ id ); return false; } //kijk of AnimationControl moet worden toegevoegd if (is_animated_overlay(this.activeOverlay)) { this.animationControl.show(); this.animationControl.initOverlay(this.activeOverlay); this.animationControl.startFrame(); if (this.activeOverlay.animation.autoplay) { this.animationControl.play(); } } else { this.animationControl.hide(); this.showOverlay(); } //laat legenda zien // OUDE CODE??? if (this.activeOverlay.legenda) { var tmp = ( this.activeOverlay.filename).replace('\\','/'); var reg = /\S*\//; var legendaUrl = tmp.match(reg) + 'colormapping.csv'; this.activeOverlay.legenda.fetchData( legendaUrl, function(legenda,data,responce){ tabLegenda.setContents(legenda.getHTML());// //scLegenda.contents }); } return true; }; NOverlayManager.prototype.addOverlay = function( overlay, callback ) { if (this.overlay[overlay.id]) { console.log("overlay "+ overlay.id+ "already exist" ); } else { this.overlay[overlay.id] = overlay; overlay.addToOverlayManager(this, callback); } }; NOverlayManager.prototype.removeOverlay = function(overlay ) { if (this.useoverlaySelect) { this.overlaySelect.removeOption(overlay.id,overlay.name);} //this.overlay[overlay.id] = null; this.overlay[overlay.id].destroy(); delete this.overlay[overlay.id] ; }; NOverlayManager.prototype.clearAllOverlays = function( ) { //remember last state if (this.activeOverlay) { this._lastActive = this.activeOverlay.name; } for (var elem in this.overlay) { this.overlay[elem].destroy(); delete this.overlay[elem] ; } this.activeOverlay = null; }; NOverlayManager.prototype.hideOverlay = function(realhide) { this.animationControl.stop(); if (this.activeOverlay === null) { return false; } this.activeOverlay.hide(realhide); return true; }; NOverlayManager.prototype.showOverlay = function (frameNr) { if (this.activeOverlay === null) {return false;} this.activeOverlay.show(frameNr); return true; }; var is_animated_overlay = function(overlay) { return (overlay.type == ANIMATEDMAPOVERLAY || overlay.type == ANIMATEDWMSOVERLAY || overlay.type == ANIMATEDPYRAMIDOVERLAY); };
gpl-3.0
craigcook/bedrock
bedrock/base/tests/test_macros.py
3102
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. import pytest from django_jinja.backend import Jinja2 jinja_env = Jinja2.get_default() def render(s, context=None): t = jinja_env.from_string(s) return t.render(context or {}).strip() EXPECTED_IMAGES = { "basic": """<img src="/media/test.jpg" alt="" />""", "lazy": """<img src="/media/test.jpg" alt="" loading="lazy" />""", "with_alt": """<img src="/media/test.jpg" alt="test alt" />""", "with_class": """<img src="/media/test.jpg" alt="" class="test" />""", "with_dimensions": """<img src="/media/test.jpg" alt="" width="64" height="64" />""", "highres": """<img class="" src="/media/test.jpg" srcset="/media/test-high-res.jpg 1.5x" alt="">""", "l10n": """<img src="/media/img/l10n/en-US/test.jpg" alt="" />""", "external": """<img src="https://test.jpg" alt="" />""", "l10n_highres": """<img class="" src="/media/img/l10n/en-US/test.jpg" srcset="/media/img/l10n/en-US/test-high-res.jpg 1.5x" alt="">""", "highres_lazy": """<img class="" src="/media/test.jpg" srcset="/media/test-high-res.jpg 1.5x" alt="" loading="lazy">""", "all_attributes": """<img class="test" src="/media/img/l10n/en-US/test.jpg" srcset="/media/img/l10n/en-US/test-high-res.jpg 1.5x" alt="test" width="64" height="64" loading="lazy">""", # noqa: E501 } @pytest.mark.parametrize( "test_input, expected", [ ("url='test.jpg'", EXPECTED_IMAGES["basic"]), ("url='test.jpg', loading='lazy'", EXPECTED_IMAGES["lazy"]), ("url='test.jpg', alt='test alt'", EXPECTED_IMAGES["with_alt"]), ("url='test.jpg', class='test'", EXPECTED_IMAGES["with_class"]), ("url='test.jpg', width='64', height='64'", EXPECTED_IMAGES["with_dimensions"]), ("url='test.jpg', include_highres=True", EXPECTED_IMAGES["highres"]), ("url='test.jpg', include_l10n=True", EXPECTED_IMAGES["l10n"]), ("url='https://test.jpg'", EXPECTED_IMAGES["external"]), ("url='test.jpg', include_highres=True, include_l10n=True", EXPECTED_IMAGES["l10n_highres"]), ("url='test.jpg', include_highres=True, loading='lazy'", EXPECTED_IMAGES["highres_lazy"]), ( "url='test.jpg', class='test', alt='test', loading='lazy', width='64', height='64',include_highres=True, include_l10n=True", EXPECTED_IMAGES["all_attributes"], ), ], ) def test_markup(test_input, expected): # note: this isn't actually setting the locale, it's matching the default expected locale mock_request = {"request": {"locale": "en-US"}} # need to split these strings and re-combine them to allow python formatting # (otherwise it conflicts with jinja import syntax) # need to import with context for the request key to appear in l10n_img helper markup = render("{% from 'macros.html' import image with context %}" + "{{{{ image({0}) }}}}".format(test_input), mock_request) assert markup == expected
mpl-2.0
jcjones/boulder
vendor/github.com/zmap/zlint/v3/lints/rfc/lint_ext_subject_key_identifier_missing_ca.go
2838
package rfc /* * ZLint Copyright 2021 Regents of the University of Michigan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import ( "github.com/zmap/zcrypto/x509" "github.com/zmap/zlint/v3/lint" "github.com/zmap/zlint/v3/util" ) type subjectKeyIdMissingCA struct{} /************************************************ To facilitate certification path construction, this extension MUST appear in all conforming CA certificates, that is, all certificates including the basic constraints extension (Section 4.2.1.9) where the value of cA is TRUE. In conforming CA certificates, the value of the subject key identifier MUST be the value placed in the key identifier field of the authority key identifier extension (Section 4.2.1.1) of certificates issued by the subject of this certificate. Applications are not required to verify that key identifiers match when performing certification path validation. ... For end entity certificates, the subject key identifier extension provides a means for identifying certificates containing the particular public key used in an application. Where an end entity has obtained multiple certificates, especially from multiple CAs, the subject key identifier provides a means to quickly identify the set of certificates containing a particular public key. To assist applications in identifying the appropriate end entity certificate, this extension SHOULD be included in all end entity certificates. ************************************************/ func init() { lint.RegisterLint(&lint.Lint{ Name: "e_ext_subject_key_identifier_missing_ca", Description: "CAs MUST include a Subject Key Identifier in all CA certificates", Citation: "RFC 5280: 4.2 & 4.2.1.2", Source: lint.RFC5280, EffectiveDate: util.RFC2459Date, Lint: NewSubjectKeyIdMissingCA, }) } func NewSubjectKeyIdMissingCA() lint.LintInterface { return &subjectKeyIdMissingCA{} } func (l *subjectKeyIdMissingCA) CheckApplies(cert *x509.Certificate) bool { return util.IsCACert(cert) } func (l *subjectKeyIdMissingCA) Execute(cert *x509.Certificate) *lint.LintResult { if util.IsExtInCert(cert, util.SubjectKeyIdentityOID) { return &lint.LintResult{Status: lint.Pass} } else { return &lint.LintResult{Status: lint.Error} } }
mpl-2.0
bfrohs/servo
components/layout/display_list_builder.rs
47008
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Builds display lists from flows and fragments. //! //! Other browser engines sometimes call this "painting", but it is more accurately called display //! list building, as the actual painting does not happen here—only deciding *what* we're going to //! paint. #![deny(unsafe_blocks)] use block::BlockFlow; use context::LayoutContext; use flow::{mod, Flow}; use flow::{IS_ABSOLUTELY_POSITIONED, NEEDS_LAYER}; use fragment::{Fragment, GenericFragment, IframeFragment, IframeFragmentInfo, ImageFragment}; use fragment::{ImageFragmentInfo, InlineAbsoluteHypotheticalFragment, InlineBlockFragment}; use fragment::{ScannedTextFragment, ScannedTextFragmentInfo, TableFragment}; use fragment::{TableCellFragment, TableColumnFragment, TableRowFragment, TableWrapperFragment}; use fragment::{UnscannedTextFragment}; use model; use util::{OpaqueNodeMethods, ToGfxColor}; use geom::approxeq::ApproxEq; use geom::{Point2D, Rect, Size2D, SideOffsets2D}; use gfx::color; use gfx::display_list::{BaseDisplayItem, BorderDisplayItem, BorderDisplayItemClass, DisplayItem}; use gfx::display_list::{DisplayList, GradientDisplayItem, GradientDisplayItemClass, GradientStop}; use gfx::display_list::{ImageDisplayItem, ImageDisplayItemClass, LineDisplayItem}; use gfx::display_list::{LineDisplayItemClass, PseudoDisplayItemClass, SidewaysLeft, SidewaysRight}; use gfx::display_list::{SolidColorDisplayItem, SolidColorDisplayItemClass, StackingContext}; use gfx::display_list::{TextDisplayItem, TextDisplayItemClass, Upright}; use gfx::render_task::RenderLayer; use servo_msg::compositor_msg::{FixedPosition, Scrollable}; use servo_msg::constellation_msg::{ConstellationChan, FrameRectMsg}; use servo_net::image::holder::ImageHolder; use servo_util::geometry::{mod, Au, ZERO_POINT, ZERO_RECT}; use servo_util::logical_geometry::{LogicalRect, WritingMode}; use servo_util::opts; use style::computed::{AngleAoc, CornerAoc, LP_Length, LP_Percentage, LengthOrPercentage}; use style::computed::{LinearGradient, LinearGradientImage, UrlImage}; use style::computed_values::{background_attachment, background_repeat, border_style, overflow}; use style::computed_values::{visibility}; use style::{ComputedValues, Bottom, Left, RGBA, Right, Top}; use sync::Arc; use url::Url; /// The results of display list building for a single flow. pub enum DisplayListBuildingResult { NoDisplayListBuildingResult, StackingContextResult(Arc<StackingContext>), DisplayListResult(Box<DisplayList>), } impl DisplayListBuildingResult { /// Adds the display list items contained within this display list building result to the given /// display list, preserving stacking order. If this display list building result does not /// consist of an entire stacking context, it will be emptied. pub fn add_to(&mut self, display_list: &mut DisplayList) { match *self { NoDisplayListBuildingResult => return, StackingContextResult(ref mut stacking_context) => { display_list.children.push_back((*stacking_context).clone()) } DisplayListResult(ref mut source_display_list) => { display_list.append_from(&mut **source_display_list) } } } } pub trait FragmentDisplayListBuilding { /// Adds the display items necessary to paint the background of this fragment to the display /// list if necessary. fn build_display_list_for_background_if_applicable(&self, style: &ComputedValues, display_list: &mut DisplayList, layout_context: &LayoutContext, level: StackingLevel, absolute_bounds: &Rect<Au>, clip_rect: &Rect<Au>); /// Adds the display items necessary to paint the background image of this fragment to the /// display list at the appropriate stacking level. fn build_display_list_for_background_image(&self, style: &ComputedValues, display_list: &mut DisplayList, layout_context: &LayoutContext, level: StackingLevel, absolute_bounds: &Rect<Au>, clip_rect: &Rect<Au>, image_url: &Url); /// Adds the display items necessary to paint the background linear gradient of this fragment /// to the display list at the appropriate stacking level. fn build_display_list_for_background_linear_gradient(&self, display_list: &mut DisplayList, level: StackingLevel, absolute_bounds: &Rect<Au>, clip_rect: &Rect<Au>, gradient: &LinearGradient, style: &ComputedValues); /// Adds the display items necessary to paint the borders of this fragment to a display list if /// necessary. fn build_display_list_for_borders_if_applicable(&self, style: &ComputedValues, display_list: &mut DisplayList, abs_bounds: &Rect<Au>, level: StackingLevel, clip_rect: &Rect<Au>); fn build_debug_borders_around_text_fragments(&self, display_list: &mut DisplayList, flow_origin: Point2D<Au>, text_fragment: &ScannedTextFragmentInfo, clip_rect: &Rect<Au>); fn build_debug_borders_around_fragment(&self, display_list: &mut DisplayList, flow_origin: Point2D<Au>, clip_rect: &Rect<Au>); /// Adds the display items for this fragment to the given display list. /// /// Arguments: /// /// * `display_list`: The display list to add display items to. /// * `layout_context`: The layout context. /// * `dirty`: The dirty rectangle in the coordinate system of the owning flow. /// * `flow_origin`: Position of the origin of the owning flow wrt the display list root flow. /// * `clip_rect`: The rectangle to clip the display items to. fn build_display_list(&mut self, display_list: &mut DisplayList, layout_context: &LayoutContext, flow_origin: Point2D<Au>, background_and_border_level: BackgroundAndBorderLevel, clip_rect: &Rect<Au>); /// Sends the size and position of this iframe fragment to the constellation. This is out of /// line to guide inlining. fn finalize_position_and_size_of_iframe(&self, iframe_fragment: &IframeFragmentInfo, offset: Point2D<Au>, layout_context: &LayoutContext); fn clip_rect_for_children(&self, current_clip_rect: Rect<Au>, flow_origin: Point2D<Au>) -> Rect<Au>; } impl FragmentDisplayListBuilding for Fragment { fn build_display_list_for_background_if_applicable(&self, style: &ComputedValues, display_list: &mut DisplayList, layout_context: &LayoutContext, level: StackingLevel, absolute_bounds: &Rect<Au>, clip_rect: &Rect<Au>) { // FIXME: This causes a lot of background colors to be displayed when they are clearly not // needed. We could use display list optimization to clean this up, but it still seems // inefficient. What we really want is something like "nearest ancestor element that // doesn't have a fragment". let background_color = style.resolve_color(style.get_background().background_color); if !background_color.alpha.approx_eq(&0.0) { display_list.push(SolidColorDisplayItemClass(box SolidColorDisplayItem { base: BaseDisplayItem::new(*absolute_bounds, self.node, *clip_rect), color: background_color.to_gfx_color(), }), level); } // The background image is painted on top of the background color. // Implements background image, per spec: // http://www.w3.org/TR/CSS21/colors.html#background let background = style.get_background(); match background.background_image { None => {} Some(LinearGradientImage(ref gradient)) => { self.build_display_list_for_background_linear_gradient(display_list, level, absolute_bounds, clip_rect, gradient, style) } Some(UrlImage(ref image_url)) => { self.build_display_list_for_background_image(style, display_list, layout_context, level, absolute_bounds, clip_rect, image_url) } } } fn build_display_list_for_background_image(&self, style: &ComputedValues, display_list: &mut DisplayList, layout_context: &LayoutContext, level: StackingLevel, absolute_bounds: &Rect<Au>, clip_rect: &Rect<Au>, image_url: &Url) { let background = style.get_background(); let mut holder = ImageHolder::new(image_url.clone(), layout_context.shared.image_cache.clone()); let image = match holder.get_image(self.node.to_untrusted_node_address()) { None => { // No image data at all? Do nothing. // // TODO: Add some kind of placeholder background image. debug!("(building display list) no background image :("); return } Some(image) => image, }; debug!("(building display list) building background image"); let image_width = Au::from_px(image.width as int); let image_height = Au::from_px(image.height as int); let mut bounds = *absolute_bounds; // Clip. // // TODO: Check the bounds to see if a clip item is actually required. let clip_rect = clip_rect.intersection(&bounds).unwrap_or(ZERO_RECT); // Use background-attachment to get the initial virtual origin let (virtual_origin_x, virtual_origin_y) = match background.background_attachment { background_attachment::scroll => { (absolute_bounds.origin.x, absolute_bounds.origin.y) } background_attachment::fixed => { (Au(0), Au(0)) } }; // Use background-position to get the offset let horizontal_position = model::specified(background.background_position.horizontal, bounds.size.width - image_width); let vertical_position = model::specified(background.background_position.vertical, bounds.size.height - image_height); let abs_x = virtual_origin_x + horizontal_position; let abs_y = virtual_origin_y + vertical_position; // Adjust origin and size based on background-repeat match background.background_repeat { background_repeat::no_repeat => { bounds.origin.x = abs_x; bounds.origin.y = abs_y; bounds.size.width = image_width; bounds.size.height = image_height; } background_repeat::repeat_x => { bounds.origin.y = abs_y; bounds.size.height = image_height; ImageFragmentInfo::tile_image(&mut bounds.origin.x, &mut bounds.size.width, abs_x, image.width); } background_repeat::repeat_y => { bounds.origin.x = abs_x; bounds.size.width = image_width; ImageFragmentInfo::tile_image(&mut bounds.origin.y, &mut bounds.size.height, abs_y, image.height); } background_repeat::repeat => { ImageFragmentInfo::tile_image(&mut bounds.origin.x, &mut bounds.size.width, abs_x, image.width); ImageFragmentInfo::tile_image(&mut bounds.origin.y, &mut bounds.size.height, abs_y, image.height); } }; // Create the image display item. display_list.push(ImageDisplayItemClass(box ImageDisplayItem { base: BaseDisplayItem::new(bounds, self.node, clip_rect), image: image.clone(), stretch_size: Size2D(Au::from_px(image.width as int), Au::from_px(image.height as int)), }), level); } fn build_display_list_for_background_linear_gradient(&self, display_list: &mut DisplayList, level: StackingLevel, absolute_bounds: &Rect<Au>, clip_rect: &Rect<Au>, gradient: &LinearGradient, style: &ComputedValues) { let clip_rect = clip_rect.intersection(absolute_bounds).unwrap_or(ZERO_RECT); // This is the distance between the center and the ending point; i.e. half of the distance // between the starting point and the ending point. let delta = match gradient.angle_or_corner { AngleAoc(angle) => { Point2D(Au((angle.radians().sin() * absolute_bounds.size.width.to_f64().unwrap() / 2.0) as i32), Au((-angle.radians().cos() * absolute_bounds.size.height.to_f64().unwrap() / 2.0) as i32)) } CornerAoc(horizontal, vertical) => { let x_factor = match horizontal { Left => -1, Right => 1, }; let y_factor = match vertical { Top => -1, Bottom => 1, }; Point2D(Au(x_factor * absolute_bounds.size.width.to_i32().unwrap() / 2), Au(y_factor * absolute_bounds.size.height.to_i32().unwrap() / 2)) } }; // This is the length of the gradient line. let length = Au((delta.x.to_f64().unwrap() * 2.0).hypot(delta.y.to_f64().unwrap() * 2.0) as i32); // Determine the position of each stop per CSS-IMAGES § 3.4. // // FIXME(#3908, pcwalton): Make sure later stops can't be behind earlier stops. let (mut stops, mut stop_run) = (Vec::new(), None); for (i, stop) in gradient.stops.iter().enumerate() { let offset = match stop.position { None => { if stop_run.is_none() { // Initialize a new stop run. let start_offset = if i == 0 { 0.0 } else { // `unwrap()` here should never fail because this is the beginning of // a stop run, which is always bounded by a length or percentage. position_to_offset(gradient.stops[i - 1].position.unwrap(), length) }; let (end_index, end_offset) = match gradient.stops .as_slice() .slice_from(i) .iter() .enumerate() .find(|&(_, ref stop)| stop.position.is_some()) { None => (gradient.stops.len() - 1, 1.0), Some((end_index, end_stop)) => { // `unwrap()` here should never fail because this is the end of // a stop run, which is always bounded by a length or // percentage. (end_index, position_to_offset(end_stop.position.unwrap(), length)) } }; stop_run = Some(StopRun { start_offset: start_offset, end_offset: end_offset, start_index: i, stop_count: end_index - i, }) } let stop_run = stop_run.unwrap(); let stop_run_length = stop_run.end_offset - stop_run.start_offset; if stop_run.stop_count == 0 { stop_run.end_offset } else { stop_run.start_offset + stop_run_length * (i - stop_run.start_index) as f32 / (stop_run.stop_count as f32) } } Some(position) => { stop_run = None; position_to_offset(position, length) } }; stops.push(GradientStop { offset: offset, color: style.resolve_color(stop.color).to_gfx_color() }) } let center = Point2D(absolute_bounds.origin.x + absolute_bounds.size.width / 2, absolute_bounds.origin.y + absolute_bounds.size.height / 2); let gradient_display_item = GradientDisplayItemClass(box GradientDisplayItem { base: BaseDisplayItem::new(*absolute_bounds, self.node, clip_rect), start_point: center - delta, end_point: center + delta, stops: stops, }); display_list.push(gradient_display_item, level) } fn build_display_list_for_borders_if_applicable(&self, style: &ComputedValues, display_list: &mut DisplayList, abs_bounds: &Rect<Au>, level: StackingLevel, clip_rect: &Rect<Au>) { let border = style.logical_border_width(); if border.is_zero() { return } let top_color = style.resolve_color(style.get_border().border_top_color); let right_color = style.resolve_color(style.get_border().border_right_color); let bottom_color = style.resolve_color(style.get_border().border_bottom_color); let left_color = style.resolve_color(style.get_border().border_left_color); // Append the border to the display list. display_list.push(BorderDisplayItemClass(box BorderDisplayItem { base: BaseDisplayItem::new(*abs_bounds, self.node, *clip_rect), border: border.to_physical(style.writing_mode), color: SideOffsets2D::new(top_color.to_gfx_color(), right_color.to_gfx_color(), bottom_color.to_gfx_color(), left_color.to_gfx_color()), style: SideOffsets2D::new(style.get_border().border_top_style, style.get_border().border_right_style, style.get_border().border_bottom_style, style.get_border().border_left_style) }), level); } fn build_debug_borders_around_text_fragments(&self, display_list: &mut DisplayList, flow_origin: Point2D<Au>, text_fragment: &ScannedTextFragmentInfo, clip_rect: &Rect<Au>) { // FIXME(#2795): Get the real container size let container_size = Size2D::zero(); // Fragment position wrt to the owning flow. let fragment_bounds = self.border_box.to_physical(self.style.writing_mode, container_size); let absolute_fragment_bounds = Rect( fragment_bounds.origin + flow_origin, fragment_bounds.size); // Compute the text fragment bounds and draw a border surrounding them. display_list.content.push_back(BorderDisplayItemClass(box BorderDisplayItem { base: BaseDisplayItem::new(absolute_fragment_bounds, self.node, *clip_rect), border: SideOffsets2D::new_all_same(Au::from_px(1)), color: SideOffsets2D::new_all_same(color::rgb(0, 0, 200)), style: SideOffsets2D::new_all_same(border_style::solid) })); // Draw a rectangle representing the baselines. let ascent = text_fragment.run.ascent(); let mut baseline = self.border_box.clone(); baseline.start.b = baseline.start.b + ascent; baseline.size.block = Au(0); let mut baseline = baseline.to_physical(self.style.writing_mode, container_size); baseline.origin = baseline.origin + flow_origin; let line_display_item = box LineDisplayItem { base: BaseDisplayItem::new(baseline, self.node, *clip_rect), color: color::rgb(0, 200, 0), style: border_style::dashed, }; display_list.content.push_back(LineDisplayItemClass(line_display_item)); } fn build_debug_borders_around_fragment(&self, display_list: &mut DisplayList, flow_origin: Point2D<Au>, clip_rect: &Rect<Au>) { // FIXME(#2795): Get the real container size let container_size = Size2D::zero(); // Fragment position wrt to the owning flow. let fragment_bounds = self.border_box.to_physical(self.style.writing_mode, container_size); let absolute_fragment_bounds = Rect( fragment_bounds.origin + flow_origin, fragment_bounds.size); // This prints a debug border around the border of this fragment. display_list.content.push_back(BorderDisplayItemClass(box BorderDisplayItem { base: BaseDisplayItem::new(absolute_fragment_bounds, self.node, *clip_rect), border: SideOffsets2D::new_all_same(Au::from_px(1)), color: SideOffsets2D::new_all_same(color::rgb(0, 0, 200)), style: SideOffsets2D::new_all_same(border_style::solid) })); } fn build_display_list(&mut self, display_list: &mut DisplayList, layout_context: &LayoutContext, flow_origin: Point2D<Au>, background_and_border_level: BackgroundAndBorderLevel, clip_rect: &Rect<Au>) { // Compute the fragment position relative to the parent stacking context. If the fragment // itself establishes a stacking context, then the origin of its position will be (0, 0) // for the purposes of this computation. let stacking_relative_flow_origin = if self.establishes_stacking_context() { ZERO_POINT } else { flow_origin }; let absolute_fragment_bounds = self.stacking_relative_bounds(&stacking_relative_flow_origin); // FIXME(#2795): Get the real container size let container_size = Size2D::zero(); let rect_to_absolute = |writing_mode: WritingMode, logical_rect: LogicalRect<Au>| { let physical_rect = logical_rect.to_physical(writing_mode, container_size); Rect(physical_rect.origin + stacking_relative_flow_origin, physical_rect.size) }; debug!("Fragment::build_display_list at rel={}, abs={}: {}", self.border_box, absolute_fragment_bounds, self); debug!("Fragment::build_display_list: dirty={}, flow_origin={}", layout_context.shared.dirty, flow_origin); if self.style().get_inheritedbox().visibility != visibility::visible { return } if !absolute_fragment_bounds.intersects(&layout_context.shared.dirty) { debug!("Fragment::build_display_list: Did not intersect..."); return } if !absolute_fragment_bounds.intersects(clip_rect) { return; } debug!("Fragment::build_display_list: intersected. Adding display item..."); if self.is_primary_fragment() { let level = StackingLevel::from_background_and_border_level(background_and_border_level); // Add a pseudo-display item for content box queries. This is a very bogus thing to do. let base_display_item = box BaseDisplayItem::new(absolute_fragment_bounds, self.node, *clip_rect); display_list.push(PseudoDisplayItemClass(base_display_item), level); // Add the background to the list, if applicable. match self.inline_context { Some(ref inline_context) => { for style in inline_context.styles.iter().rev() { self.build_display_list_for_background_if_applicable( &**style, display_list, layout_context, level, &absolute_fragment_bounds, clip_rect); } } None => {} } match self.specific { ScannedTextFragment(_) => {}, _ => { self.build_display_list_for_background_if_applicable( &*self.style, display_list, layout_context, level, &absolute_fragment_bounds, clip_rect); } } // Add a border, if applicable. // // TODO: Outlines. match self.inline_context { Some(ref inline_context) => { for style in inline_context.styles.iter().rev() { self.build_display_list_for_borders_if_applicable( &**style, display_list, &absolute_fragment_bounds, level, clip_rect); } } None => {} } match self.specific { ScannedTextFragment(_) => {}, _ => { self.build_display_list_for_borders_if_applicable( &*self.style, display_list, &absolute_fragment_bounds, level, clip_rect); } } } let content_box = self.content_box(); let absolute_content_box = rect_to_absolute(self.style.writing_mode, content_box); // Create special per-fragment-type display items. match self.specific { UnscannedTextFragment(_) => panic!("Shouldn't see unscanned fragments here."), TableColumnFragment(_) => panic!("Shouldn't see table column fragments here."), ScannedTextFragment(ref text_fragment) => { // Create the text display item. let orientation = if self.style.writing_mode.is_vertical() { if self.style.writing_mode.is_sideways_left() { SidewaysLeft } else { SidewaysRight } } else { Upright }; let metrics = &text_fragment.run.font_metrics; let baseline_origin = { let mut content_box_start = content_box.start; content_box_start.b = content_box_start.b + metrics.ascent; content_box_start.to_physical(self.style.writing_mode, container_size) + flow_origin }; display_list.content.push_back(TextDisplayItemClass(box TextDisplayItem { base: BaseDisplayItem::new(absolute_content_box, self.node, *clip_rect), text_run: text_fragment.run.clone(), range: text_fragment.range, text_color: self.style().get_color().color.to_gfx_color(), orientation: orientation, baseline_origin: baseline_origin, })); // Create display items for text decoration { let line = |maybe_color: Option<RGBA>, rect: || -> LogicalRect<Au>| { match maybe_color { None => {} Some(color) => { let bounds = rect_to_absolute(self.style.writing_mode, rect()); display_list.content.push_back(SolidColorDisplayItemClass( box SolidColorDisplayItem { base: BaseDisplayItem::new(bounds, self.node, *clip_rect), color: color.to_gfx_color(), })) } } }; let text_decorations = self.style().get_inheritedtext()._servo_text_decorations_in_effect; line(text_decorations.underline, || { let mut rect = content_box.clone(); rect.start.b = rect.start.b + metrics.ascent - metrics.underline_offset; rect.size.block = metrics.underline_size; rect }); line(text_decorations.overline, || { let mut rect = content_box.clone(); rect.size.block = metrics.underline_size; rect }); line(text_decorations.line_through, || { let mut rect = content_box.clone(); rect.start.b = rect.start.b + metrics.ascent - metrics.strikeout_offset; rect.size.block = metrics.strikeout_size; rect }); } if opts::get().show_debug_fragment_borders { self.build_debug_borders_around_text_fragments(display_list, flow_origin, &**text_fragment, clip_rect); } } GenericFragment | IframeFragment(..) | TableFragment | TableCellFragment | TableRowFragment | TableWrapperFragment | InlineBlockFragment(_) | InlineAbsoluteHypotheticalFragment(_) => { if opts::get().show_debug_fragment_borders { self.build_debug_borders_around_fragment(display_list, flow_origin, clip_rect); } } ImageFragment(ref mut image_fragment) => { let image_ref = &mut image_fragment.image; match image_ref.get_image(self.node.to_untrusted_node_address()) { Some(image) => { debug!("(building display list) building image fragment"); // Place the image into the display list. display_list.content.push_back(ImageDisplayItemClass(box ImageDisplayItem { base: BaseDisplayItem::new(absolute_content_box, self.node, *clip_rect), image: image.clone(), stretch_size: absolute_content_box.size, })); } None => { // No image data at all? Do nothing. // // TODO: Add some kind of placeholder image. debug!("(building display list) no image :("); } } } } if opts::get().show_debug_fragment_borders { self.build_debug_borders_around_fragment(display_list, flow_origin, clip_rect) } // If this is an iframe, then send its position and size up to the constellation. // // FIXME(pcwalton): Doing this during display list construction seems potentially // problematic if iframes are outside the area we're computing the display list for, since // they won't be able to reflow at all until the user scrolls to them. Perhaps we should // separate this into two parts: first we should send the size only to the constellation // once that's computed during assign-block-sizes, and second we should should send the // origin to the constellation here during display list construction. This should work // because layout for the iframe only needs to know size, and origin is only relevant if // the iframe is actually going to be displayed. match self.specific { IframeFragment(ref iframe_fragment) => { self.finalize_position_and_size_of_iframe(&**iframe_fragment, absolute_fragment_bounds.origin, layout_context) } _ => {} } } #[inline(never)] fn finalize_position_and_size_of_iframe(&self, iframe_fragment: &IframeFragmentInfo, offset: Point2D<Au>, layout_context: &LayoutContext) { let border_padding = (self.border_padding).to_physical(self.style.writing_mode); let content_size = self.content_box().size.to_physical(self.style.writing_mode); let iframe_rect = Rect(Point2D(geometry::to_frac_px(offset.x + border_padding.left) as f32, geometry::to_frac_px(offset.y + border_padding.top) as f32), Size2D(geometry::to_frac_px(content_size.width) as f32, geometry::to_frac_px(content_size.height) as f32)); debug!("finalizing position and size of iframe for {},{}", iframe_fragment.pipeline_id, iframe_fragment.subpage_id); let ConstellationChan(ref chan) = layout_context.shared.constellation_chan; chan.send(FrameRectMsg(iframe_fragment.pipeline_id, iframe_fragment.subpage_id, iframe_rect)); } fn clip_rect_for_children(&self, current_clip_rect: Rect<Au>, flow_origin: Point2D<Au>) -> Rect<Au> { // Don't clip if we're text. match self.specific { ScannedTextFragment(_) => return current_clip_rect, _ => {} } // Only clip if `overflow` tells us to. match self.style.get_box().overflow { overflow::hidden | overflow::auto | overflow::scroll => {} _ => return current_clip_rect, } // Create a new clip rect. // // FIXME(#2795): Get the real container size. let physical_rect = self.border_box.to_physical(self.style.writing_mode, Size2D::zero()); current_clip_rect.intersection(&Rect(physical_rect.origin + flow_origin, physical_rect.size)).unwrap_or(ZERO_RECT) } } pub trait BlockFlowDisplayListBuilding { fn build_display_list_for_block_base(&mut self, display_list: &mut DisplayList, layout_context: &LayoutContext, background_border_level: BackgroundAndBorderLevel); fn build_display_list_for_block(&mut self, layout_context: &LayoutContext, background_border_level: BackgroundAndBorderLevel); fn build_display_list_for_absolutely_positioned_block(&mut self, layout_context: &LayoutContext); fn build_display_list_for_floating_block(&mut self, layout_context: &LayoutContext); } impl BlockFlowDisplayListBuilding for BlockFlow { fn build_display_list_for_block_base(&mut self, display_list: &mut DisplayList, layout_context: &LayoutContext, background_border_level: BackgroundAndBorderLevel) { // Add the box that starts the block context. let stacking_relative_fragment_origin = self.base.stacking_relative_position_of_child_fragment(&self.fragment); self.fragment.build_display_list(display_list, layout_context, stacking_relative_fragment_origin, background_border_level, &self.base.clip_rect); for kid in self.base.children.iter_mut() { if flow::base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED) { // All absolute flows will be handled by their containing block. continue } flow::mut_base(kid).display_list_building_result.add_to(display_list); } // Process absolute descendant links. for abs_descendant_link in self.base.abs_descendants.iter() { // TODO(pradeep): Send in our absolute position directly. flow::mut_base(abs_descendant_link).display_list_building_result.add_to(display_list); } } fn build_display_list_for_block(&mut self, layout_context: &LayoutContext, background_border_level: BackgroundAndBorderLevel) { let mut display_list = box DisplayList::new(); self.build_display_list_for_block_base(&mut *display_list, layout_context, background_border_level); self.base.display_list_building_result = DisplayListResult(display_list); } fn build_display_list_for_absolutely_positioned_block(&mut self, layout_context: &LayoutContext) { let mut display_list = box DisplayList::new(); self.build_display_list_for_block_base(&mut *display_list, layout_context, RootOfStackingContextLevel); let bounds = Rect(self.base.stacking_relative_position, self.base.overflow.size.to_physical(self.base.writing_mode)); let z_index = self.fragment.style().get_box().z_index.number_or_zero(); if !self.base.absolute_position_info.layers_needed_for_positioned_flows && !self.base.flags.contains(NEEDS_LAYER) { // We didn't need a layer. self.base.display_list_building_result = StackingContextResult(Arc::new(StackingContext::new(display_list, bounds, z_index, None))); return } // If we got here, then we need a new layer. let scroll_policy = if self.is_fixed() { FixedPosition } else { Scrollable }; let transparent = color::rgba(1.0, 1.0, 1.0, 0.0); let stacking_context = Arc::new(StackingContext::new(display_list, bounds, z_index, Some(Arc::new(RenderLayer::new(self.layer_id(0), transparent, scroll_policy))))); self.base.display_list_building_result = StackingContextResult(stacking_context) } fn build_display_list_for_floating_block(&mut self, layout_context: &LayoutContext) { let mut display_list = box DisplayList::new(); self.build_display_list_for_block_base(&mut *display_list, layout_context, RootOfStackingContextLevel); display_list.form_float_pseudo_stacking_context(); self.base.display_list_building_result = DisplayListResult(display_list); } } // A helper data structure for gradients. struct StopRun { start_offset: f32, end_offset: f32, start_index: uint, stop_count: uint, } fn fmin(a: f32, b: f32) -> f32 { if a < b { a } else { b } } fn position_to_offset(position: LengthOrPercentage, Au(total_length): Au) -> f32 { match position { LP_Length(Au(length)) => fmin(1.0, (length as f32) / (total_length as f32)), LP_Percentage(percentage) => percentage as f32, } } /// "Steps" as defined by CSS 2.1 § E.2. #[deriving(Clone, PartialEq, Show)] pub enum StackingLevel { /// The border and backgrounds for the root of this stacking context: steps 1 and 2. BackgroundAndBordersStackingLevel, /// Borders and backgrounds for block-level descendants: step 4. BlockBackgroundsAndBordersStackingLevel, /// All other content. ContentStackingLevel, } impl StackingLevel { #[inline] pub fn from_background_and_border_level(level: BackgroundAndBorderLevel) -> StackingLevel { match level { RootOfStackingContextLevel => BackgroundAndBordersStackingLevel, BlockLevel => BlockBackgroundsAndBordersStackingLevel, ContentLevel => ContentStackingLevel, } } } /// Which level to place backgrounds and borders in. pub enum BackgroundAndBorderLevel { RootOfStackingContextLevel, BlockLevel, ContentLevel, } trait StackingContextConstruction { /// Adds the given display item at the specified level to this display list. fn push(&mut self, display_item: DisplayItem, level: StackingLevel); } impl StackingContextConstruction for DisplayList { fn push(&mut self, display_item: DisplayItem, level: StackingLevel) { match level { BackgroundAndBordersStackingLevel => { self.background_and_borders.push_back(display_item) } BlockBackgroundsAndBordersStackingLevel => { self.block_backgrounds_and_borders.push_back(display_item) } ContentStackingLevel => self.content.push_back(display_item), } } }
mpl-2.0
mlorb/scinote-web
spec/controllers/assets_controller_spec.rb
2546
# frozen_string_literal: true require 'rails_helper' describe AssetsController, type: :controller do login_user let(:user) { subject.current_user } let!(:team) { create :team, created_by: user } let(:user_team) { create :user_team, :admin, user: user, team: team } let!(:user_project) { create :user_project, :owner, user: user } let(:project) do create :project, team: team, user_projects: [user_project] end let(:experiment) { create :experiment, project: project } let(:my_module) { create :my_module, name: 'test task', experiment: experiment } let(:protocol) do create :protocol, my_module: my_module, team: team, added_by: user end let(:step) { create :step, protocol: protocol, user: user } let(:step_asset_task) { create :step_asset, step: step } let(:result) do create :result, name: 'test result', my_module: my_module, user: user end let(:result_asset) { create :result_asset, result: result } let(:protocol_in_repository) { create :protocol, :in_public_repository, team: team } let(:step_in_repository) { create :step, protocol: protocol_in_repository, user: user } let!(:asset) { create :asset } let(:step_asset_in_repository) { create :step_asset, step: step_in_repository, asset: asset } describe 'POST start_edit' do before do allow(controller).to receive(:check_edit_permission).and_return(true) end let(:action) { post :create_start_edit_image_activity, params: params, format: :json } let!(:params) do { id: nil } end it 'calls create activity service (start edit image on step)' do params[:id] = step_asset_task.asset.id expect(Activities::CreateActivityService).to receive(:call) .with(hash_including(activity_type: :edit_image_on_step)) action end it 'calls create activity service (start edit image on result)' do params[:id] = result_asset.asset.id expect(Activities::CreateActivityService).to receive(:call) .with(hash_including(activity_type: :edit_image_on_result)) action end it 'calls create activity service (start edit image on step in repository)' do params[:id] = step_asset_in_repository.asset.id user_team expect(Activities::CreateActivityService).to receive(:call) .with(hash_including(activity_type: :edit_image_on_step_in_repository)) action end it 'adds activity in DB' do params[:id] = step_asset_task.asset.id expect { action } .to(change { Activity.count }) end end end
mpl-2.0
Ninir/terraform-provider-aws
vendor/github.com/aws/aws-sdk-go/service/kinesisvideo/errors.go
2983
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package kinesisvideo const ( // ErrCodeAccountStreamLimitExceededException for service response error code // "AccountStreamLimitExceededException". // // The number of streams created for the account is too high. ErrCodeAccountStreamLimitExceededException = "AccountStreamLimitExceededException" // ErrCodeClientLimitExceededException for service response error code // "ClientLimitExceededException". // // Kinesis Video Streams has throttled the request because you have exceeded // the limit of allowed client calls. Try making the call later. ErrCodeClientLimitExceededException = "ClientLimitExceededException" // ErrCodeDeviceStreamLimitExceededException for service response error code // "DeviceStreamLimitExceededException". // // Not implemented. ErrCodeDeviceStreamLimitExceededException = "DeviceStreamLimitExceededException" // ErrCodeInvalidArgumentException for service response error code // "InvalidArgumentException". // // The value for this input parameter is invalid. ErrCodeInvalidArgumentException = "InvalidArgumentException" // ErrCodeInvalidDeviceException for service response error code // "InvalidDeviceException". // // Not implemented. ErrCodeInvalidDeviceException = "InvalidDeviceException" // ErrCodeInvalidResourceFormatException for service response error code // "InvalidResourceFormatException". // // The format of the StreamARN is invalid. ErrCodeInvalidResourceFormatException = "InvalidResourceFormatException" // ErrCodeNotAuthorizedException for service response error code // "NotAuthorizedException". // // The caller is not authorized to perform this operation. ErrCodeNotAuthorizedException = "NotAuthorizedException" // ErrCodeResourceInUseException for service response error code // "ResourceInUseException". // // The stream is currently not available for this operation. ErrCodeResourceInUseException = "ResourceInUseException" // ErrCodeResourceNotFoundException for service response error code // "ResourceNotFoundException". // // Amazon Kinesis Video Streams can't find the stream that you specified. ErrCodeResourceNotFoundException = "ResourceNotFoundException" // ErrCodeTagsPerResourceExceededLimitException for service response error code // "TagsPerResourceExceededLimitException". // // You have exceeded the limit of tags that you can associate with the resource. // Kinesis video streams support up to 50 tags. ErrCodeTagsPerResourceExceededLimitException = "TagsPerResourceExceededLimitException" // ErrCodeVersionMismatchException for service response error code // "VersionMismatchException". // // The stream version that you specified is not the latest version. To get the // latest version, use the DescribeStream (https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_DescribeStream.html) // API. ErrCodeVersionMismatchException = "VersionMismatchException" )
mpl-2.0
hintjens/zmq.rs
src/v2_protocol.rs
94
pub static MORE_FLAG: u8 = 1; pub static LARGE_FLAG: u8 = 2; pub static COMMAND_FLAG: u8 = 4;
mpl-2.0
dbresson/nomad
client/driver/executor_plugin.go
5188
package driver import ( "encoding/gob" "log" "net/rpc" "github.com/hashicorp/go-plugin" "github.com/hashicorp/nomad/client/driver/executor" cstructs "github.com/hashicorp/nomad/client/structs" "github.com/hashicorp/nomad/nomad/structs" ) // Registering these types since we have to serialize and de-serialize the Task // structs over the wire between drivers and the executor. func init() { gob.Register([]interface{}{}) gob.Register(map[string]interface{}{}) gob.Register([]map[string]string{}) gob.Register([]map[string]int{}) } type ExecutorRPC struct { client *rpc.Client logger *log.Logger } // LaunchCmdArgs wraps a user command and the args for the purposes of RPC type LaunchCmdArgs struct { Cmd *executor.ExecCommand Ctx *executor.ExecutorContext } // LaunchSyslogServerArgs wraps the executor context for the purposes of RPC type LaunchSyslogServerArgs struct { Ctx *executor.ExecutorContext } // SyncServicesArgs wraps the consul context for the purposes of RPC type SyncServicesArgs struct { Ctx *executor.ConsulContext } func (e *ExecutorRPC) LaunchCmd(cmd *executor.ExecCommand, ctx *executor.ExecutorContext) (*executor.ProcessState, error) { var ps *executor.ProcessState err := e.client.Call("Plugin.LaunchCmd", LaunchCmdArgs{Cmd: cmd, Ctx: ctx}, &ps) return ps, err } func (e *ExecutorRPC) LaunchSyslogServer(ctx *executor.ExecutorContext) (*executor.SyslogServerState, error) { var ss *executor.SyslogServerState err := e.client.Call("Plugin.LaunchSyslogServer", LaunchSyslogServerArgs{Ctx: ctx}, &ss) return ss, err } func (e *ExecutorRPC) Wait() (*executor.ProcessState, error) { var ps executor.ProcessState err := e.client.Call("Plugin.Wait", new(interface{}), &ps) return &ps, err } func (e *ExecutorRPC) ShutDown() error { return e.client.Call("Plugin.ShutDown", new(interface{}), new(interface{})) } func (e *ExecutorRPC) Exit() error { return e.client.Call("Plugin.Exit", new(interface{}), new(interface{})) } func (e *ExecutorRPC) UpdateLogConfig(logConfig *structs.LogConfig) error { return e.client.Call("Plugin.UpdateLogConfig", logConfig, new(interface{})) } func (e *ExecutorRPC) UpdateTask(task *structs.Task) error { return e.client.Call("Plugin.UpdateTask", task, new(interface{})) } func (e *ExecutorRPC) SyncServices(ctx *executor.ConsulContext) error { return e.client.Call("Plugin.SyncServices", SyncServicesArgs{Ctx: ctx}, new(interface{})) } func (e *ExecutorRPC) DeregisterServices() error { return e.client.Call("Plugin.DeregisterServices", new(interface{}), new(interface{})) } func (e *ExecutorRPC) Version() (*executor.ExecutorVersion, error) { var version executor.ExecutorVersion err := e.client.Call("Plugin.Version", new(interface{}), &version) return &version, err } func (e *ExecutorRPC) Stats() (*cstructs.TaskResourceUsage, error) { var resourceUsage cstructs.TaskResourceUsage err := e.client.Call("Plugin.Stats", new(interface{}), &resourceUsage) return &resourceUsage, err } type ExecutorRPCServer struct { Impl executor.Executor logger *log.Logger } func (e *ExecutorRPCServer) LaunchCmd(args LaunchCmdArgs, ps *executor.ProcessState) error { state, err := e.Impl.LaunchCmd(args.Cmd, args.Ctx) if state != nil { *ps = *state } return err } func (e *ExecutorRPCServer) LaunchSyslogServer(args LaunchSyslogServerArgs, ss *executor.SyslogServerState) error { state, err := e.Impl.LaunchSyslogServer(args.Ctx) if state != nil { *ss = *state } return err } func (e *ExecutorRPCServer) Wait(args interface{}, ps *executor.ProcessState) error { state, err := e.Impl.Wait() if state != nil { *ps = *state } return err } func (e *ExecutorRPCServer) ShutDown(args interface{}, resp *interface{}) error { return e.Impl.ShutDown() } func (e *ExecutorRPCServer) Exit(args interface{}, resp *interface{}) error { return e.Impl.Exit() } func (e *ExecutorRPCServer) UpdateLogConfig(args *structs.LogConfig, resp *interface{}) error { return e.Impl.UpdateLogConfig(args) } func (e *ExecutorRPCServer) UpdateTask(args *structs.Task, resp *interface{}) error { return e.Impl.UpdateTask(args) } func (e *ExecutorRPCServer) SyncServices(args SyncServicesArgs, resp *interface{}) error { return e.Impl.SyncServices(args.Ctx) } func (e *ExecutorRPCServer) DeregisterServices(args interface{}, resp *interface{}) error { return e.Impl.DeregisterServices() } func (e *ExecutorRPCServer) Version(args interface{}, version *executor.ExecutorVersion) error { ver, err := e.Impl.Version() if ver != nil { *version = *ver } return err } func (e *ExecutorRPCServer) Stats(args interface{}, resourceUsage *cstructs.TaskResourceUsage) error { ru, err := e.Impl.Stats() if ru != nil { *resourceUsage = *ru } return err } type ExecutorPlugin struct { logger *log.Logger Impl *ExecutorRPCServer } func (p *ExecutorPlugin) Server(*plugin.MuxBroker) (interface{}, error) { if p.Impl == nil { p.Impl = &ExecutorRPCServer{Impl: executor.NewExecutor(p.logger), logger: p.logger} } return p.Impl, nil } func (p *ExecutorPlugin) Client(b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) { return &ExecutorRPC{client: c, logger: p.logger}, nil }
mpl-2.0
armandobs14/SaudeBR
SaudeBR_WEB/vendor/symfony/dependency-injection/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
43930
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\Variable; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; use Symfony\Component\DependencyInjection\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\Expression; /** * PhpDumper dumps a service container as a PHP class. * * @author Fabien Potencier <fabien@symfony.com> * @author Johannes M. Schmitt <schmittjoh@gmail.com> * * @api */ class PhpDumper extends Dumper { /** * Characters that might appear in the generated variable name as first character * @var string */ const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz'; /** * Characters that might appear in the generated variable name as any but the first character * @var string */ const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_'; private $inlinedDefinitions; private $definitionVariables; private $referenceVariables; private $variableCount; private $reservedVariables = array('instance', 'class'); private $expressionLanguage; /** * @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface */ private $proxyDumper; /** * {@inheritDoc} * * @api */ public function __construct(ContainerBuilder $container) { parent::__construct($container); $this->inlinedDefinitions = new \SplObjectStorage; } /** * Sets the dumper to be used when dumping proxies in the generated container. * * @param ProxyDumper $proxyDumper */ public function setProxyDumper(ProxyDumper $proxyDumper) { $this->proxyDumper = $proxyDumper; } /** * Dumps the service container as a PHP class. * * Available options: * * * class: The class name * * base_class: The base class name * * namespace: The class namespace * * @param array $options An array of options * * @return string A PHP class representing of the service container * * @api */ public function dump(array $options = array()) { $options = array_merge(array( 'class' => 'ProjectServiceContainer', 'base_class' => 'Container', 'namespace' => '', ), $options); $code = $this->startClass($options['class'], $options['base_class'], $options['namespace']); if ($this->container->isFrozen()) { $code .= $this->addFrozenConstructor(); } else { $code .= $this->addConstructor(); } $code .= $this->addServices(). $this->addDefaultParametersMethod(). $this->endClass(). $this->addProxyClasses() ; return $code; } /** * Retrieves the currently set proxy dumper or instantiates one. * * @return ProxyDumper */ private function getProxyDumper() { if (!$this->proxyDumper) { $this->proxyDumper = new NullDumper(); } return $this->proxyDumper; } /** * Generates Service local temp variables. * * @param string $cId * @param string $definition * * @return string */ private function addServiceLocalTempVariables($cId, $definition) { static $template = " \$%s = %s;\n"; $localDefinitions = array_merge( array($definition), $this->getInlinedDefinitions($definition) ); $calls = $behavior = array(); foreach ($localDefinitions as $iDefinition) { $this->getServiceCallsFromArguments($iDefinition->getArguments(), $calls, $behavior); $this->getServiceCallsFromArguments($iDefinition->getMethodCalls(), $calls, $behavior); $this->getServiceCallsFromArguments($iDefinition->getProperties(), $calls, $behavior); } $code = ''; foreach ($calls as $id => $callCount) { if ('service_container' === $id || $id === $cId) { continue; } if ($callCount > 1) { $name = $this->getNextVariableName(); $this->referenceVariables[$id] = new Variable($name); if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $behavior[$id]) { $code .= sprintf($template, $name, $this->getServiceCall($id)); } else { $code .= sprintf($template, $name, $this->getServiceCall($id, new Reference($id, ContainerInterface::NULL_ON_INVALID_REFERENCE))); } } } if ('' !== $code) { $code .= "\n"; } return $code; } /** * Generates code for the proxies to be attached after the container class * * @return string */ private function addProxyClasses() { /* @var $proxyDefinitions Definition[] */ $definitions = array_filter( $this->container->getDefinitions(), array($this->getProxyDumper(), 'isProxyCandidate') ); $code = ''; foreach ($definitions as $definition) { $code .= "\n" . $this->getProxyDumper()->getProxyCode($definition); } return $code; } /** * Generates the require_once statement for service includes. * * @param string $id The service id * @param Definition $definition * * @return string */ private function addServiceInclude($id, $definition) { $template = " require_once %s;\n"; $code = ''; if (null !== $file = $definition->getFile()) { $code .= sprintf($template, $this->dumpValue($file)); } foreach ($this->getInlinedDefinitions($definition) as $definition) { if (null !== $file = $definition->getFile()) { $code .= sprintf($template, $this->dumpValue($file)); } } if ('' !== $code) { $code .= "\n"; } return $code; } /** * Generates the inline definition of a service. * * @param string $id * @param Definition $definition * * @return string * * @throws RuntimeException When the factory definition is incomplete * @throws ServiceCircularReferenceException When a circular reference is detected */ private function addServiceInlinedDefinitions($id, $definition) { $code = ''; $variableMap = $this->definitionVariables; $nbOccurrences = new \SplObjectStorage(); $processed = new \SplObjectStorage(); $inlinedDefinitions = $this->getInlinedDefinitions($definition); foreach ($inlinedDefinitions as $definition) { if (false === $nbOccurrences->contains($definition)) { $nbOccurrences->offsetSet($definition, 1); } else { $i = $nbOccurrences->offsetGet($definition); $nbOccurrences->offsetSet($definition, $i + 1); } } foreach ($inlinedDefinitions as $sDefinition) { if ($processed->contains($sDefinition)) { continue; } $processed->offsetSet($sDefinition); $class = $this->dumpValue($sDefinition->getClass()); if ($nbOccurrences->offsetGet($sDefinition) > 1 || $sDefinition->getMethodCalls() || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) { $name = $this->getNextVariableName(); $variableMap->offsetSet($sDefinition, new Variable($name)); // a construct like: // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a); // this is an indication for a wrong implementation, you can circumvent this problem // by setting up your service structure like this: // $b = new ServiceB(); // $a = new ServiceA(ServiceB $b); // $b->setServiceA(ServiceA $a); if ($this->hasReference($id, $sDefinition->getArguments())) { throw new ServiceCircularReferenceException($id, array($id)); } $code .= $this->addNewInstance($id, $sDefinition, '$'.$name, ' = '); if (!$this->hasReference($id, $sDefinition->getMethodCalls(), true) && !$this->hasReference($id, $sDefinition->getProperties(), true)) { $code .= $this->addServiceMethodCalls(null, $sDefinition, $name); $code .= $this->addServiceProperties(null, $sDefinition, $name); $code .= $this->addServiceConfigurator(null, $sDefinition, $name); } $code .= "\n"; } } return $code; } /** * Adds the service return statement. * * @param string $id Service id * @param Definition $definition * * @return string */ private function addServiceReturn($id, $definition) { if ($this->isSimpleInstance($id, $definition)) { return " }\n"; } return "\n return \$instance;\n }\n"; } /** * Generates the service instance. * * @param string $id * @param Definition $definition * * @return string * * @throws InvalidArgumentException * @throws RuntimeException */ private function addServiceInstance($id, $definition) { $class = $this->dumpValue($definition->getClass()); if (0 === strpos($class, "'") && !preg_match('/^\'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) { throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id)); } $simple = $this->isSimpleInstance($id, $definition); $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); $instantiation = ''; if (!$isProxyCandidate && ContainerInterface::SCOPE_CONTAINER === $definition->getScope()) { $instantiation = "\$this->services['$id'] = ".($simple ? '' : '$instance'); } elseif (!$isProxyCandidate && ContainerInterface::SCOPE_PROTOTYPE !== $scope = $definition->getScope()) { $instantiation = "\$this->services['$id'] = \$this->scopedServices['$scope']['$id'] = ".($simple ? '' : '$instance'); } elseif (!$simple) { $instantiation = '$instance'; } $return = ''; if ($simple) { $return = 'return '; } else { $instantiation .= ' = '; } $code = $this->addNewInstance($id, $definition, $return, $instantiation); if (!$simple) { $code .= "\n"; } return $code; } /** * Checks if the definition is a simple instance. * * @param string $id * @param Definition $definition * * @return Boolean */ private function isSimpleInstance($id, $definition) { foreach (array_merge(array($definition), $this->getInlinedDefinitions($definition)) as $sDefinition) { if ($definition !== $sDefinition && !$this->hasReference($id, $sDefinition->getMethodCalls())) { continue; } if ($sDefinition->getMethodCalls() || $sDefinition->getProperties() || $sDefinition->getConfigurator()) { return false; } } return true; } /** * Adds method calls to a service definition. * * @param string $id * @param Definition $definition * @param string $variableName * * @return string */ private function addServiceMethodCalls($id, $definition, $variableName = 'instance') { $calls = ''; foreach ($definition->getMethodCalls() as $call) { $arguments = array(); foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments))); } return $calls; } private function addServiceProperties($id, $definition, $variableName = 'instance') { $code = ''; foreach ($definition->getProperties() as $name => $value) { $code .= sprintf(" \$%s->%s = %s;\n", $variableName, $name, $this->dumpValue($value)); } return $code; } /** * Generates the inline definition setup. * * @param string $id * @param Definition $definition * @return string */ private function addServiceInlinedDefinitionsSetup($id, $definition) { $this->referenceVariables[$id] = new Variable('instance'); $code = ''; $processed = new \SplObjectStorage(); foreach ($this->getInlinedDefinitions($definition) as $iDefinition) { if ($processed->contains($iDefinition)) { continue; } $processed->offsetSet($iDefinition); if (!$this->hasReference($id, $iDefinition->getMethodCalls(), true) && !$this->hasReference($id, $iDefinition->getProperties(), true)) { continue; } // if the instance is simple, the return statement has already been generated // so, the only possible way to get there is because of a circular reference if ($this->isSimpleInstance($id, $definition)) { throw new ServiceCircularReferenceException($id, array($id)); } $name = (string) $this->definitionVariables->offsetGet($iDefinition); $code .= $this->addServiceMethodCalls(null, $iDefinition, $name); $code .= $this->addServiceProperties(null, $iDefinition, $name); $code .= $this->addServiceConfigurator(null, $iDefinition, $name); } if ('' !== $code) { $code .= "\n"; } return $code; } /** * Adds configurator definition * * @param string $id * @param Definition $definition * @param string $variableName * * @return string */ private function addServiceConfigurator($id, $definition, $variableName = 'instance') { if (!$callable = $definition->getConfigurator()) { return ''; } if (is_array($callable)) { if ($callable[0] instanceof Reference) { return sprintf(" %s->%s(\$%s);\n", $this->getServiceCall((string) $callable[0]), $callable[1], $variableName); } return sprintf(" call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } return sprintf(" %s(\$%s);\n", $callable, $variableName); } /** * Adds a service * * @param string $id * @param Definition $definition * * @return string */ private function addService($id, $definition) { $this->definitionVariables = new \SplObjectStorage(); $this->referenceVariables = array(); $this->variableCount = 0; $return = array(); if ($definition->isSynthetic()) { $return[] = '@throws RuntimeException always since this service is expected to be injected dynamically'; } elseif ($class = $definition->getClass()) { $return[] = sprintf("@return %s A %s instance.", 0 === strpos($class, '%') ? 'object' : $class, $class); } elseif ($definition->getFactoryClass()) { $return[] = sprintf('@return object An instance returned by %s::%s().', $definition->getFactoryClass(), $definition->getFactoryMethod()); } elseif ($definition->getFactoryService()) { $return[] = sprintf('@return object An instance returned by %s::%s().', $definition->getFactoryService(), $definition->getFactoryMethod()); } $scope = $definition->getScope(); if (!in_array($scope, array(ContainerInterface::SCOPE_CONTAINER, ContainerInterface::SCOPE_PROTOTYPE))) { if ($return && 0 === strpos($return[count($return) - 1], '@return')) { $return[] = ''; } $return[] = sprintf("@throws InactiveScopeException when the '%s' service is requested while the '%s' scope is not active", $id, $scope); } $return = implode("\n * ", $return); $doc = ''; if (ContainerInterface::SCOPE_PROTOTYPE !== $scope) { $doc .= <<<EOF * * This service is shared. * This method always returns the same instance of the service. EOF; } if (!$definition->isPublic()) { $doc .= <<<EOF * * This service is private. * If you want to be able to request this service from the container directly, * make it public, otherwise you might end up with broken code. EOF; } if ($definition->isLazy()) { $lazyInitialization = '$lazyLoad = true'; $lazyInitializationDoc = "\n * @param boolean \$lazyLoad whether to try lazy-loading the service with a proxy\n *"; } else { $lazyInitialization = ''; $lazyInitializationDoc = ''; } // with proxies, for 5.3.3 compatibility, the getter must be public to be accessible to the initializer $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); $visibility = $isProxyCandidate ? 'public' : 'protected'; $code = <<<EOF /** * Gets the '$id' service.$doc *$lazyInitializationDoc * $return */ {$visibility} function get{$this->camelize($id)}Service($lazyInitialization) { EOF; $code .= $isProxyCandidate ? $this->getProxyDumper()->getProxyFactoryCode($definition, $id) : ''; if (!in_array($scope, array(ContainerInterface::SCOPE_CONTAINER, ContainerInterface::SCOPE_PROTOTYPE))) { $code .= <<<EOF if (!isset(\$this->scopedServices['$scope'])) { throw new InactiveScopeException('$id', '$scope'); } EOF; } if ($definition->isSynthetic()) { $code .= sprintf(" throw new RuntimeException('You have requested a synthetic service (\"%s\"). The DIC does not know how to construct this service.');\n }\n", $id); } else { $code .= $this->addServiceInclude($id, $definition). $this->addServiceLocalTempVariables($id, $definition). $this->addServiceInlinedDefinitions($id, $definition). $this->addServiceInstance($id, $definition). $this->addServiceInlinedDefinitionsSetup($id, $definition). $this->addServiceMethodCalls($id, $definition). $this->addServiceProperties($id, $definition). $this->addServiceConfigurator($id, $definition). $this->addServiceReturn($id, $definition) ; } $this->definitionVariables = null; $this->referenceVariables = null; return $code; } /** * Adds multiple services * * @return string */ private function addServices() { $publicServices = $privateServices = $synchronizers = ''; $definitions = $this->container->getDefinitions(); ksort($definitions); foreach ($definitions as $id => $definition) { if ($definition->isPublic()) { $publicServices .= $this->addService($id, $definition); } else { $privateServices .= $this->addService($id, $definition); } $synchronizers .= $this->addServiceSynchronizer($id, $definition); } return $publicServices.$synchronizers.$privateServices; } /** * Adds synchronizer methods. * * @param string $id A service identifier * @param Definition $definition A Definition instance */ private function addServiceSynchronizer($id, Definition $definition) { if (!$definition->isSynchronized()) { return; } $code = ''; foreach ($this->container->getDefinitions() as $definitionId => $definition) { foreach ($definition->getMethodCalls() as $call) { foreach ($call[1] as $argument) { if ($argument instanceof Reference && $id == (string) $argument) { $arguments = array(); foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } $call = $this->wrapServiceConditionals($call[1], sprintf("\$this->get('%s')->%s(%s);", $definitionId, $call[0], implode(', ', $arguments))); $code .= <<<EOF if (\$this->initialized('$definitionId')) { $call } EOF; } } } } if (!$code) { return; } return <<<EOF /** * Updates the '$id' service. */ protected function synchronize{$this->camelize($id)}Service() { $code } EOF; } private function addNewInstance($id, Definition $definition, $return, $instantiation) { $class = $this->dumpValue($definition->getClass()); $arguments = array(); foreach ($definition->getArguments() as $value) { $arguments[] = $this->dumpValue($value); } if (null !== $definition->getFactoryMethod()) { if (null !== $definition->getFactoryClass()) { return sprintf(" $return{$instantiation}call_user_func(array(%s, '%s')%s);\n", $this->dumpValue($definition->getFactoryClass()), $definition->getFactoryMethod(), $arguments ? ', '.implode(', ', $arguments) : ''); } if (null !== $definition->getFactoryService()) { return sprintf(" $return{$instantiation}%s->%s(%s);\n", $this->getServiceCall($definition->getFactoryService()), $definition->getFactoryMethod(), implode(', ', $arguments)); } throw new RuntimeException(sprintf('Factory method requires a factory service or factory class in service definition for %s', $id)); } if (false !== strpos($class, '$')) { return sprintf(" \$class = %s;\n\n $return{$instantiation}new \$class(%s);\n", $class, implode(', ', $arguments)); } return sprintf(" $return{$instantiation}new \\%s(%s);\n", substr(str_replace('\\\\', '\\', $class), 1, -1), implode(', ', $arguments)); } /** * Adds the class headers. * * @param string $class Class name * @param string $baseClass The name of the base class * @param string $namespace The class namespace * * @return string */ private function startClass($class, $baseClass, $namespace) { $bagClass = $this->container->isFrozen() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;'; $namespaceLine = $namespace ? "namespace $namespace;\n" : ''; return <<<EOF <?php $namespaceLine use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\Exception\InactiveScopeException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Parameter; $bagClass /** * $class * * This class has been auto-generated * by the Symfony Dependency Injection Component. */ class $class extends $baseClass { EOF; } /** * Adds the constructor. * * @return string */ private function addConstructor() { $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null; $code = <<<EOF /** * Constructor. */ public function __construct() { parent::__construct($arguments); EOF; if (count($scopes = $this->container->getScopes()) > 0) { $code .= "\n"; $code .= " \$this->scopes = ".$this->dumpValue($scopes).";\n"; $code .= " \$this->scopeChildren = ".$this->dumpValue($this->container->getScopeChildren()).";\n"; } $code .= $this->addMethodMap(); $code .= $this->addAliases(); $code .= <<<EOF } EOF; return $code; } /** * Adds the constructor for a frozen container. * * @return string */ private function addFrozenConstructor() { $code = <<<EOF /** * Constructor. */ public function __construct() { EOF; if ($this->container->getParameterBag()->all()) { $code .= "\n \$this->parameters = \$this->getDefaultParameters();\n"; } $code .= <<<EOF \$this->services = \$this->scopedServices = \$this->scopeStacks = array(); \$this->set('service_container', \$this); EOF; $code .= "\n"; if (count($scopes = $this->container->getScopes()) > 0) { $code .= " \$this->scopes = ".$this->dumpValue($scopes).";\n"; $code .= " \$this->scopeChildren = ".$this->dumpValue($this->container->getScopeChildren()).";\n"; } else { $code .= " \$this->scopes = array();\n"; $code .= " \$this->scopeChildren = array();\n"; } $code .= $this->addMethodMap(); $code .= $this->addAliases(); $code .= <<<EOF } EOF; return $code; } /** * Adds the methodMap property definition * * @return string */ private function addMethodMap() { if (!$definitions = $this->container->getDefinitions()) { return ''; } $code = " \$this->methodMap = array(\n"; ksort($definitions); foreach ($definitions as $id => $definition) { $code .= ' '.var_export($id, true).' => '.var_export('get'.$this->camelize($id).'Service', true).",\n"; } return $code . " );\n"; } /** * Adds the aliases property definition * * @return string */ private function addAliases() { if (!$aliases = $this->container->getAliases()) { if ($this->container->isFrozen()) { return "\n \$this->aliases = array();\n"; } else { return ''; } } $code = " \$this->aliases = array(\n"; ksort($aliases); foreach ($aliases as $alias => $id) { $id = (string) $id; while (isset($aliases[$id])) { $id = (string) $aliases[$id]; } $code .= ' '.var_export($alias, true).' => '.var_export($id, true).",\n"; } return $code . " );\n"; } /** * Adds default parameters method. * * @return string */ private function addDefaultParametersMethod() { if (!$this->container->getParameterBag()->all()) { return ''; } $parameters = $this->exportParameters($this->container->getParameterBag()->all()); $code = ''; if ($this->container->isFrozen()) { $code .= <<<EOF /** * {@inheritdoc} */ public function getParameter(\$name) { \$name = strtolower(\$name); if (!(isset(\$this->parameters[\$name]) || array_key_exists(\$name, \$this->parameters))) { throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', \$name)); } return \$this->parameters[\$name]; } /** * {@inheritdoc} */ public function hasParameter(\$name) { \$name = strtolower(\$name); return isset(\$this->parameters[\$name]) || array_key_exists(\$name, \$this->parameters); } /** * {@inheritdoc} */ public function setParameter(\$name, \$value) { throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); } /** * {@inheritDoc} */ public function getParameterBag() { if (null === \$this->parameterBag) { \$this->parameterBag = new FrozenParameterBag(\$this->parameters); } return \$this->parameterBag; } EOF; } $code .= <<<EOF /** * Gets the default parameters. * * @return array An array of the default parameters */ protected function getDefaultParameters() { return $parameters; } EOF; return $code; } /** * Exports parameters. * * @param array $parameters * @param string $path * @param integer $indent * * @return string * * @throws InvalidArgumentException */ private function exportParameters($parameters, $path = '', $indent = 12) { $php = array(); foreach ($parameters as $key => $value) { if (is_array($value)) { $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4); } elseif ($value instanceof Variable) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key)); } elseif ($value instanceof Definition) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".', $value->getClass(), $path.'/'.$key)); } elseif ($value instanceof Reference) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").', $value, $path.'/'.$key)); } else { $value = var_export($value, true); } $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), var_export($key, true), $value); } return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4)); } /** * Ends the class definition. * * @return string */ private function endClass() { return <<<EOF } EOF; } /** * Wraps the service conditionals. * * @param string $value * @param string $code * * @return string */ private function wrapServiceConditionals($value, $code) { if (!$services = ContainerBuilder::getServiceConditionals($value)) { return $code; } $conditions = array(); foreach ($services as $service) { $conditions[] = sprintf("\$this->has('%s')", $service); } // re-indent the wrapped code $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code))); return sprintf(" if (%s) {\n%s }\n", implode(' && ', $conditions), $code); } /** * Builds service calls from arguments. * * @param array $arguments * @param array &$calls By reference * @param array &$behavior By reference */ private function getServiceCallsFromArguments(array $arguments, array &$calls, array &$behavior) { foreach ($arguments as $argument) { if (is_array($argument)) { $this->getServiceCallsFromArguments($argument, $calls, $behavior); } elseif ($argument instanceof Reference) { $id = (string) $argument; if (!isset($calls[$id])) { $calls[$id] = 0; } if (!isset($behavior[$id])) { $behavior[$id] = $argument->getInvalidBehavior(); } elseif (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) { $behavior[$id] = $argument->getInvalidBehavior(); } $calls[$id] += 1; } } } /** * Returns the inline definition. * * @param Definition $definition * * @return array */ private function getInlinedDefinitions(Definition $definition) { if (false === $this->inlinedDefinitions->contains($definition)) { $definitions = array_merge( $this->getDefinitionsFromArguments($definition->getArguments()), $this->getDefinitionsFromArguments($definition->getMethodCalls()), $this->getDefinitionsFromArguments($definition->getProperties()) ); $this->inlinedDefinitions->offsetSet($definition, $definitions); return $definitions; } return $this->inlinedDefinitions->offsetGet($definition); } /** * Gets the definition from arguments. * * @param array $arguments * * @return array */ private function getDefinitionsFromArguments(array $arguments) { $definitions = array(); foreach ($arguments as $argument) { if (is_array($argument)) { $definitions = array_merge($definitions, $this->getDefinitionsFromArguments($argument)); } elseif ($argument instanceof Definition) { $definitions = array_merge( $definitions, $this->getInlinedDefinitions($argument), array($argument) ); } } return $definitions; } /** * Checks if a service id has a reference. * * @param string $id * @param array $arguments * @param Boolean $deep * @param array $visited * * @return Boolean */ private function hasReference($id, array $arguments, $deep = false, array $visited = array()) { foreach ($arguments as $argument) { if (is_array($argument)) { if ($this->hasReference($id, $argument, $deep, $visited)) { return true; } } elseif ($argument instanceof Reference) { $argumentId = (string) $argument; if ($id === $argumentId) { return true; } if ($deep && !isset($visited[$argumentId])) { $visited[$argumentId] = true; $service = $this->container->getDefinition($argumentId); $arguments = array_merge($service->getMethodCalls(), $service->getArguments(), $service->getProperties()); if ($this->hasReference($id, $arguments, $deep, $visited)) { return true; } } } } return false; } /** * Dumps values. * * @param array $value * @param Boolean $interpolate * * @return string * * @throws RuntimeException */ private function dumpValue($value, $interpolate = true) { if (is_array($value)) { $code = array(); foreach ($value as $k => $v) { $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)); } return sprintf('array(%s)', implode(', ', $code)); } elseif ($value instanceof Definition) { if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) { return $this->dumpValue($this->definitionVariables->offsetGet($value), $interpolate); } if (count($value->getMethodCalls()) > 0) { throw new RuntimeException('Cannot dump definitions which have method calls.'); } if (null !== $value->getConfigurator()) { throw new RuntimeException('Cannot dump definitions which have a configurator.'); } $arguments = array(); foreach ($value->getArguments() as $argument) { $arguments[] = $this->dumpValue($argument); } $class = $this->dumpValue($value->getClass()); if (false !== strpos($class, '$')) { throw new RuntimeException('Cannot dump definitions which have a variable class name.'); } if (null !== $value->getFactoryMethod()) { if (null !== $value->getFactoryClass()) { return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($value->getFactoryClass()), $value->getFactoryMethod(), count($arguments) > 0 ? ', '.implode(', ', $arguments) : ''); } elseif (null !== $value->getFactoryService()) { return sprintf("%s->%s(%s)", $this->getServiceCall($value->getFactoryService()), $value->getFactoryMethod(), implode(', ', $arguments)); } else { throw new RuntimeException('Cannot dump definitions which have factory method without factory service or factory class.'); } } return sprintf("new \\%s(%s)", substr(str_replace('\\\\', '\\', $class), 1, -1), implode(', ', $arguments)); } elseif ($value instanceof Variable) { return '$'.$value; } elseif ($value instanceof Reference) { if (null !== $this->referenceVariables && isset($this->referenceVariables[$id = (string) $value])) { return $this->dumpValue($this->referenceVariables[$id], $interpolate); } return $this->getServiceCall((string) $value, $value); } elseif ($value instanceof Expression) { return $this->getExpressionLanguage()->compile((string) $value, array('container')); } elseif ($value instanceof Parameter) { return $this->dumpParameter($value); } elseif (true === $interpolate && is_string($value)) { if (preg_match('/^%([^%]+)%$/', $value, $match)) { // we do this to deal with non string values (Boolean, integer, ...) // the preg_replace_callback converts them to strings return $this->dumpParameter(strtolower($match[1])); } else { $that = $this; $replaceParameters = function ($match) use ($that) { return "'.".$that->dumpParameter(strtolower($match[2])).".'"; }; $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, var_export($value, true))); return $code; } } elseif (is_object($value) || is_resource($value)) { throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); } else { return var_export($value, true); } } /** * Dumps a parameter * * @param string $name * * @return string */ public function dumpParameter($name) { if ($this->container->isFrozen() && $this->container->hasParameter($name)) { return $this->dumpValue($this->container->getParameter($name), false); } return sprintf("\$this->getParameter('%s')", strtolower($name)); } /** * Gets a service call * * @param string $id * @param Reference $reference * * @return string */ private function getServiceCall($id, Reference $reference = null) { if ('service_container' === $id) { return '$this'; } if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) { return sprintf('$this->get(\'%s\', ContainerInterface::NULL_ON_INVALID_REFERENCE)', $id); } else { if ($this->container->hasAlias($id)) { $id = (string) $this->container->getAlias($id); } return sprintf('$this->get(\'%s\')', $id); } } /** * Convert a service id to a valid PHP method name. * * @param string $id * * @return string * * @throws InvalidArgumentException */ private function camelize($id) { $name = Container::camelize($id); if (!preg_match('/^[a-zA-Z0-9_\x7f-\xff]+$/', $name)) { throw new InvalidArgumentException(sprintf('Service id "%s" cannot be converted to a valid PHP method name.', $id)); } return $name; } /** * Returns the next name to use * * @return string */ private function getNextVariableName() { $firstChars = self::FIRST_CHARS; $firstCharsLength = strlen($firstChars); $nonFirstChars = self::NON_FIRST_CHARS; $nonFirstCharsLength = strlen($nonFirstChars); while (true) { $name = ''; $i = $this->variableCount; if ('' === $name) { $name .= $firstChars[$i%$firstCharsLength]; $i = intval($i/$firstCharsLength); } while ($i > 0) { $i -= 1; $name .= $nonFirstChars[$i%$nonFirstCharsLength]; $i = intval($i/$nonFirstCharsLength); } $this->variableCount += 1; // check that the name is not reserved if (in_array($name, $this->reservedVariables, true)) { continue; } return $name; } } private function getExpressionLanguage() { if (null === $this->expressionLanguage) { if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); } $this->expressionLanguage = new ExpressionLanguage(); } return $this->expressionLanguage; } }
agpl-3.0
pgorod/SuiteCRM
modules/Meetings/metadata/subpanels/ForActivities.php
4855
<?php if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } /** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ $subpanel_layout = array( //Removed button because this layout def is a component of //the activities sub-panel. 'where' => "(meetings.status !='Held' AND meetings.status !='Not Held')", 'list_fields' => array( 'object_image'=>array( 'vname' => 'LBL_OBJECT_IMAGE', 'widget_class' => 'SubPanelIcon', 'width' => '2%', 'image2'=>'__VARIABLE', 'image2_ext_url_field'=>'displayed_url', ), 'name'=>array( 'vname' => 'LBL_LIST_SUBJECT', 'widget_class' => 'SubPanelDetailViewLink', 'width' => '42%', ), 'status'=>array( 'widget_class' => 'SubPanelActivitiesStatusField', 'vname' => 'LBL_LIST_STATUS', 'width' => '15%', ), 'contact_name'=>array( 'widget_class' => 'SubPanelDetailViewLink', 'target_record_key' => 'contact_id', 'target_module' => 'Contacts', 'module' => 'Contacts', 'vname' => 'LBL_LIST_CONTACT', 'width' => '11%', 'sortable'=>false, ), 'contact_id'=>array( 'usage'=>'query_only', ), 'contact_name_owner'=>array( 'usage'=>'query_only', 'force_exists'=>true ), 'contact_name_mod'=>array( 'usage'=>'query_only', 'force_exists'=>true ), 'date_end'=>array( 'vname' => 'LBL_LIST_DUE_DATE', 'width' => '10%', 'alias' => 'date_due', 'sort_by' => 'date_due' ), 'assigned_user_name' => array( 'name' => 'assigned_user_name', 'vname' => 'LBL_LIST_ASSIGNED_TO_NAME', 'widget_class' => 'SubPanelDetailViewLink', 'target_record_key' => 'assigned_user_id', 'target_module' => 'Employees', 'width' => '10%', ), 'edit_button'=>array( 'vname' => 'LBL_EDIT_BUTTON', 'widget_class' => 'SubPanelEditButton', 'width' => '2%', ), 'close_button'=>array( 'widget_class' => 'SubPanelCloseButton', 'vname' => 'LBL_LIST_CLOSE', 'sortable'=>false, 'width' => '6%', ), 'remove_button'=>array( 'vname' => 'LBL_REMOVE', 'widget_class' => 'SubPanelRemoveButton', 'width' => '2%', ), 'time_start'=>array( 'usage'=>'query_only', ), 'recurring_source'=>array( 'usage'=>'query_only', ), ), );
agpl-3.0
frodejohansen/codebrag
codebrag-ui/app/scripts/common/directives/savingStatus.js
1732
/** * Replaces EL text with correct value and toggle correct css class * usage <EL saving-status="status_property"></EL> */ angular.module('codebrag.common.directives') .directive('savingStatus', function($timeout) { var statusToText = { "pending": 'Saving...', "success": 'Saved', "failed": 'Something went wrong, not saved', allClasses: function() { return Object.keys(this); } }; var hideTimerHandler; return { restrict: 'A', link: function(scope, el, attrs) { scope.$watch(attrs.savingStatus, function(changedStatus) { if(changedStatus) { showStatusInfo(changedStatus); scheduleStatusInfoFadeOut(changedStatus); } }); function showStatusInfo(changedStatus) { $timeout.cancel(hideTimerHandler); removeStatusClasses(); el.addClass(changedStatus); el.text(statusToText[changedStatus]); el.show(); } function scheduleStatusInfoFadeOut(status) { if(status !== 'pending') { hideTimerHandler = $timeout(function() { el.fadeOut(); }, 2000); } } function removeStatusClasses() { statusToText.allClasses().forEach(function(clazz) { el.removeClass(clazz); }); } } }; });
agpl-3.0
esofthead/mycollab
mycollab-web/src/main/java/com/mycollab/vaadin/ui/AbstractOptionValComboBox.java
2614
/** * Copyright © MyCollab * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * <p> * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.vaadin.ui; import com.mycollab.common.domain.OptionVal; import com.mycollab.core.utils.StringUtils; import com.mycollab.vaadin.UserUIContext; import com.vaadin.data.Converter; import com.vaadin.data.Result; import com.vaadin.data.ValueContext; import com.vaadin.ui.ComboBox; import com.vaadin.ui.ItemCaptionGenerator; import java.util.List; /** * @author MyCollab Ltd * @since 5.1.1 */ public abstract class AbstractOptionValComboBox<E extends Enum<E>> extends ComboBox<OptionVal> implements Converter<OptionVal, String> { private Class<E> enumCls; private List<OptionVal> options; public AbstractOptionValComboBox(Class<E> enumCls) { this.enumCls = enumCls; this.setPageLength(20); this.setEmptySelectionAllowed(false); options = loadOptions(); this.setItems(options); this.setStyleGenerator(itemId -> { if (itemId != null) { return "" + itemId.hashCode(); } return null; }); this.setItemCaptionGenerator((ItemCaptionGenerator<OptionVal>) option -> { String value = option.getTypeval(); try { Enum anEnum = Enum.valueOf(enumCls, value); return StringUtils.trim(UserUIContext.getMessage(anEnum), 25, true); } catch (Exception e) { return StringUtils.trim(value, 25, true); } }); } abstract protected List<OptionVal> loadOptions(); @Override public Result<String> convertToModel(OptionVal value, ValueContext context) { return (value != null) ? Result.ok(value.getTypeval()) : Result.ok(null); } @Override public OptionVal convertToPresentation(String value, ValueContext context) { return options.stream().filter(option -> option.getTypeval().equals(value)).findFirst().orElse(null); } }
agpl-3.0
ThomasMiconi/htmresearch
projects/sequence_prediction/continuous_sequence/plotPerformance.py
17017
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from matplotlib import pyplot as plt from htmresearch.support.sequence_learning_utils import * import pandas as pd from pylab import rcParams from plot import ExperimentResult, plotAccuracy, computeSquareDeviation, computeLikelihood, plotLSTMresult from nupic.encoders.scalar import ScalarEncoder as NupicScalarEncoder rcParams.update({'figure.autolayout': True}) rcParams.update({'figure.facecolor': 'white'}) rcParams.update({'ytick.labelsize': 8}) rcParams.update({'figure.figsize': (12, 6)}) import matplotlib as mpl mpl.rcParams['pdf.fonttype'] = 42 plt.ion() plt.close('all') window = 960 skipTrain = 10000 figPath = './result/' def getDatetimeAxis(): """ use datetime as x-axis """ dataSet = 'nyc_taxi' filePath = './data/' + dataSet + '.csv' data = pd.read_csv(filePath, header=0, skiprows=[1, 2], names=['datetime', 'value', 'timeofday', 'dayofweek']) xaxisDate = pd.to_datetime(data['datetime']) return xaxisDate def computeAltMAPE(truth, prediction, startFrom=0): return np.nanmean(np.abs(truth[startFrom:] - prediction[startFrom:]))/np.nanmean(np.abs(truth[startFrom:])) def computeNRMSE(truth, prediction, startFrom=0): squareDeviation = computeSquareDeviation(prediction, truth) squareDeviation[:startFrom] = None return np.sqrt(np.nanmean(squareDeviation))/np.nanstd(truth) def loadExperimentResult(filePath): expResult = pd.read_csv(filePath, header=0, skiprows=[1, 2], names=['step', 'value', 'prediction5']) groundTruth = np.roll(expResult['value'], -5) prediction5step = np.array(expResult['prediction5']) return (groundTruth, prediction5step) if __name__ == "__main__": xaxisDate = getDatetimeAxis() expResult = ExperimentResult('results/nyc_taxi_experiment_continuous/learning_window6001.0/') # ### Figure 1: Continuous vs Batch LSTM # fig = plt.figure() # # NRMSE_StaticLSTM = plotLSTMresult('results/nyc_taxi_experiment_one_shot/', # # window, xaxis=xaxis_datetime, label='static lstm') # (nrmseLSTM6000, expResultLSTM6000) = \ # plotLSTMresult('results/nyc_taxi_experiment_continuous/learning_window6001.0/', # window, xaxis=xaxisDate, label='continuous LSTM-6000') # plt.legend() # plt.savefig(figPath + 'continuousVsbatch.pdf') # ### Figure 2: Continuous LSTM with different window size fig = plt.figure() (nrmseLSTM1000, expResultLSTM1000) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous/learning_window1001.0/', window, xaxis=xaxisDate, label='continuous LSTM-1000') (nrmseLSTM3000, expResultLSTM3000) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous/learning_window3001.0/', window, xaxis=xaxisDate, label='continuous LSTM-3000') (nrmseLSTM6000, expResultLSTM6000) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous/learning_window6001.0/', window, xaxis=xaxisDate, label='continuous LSTM-6000') (nrmseLSTMonline, expResultLSTMonline) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous_online/learning_window100.0/', window, xaxis=xaxisDate, label='continuous LSTM-online') dataSet = 'nyc_taxi' filePath = './prediction/' + dataSet + '_TM_pred.csv' (tmTruth, tmPrediction) = loadExperimentResult('./prediction/' + dataSet + '_TM_pred.csv') squareDeviation = computeSquareDeviation(tmPrediction, tmTruth) squareDeviation[:skipTrain] = None nrmseTM = plotAccuracy((squareDeviation, xaxisDate), tmTruth, window=window, errorType='square_deviation', label='TM') (esnTruth, esnPrediction) = loadExperimentResult('./prediction/' + dataSet + '_esn_online_pred.csv') squareDeviation = computeSquareDeviation(esnPrediction, esnTruth) squareDeviation[:skipTrain] = None nrmseESN = plotAccuracy((squareDeviation, xaxisDate), tmTruth, window=window, errorType='square_deviation', label='ESN') (knnTruth, knnPrediction) = loadExperimentResult('./prediction/' + dataSet + '_plainKNN_pred.csv') squareDeviation = computeSquareDeviation(knnPrediction, knnTruth) squareDeviation[:skipTrain] = None nrmseKNN = plotAccuracy((squareDeviation, xaxisDate), tmTruth, window=window, errorType='square_deviation', label='KNN') (arimaTruth, arimaPrediction) = loadExperimentResult('./prediction/' + dataSet + '_ARIMA_pred.csv') squareDeviation = computeSquareDeviation(arimaPrediction, arimaTruth) squareDeviation[:skipTrain] = None nrmseARIMA = plotAccuracy((squareDeviation, xaxisDate), arimaTruth, window=window, errorType='square_deviation', label='ARIMA') (adaptiveFilterTruth, adaptiveFilterPrediction) = loadExperimentResult('./prediction/' + dataSet + '_adaptiveFilter_pred.csv') squareDeviation = computeSquareDeviation(adaptiveFilterPrediction, adaptiveFilterTruth) squareDeviation[:skipTrain] = None nrmseAdaptiveFilter = plotAccuracy((squareDeviation, xaxisDate), adaptiveFilterTruth, window=window, errorType='square_deviation', label='AdaptiveFilter') (tdnnTruth, tdnnPrediction) = loadExperimentResult('./prediction/' + dataSet + '_tdnn_pred.csv') squareDeviation = computeSquareDeviation(tdnnPrediction, tdnnTruth) squareDeviation[:skipTrain] = None nrmseTDNN = plotAccuracy((squareDeviation, xaxisDate), tdnnTruth, window=window, errorType='square_deviation', label='TDNN') (elmTruth, elmPrediction) = loadExperimentResult('./prediction/' + dataSet + '_elm_pred.csv') squareDeviation = computeSquareDeviation(elmPrediction, elmTruth) squareDeviation[:skipTrain] = None nrmseELM = plotAccuracy((squareDeviation, xaxisDate), elmTruth, window=window, errorType='square_deviation', label='Extreme Learning Machine') shiftPrediction = np.roll(tmTruth, 5).astype('float32') squareDeviation = computeSquareDeviation(shiftPrediction, tmTruth) squareDeviation[:skipTrain] = None nrmseShift = plotAccuracy((squareDeviation, xaxisDate), tmTruth, window=window, errorType='square_deviation', label='Shift') plt.legend() plt.savefig(figPath + 'continuous.pdf') ### Figure 3: Continuous LSTM with different window size using the likelihood metric # fig = plt.figure() # # negLL_StaticLSTM = \ # # plotLSTMresult('results/nyc_taxi_experiment_one_shot_likelihood/', # # window, xaxis=xaxis_datetime, label='static LSTM ') # # plt.clf() # (negLLLSTM1000, expResultLSTM1000negLL) = \ # plotLSTMresult('results/nyc_taxi_experiment_continuous_likelihood/learning_window1001.0/', # window, xaxis=xaxisDate, label='continuous LSTM-1000') # # (negLLLSTM3000, expResultLSTM3000negLL) = \ # plotLSTMresult('results/nyc_taxi_experiment_continuous_likelihood/learning_window3001.0/', # window, xaxis=xaxisDate, label='continuous LSTM-3000') # # (negLLLSTM6000, expResultLSTM6000negLL) = \ # plotLSTMresult('results/nyc_taxi_experiment_continuous_likelihood/learning_window6001.0/', # window, xaxis=xaxisDate, label='continuous LSTM-6000') # # dataSet = 'nyc_taxi' # tm_prediction = np.load('./result/'+dataSet+'TMprediction.npy') # tmTruth = np.load('./result/' + dataSet + 'TMtruth.npy') # # encoder = NupicScalarEncoder(w=1, minval=0, maxval=40000, n=22, forced=True) # negLL = computeLikelihood(tm_prediction, tmTruth, encoder) # negLL[:skipTrain] = None # negLLTM = plotAccuracy((negLL, xaxisDate), tmTruth, # window=window, errorType='negLL', label='TM') # plt.legend() # plt.savefig(figPath + 'continuous_likelihood.pdf') ### Figure 4: Continuous LSTM with different window size using the likelihood metric fig = plt.figure() plt.clf() (negLLLSTM1000, expResultLSTM1000negLL) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous_likelihood/learning_window1001.0/', window, xaxis=xaxisDate, label='continuous LSTM-1000') (negLLLSTM3000, expResultLSTM3000negLL) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous_likelihood/learning_window3001.0/', window, xaxis=xaxisDate, label='continuous LSTM-3000') (negLLLSTM6000, expResultLSTM6000negLL) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous_likelihood/learning_window6001.0/', window, xaxis=xaxisDate, label='continuous LSTM-6000') (negLLLSTMOnline, expResultLSTMOnlinenegLL) = plotLSTMresult( 'results/nyc_taxi_experiment_continuous_likelihood_online/learning_window200.0/', window, xaxis=xaxisDate, label='continuous LSTM-online') dataSet = 'nyc_taxi' tmPredictionLL = np.load('./result/'+dataSet+'TMprediction.npy') tmTruth = np.load('./result/' + dataSet + 'TMtruth.npy') encoder = NupicScalarEncoder(w=1, minval=0, maxval=40000, n=22, forced=True) negLL = computeLikelihood(tmPredictionLL, tmTruth, encoder) negLL[:skipTrain] = None negLLTM = plotAccuracy((negLL, xaxisDate), tmTruth, window=window, errorType='negLL', label='TM') plt.legend() plt.savefig(figPath + 'continuous_likelihood.pdf') startFrom = skipTrain altMAPELSTM6000 = computeAltMAPE(expResultLSTM6000.truth, expResultLSTM6000.predictions, startFrom) altMAPELSTM3000 = computeAltMAPE(expResultLSTM3000.truth, expResultLSTM3000.predictions, startFrom) altMAPELSTM1000 = computeAltMAPE(expResultLSTM1000.truth, expResultLSTM1000.predictions, startFrom) altMAPELSTMonline = computeAltMAPE(expResultLSTMonline.truth, expResultLSTMonline.predictions, startFrom) altMAPETM = computeAltMAPE(tmTruth, tmPrediction, startFrom) altMAPEARIMA = computeAltMAPE(arimaTruth, arimaPrediction, startFrom) altMAPEESN = computeAltMAPE(esnTruth, esnPrediction, startFrom) altMAPEKNN = computeAltMAPE(knnTruth, knnPrediction, startFrom) altMAPEShift = computeAltMAPE(tmTruth, shiftPrediction, startFrom) altMAPEAdaptiveFilter = computeAltMAPE(tmTruth, adaptiveFilterPrediction, startFrom) altMAPEELM = computeAltMAPE(elmTruth, elmPrediction, startFrom) altMAPETDNN = computeAltMAPE(tdnnTruth, tdnnPrediction, startFrom) truth = tmTruth nrmseShiftMean = np.sqrt(np.nanmean(nrmseShift)) / np.nanstd(truth) nrmseARIMAmean = np.sqrt(np.nanmean(nrmseARIMA)) / np.nanstd(truth) nrmseESNmean = np.sqrt(np.nanmean(nrmseESN)) / np.nanstd(truth) nrmseKNNmean = np.sqrt(np.nanmean(nrmseKNN)) / np.nanstd(truth) nrmseTMmean = np.sqrt(np.nanmean(nrmseTM)) / np.nanstd(truth) nrmseELMmean = np.sqrt(np.nanmean(nrmseELM)) / np.nanstd(truth) nrmseTDNNmean = np.sqrt(np.nanmean(nrmseTDNN)) / np.nanstd(truth) nrmseLSTM1000mean = np.sqrt(np.nanmean(nrmseLSTM1000)) / np.nanstd(truth) nrmseLSTM3000mean = np.sqrt(np.nanmean(nrmseLSTM3000)) / np.nanstd(truth) nrmseLSTM6000mean = np.sqrt(np.nanmean(nrmseLSTM6000)) / np.nanstd(truth) nrmseLSTMonlinemean = np.sqrt(np.nanmean(nrmseLSTMonline)) / np.nanstd(truth) fig, ax = plt.subplots(nrows=1, ncols=3) inds = np.arange(9) ax1 = ax[0] width = 0.5 ax1.bar(inds, [nrmseARIMAmean, nrmseELMmean, nrmseTDNNmean, nrmseESNmean, nrmseLSTMonlinemean, nrmseLSTM1000mean, nrmseLSTM3000mean, nrmseLSTM6000mean, nrmseTMmean], width=width) ax1.set_xticks(inds+width/2) ax1.set_ylabel('NRMSE') ax1.set_xlim([inds[0]-width*.6, inds[-1]+width*1.4]) ax1.set_xticklabels( ('ARIMA', 'ELM', 'TDNN', 'ESN', 'LSTM-online', 'LSTM1000', 'LSTM3000', 'LSTM6000', 'HTM') ) for tick in ax1.xaxis.get_major_ticks(): tick.label.set_rotation('vertical') ax3 = ax[1] ax3.bar(inds, [altMAPEARIMA, altMAPEELM, altMAPETDNN, altMAPEESN, altMAPELSTMonline, altMAPELSTM1000, altMAPELSTM3000, altMAPELSTM6000, altMAPETM], width=width, color='b') ax3.set_xticks(inds+width/2) ax3.set_xlim([inds[0]-width*.6, inds[-1]+width*1.4]) ax3.set_ylabel('MAPE') ax3.set_xticklabels( ('ARIMA', 'ELM', 'TDNN', 'ESN', 'LSTM-online', 'LSTM1000', 'LSTM3000', 'LSTM6000', 'HTM') ) for tick in ax3.xaxis.get_major_ticks(): tick.label.set_rotation('vertical') ax2 = ax[2] ax2.set_ylabel('Negative Log-likelihood') ax2.bar(inds, [np.nanmean(negLLLSTMOnline), np.nanmean(negLLLSTM1000), np.nanmean(negLLLSTM3000), np.nanmean(negLLLSTM6000), np.nanmean(negLLTM), 0, 0, 0, 0], width=width, color='b') ax2.set_xticks(inds+width/2) ax2.set_xlim([inds[0]-width*.6, inds[-1]+width*1.4]) ax2.set_ylim([0, 2.0]) ax2.set_xticklabels(('LSTM-online', 'LSTM1000', 'LSTM3000', 'LSTM6000', 'HTM', '', '', '')) for tick in ax2.xaxis.get_major_ticks(): tick.label.set_rotation('vertical') plt.savefig(figPath + 'model_performance_summary_alternative.pdf') fig, ax = plt.subplots(nrows=1, ncols=3) inds = np.arange(6) ax1 = ax[0] width = 0.5 ax1.bar(inds, [nrmseELMmean, nrmseESNmean, nrmseLSTM1000mean, nrmseLSTM3000mean, nrmseLSTM6000mean, nrmseTMmean], width=width) ax1.set_xticks(inds+width/2) ax1.set_ylabel('NRMSE') ax1.set_xlim([inds[0]-width*.6, inds[-1]+width*1.4]) ax1.set_xticklabels( ('ELM', 'ESN', 'LSTM1000', 'LSTM3000', 'LSTM6000', 'HTM') ) for tick in ax1.xaxis.get_major_ticks(): tick.label.set_rotation('vertical') ax3 = ax[1] ax3.bar(inds, [altMAPEELM, altMAPEESN, altMAPELSTM1000, altMAPELSTM3000, altMAPELSTM6000, altMAPETM], width=width, color='b') ax3.set_xticks(inds+width/2) ax3.set_xlim([inds[0]-width*.6, inds[-1]+width*1.4]) ax3.set_ylabel('MAPE') ax3.set_xticklabels( ('ELM', 'ESN', 'LSTM1000', 'LSTM3000', 'LSTM6000', 'HTM') ) for tick in ax3.xaxis.get_major_ticks(): tick.label.set_rotation('vertical') plt.savefig(figPath + 'model_performance_summary_neural_networks.pdf') ### Figure 6: # fig = plt.figure(6) # plt.plot(xaxis_datetime, tm_truth, label='Before') # plt.plot(xaxis_datetime, tm_truth_perturb, label='After') # plt.xlim([xaxis_datetime[13050], xaxis_datetime[13480]]) # plt.ylabel('30min Passenger Count') # plt.legend() # plt.savefig(figPath + 'example_perturbed_data.pdf') ### Plot Example Data Segments import datetime from matplotlib.dates import DayLocator, HourLocator, DateFormatter fig, ax = plt.subplots() ax.plot(xaxisDate, tmTruth, 'k-o') ax.xaxis.set_major_locator( DayLocator() ) ax.xaxis.set_minor_locator( HourLocator(range(0,25,6)) ) ax.xaxis.set_major_formatter( DateFormatter('%Y-%m-%d') ) ax.set_xlim([xaxisDate[14060], xaxisDate[14400]]) yticklabel = ax.get_yticks()/1000 new_yticklabel = [] for i in range(len(yticklabel)): new_yticklabel.append( str(int(yticklabel[i]))+' k') ax.set_yticklabels(new_yticklabel) ax.set_ylim([0, 30000]) ax.set_ylabel('Passenger Count in 30 min window') plt.savefig(figPath + 'example_data.pdf')
agpl-3.0
rafamanzo/mezuro-travis
test/unit/block_test.rb
4804
require File.dirname(__FILE__) + '/../test_helper' class BlockTest < ActiveSupport::TestCase should 'describe itself' do assert_kind_of String, Block.description end should 'access owner through box' do user = create_user('testinguser').person box = fast_create(Box, :owner_id => user, :owner_type => 'Person') block = Block.new block.box = box block.save! assert_equal user, block.owner end should 'have no owner when there is no box' do assert_nil Block.new.owner end should 'provide no footer by default' do assert_nil Block.new.footer end should 'provide an empty default title' do assert_equal '', Block.new.default_title end should 'be editable by default' do assert Block.new.editable? end should 'have default titles' do b = Block.new b.expects(:default_title).returns('my title') assert_equal 'my title', b.title end should 'have default view_title ' do b = Block.new b.expects(:title).returns('my title') assert_equal 'my title', b.view_title end should 'be cacheable' do b = Block.new assert b.cacheable? end should 'list enabled blocks' do block1 = fast_create(Block, :title => 'test 1') block2 = fast_create(Block, :title => 'test 2', :enabled => false) assert_includes Block.enabled, block1 assert_not_includes Block.enabled, block2 end should 'be displayed everywhere by default' do assert_equal true, Block.new.visible? end should 'not display when set to hidden' do assert_equal false, Block.new(:display => 'never').visible? assert_equal false, Block.new(:display => 'never').visible?(:article => Article.new) end should 'be able to be displayed only in the homepage' do profile = Profile.new home_page = Article.new profile.home_page = home_page block = Block.new(:display => 'home_page_only') block.stubs(:owner).returns(profile) assert_equal true, block.visible?(:article => home_page) assert_equal false, block.visible?(:article => Article.new) end should 'be able to be displayed only in the homepage (index) of the environment' do block = Block.new(:display => 'home_page_only') assert_equal true, block.visible?(:article => nil, :request_path => '/') assert_equal false, block.visible?(:article => nil) end should 'be able to be displayed everywhere except in the homepage' do profile = Profile.new home_page = Article.new profile.home_page = home_page block = Block.new(:display => 'except_home_page') block.stubs(:owner).returns(profile) assert_equal false, block.visible?(:article => home_page) assert_equal true, block.visible?(:article => Article.new) end should 'be able to be displayed everywhere except on profile index' do profile = Profile.new(:identifier => 'testinguser') block = Block.new(:display => 'except_home_page') block.stubs(:owner).returns(profile) assert_equal false, block.visible?(:article => nil, :request_path => '/testinguser') assert_equal true, block.visible?(:article => nil) end should 'be able to save display setting' do user = create_user('testinguser').person box = fast_create(Box, :owner_id => user.id, :owner_type => 'Profile') block = create(Block, :display => 'never', :box_id => box.id) block.reload assert_equal 'never', block.display end should 'be able to update display setting' do user = create_user('testinguser').person box = fast_create(Box, :owner_id => user.id, :owner_type => 'Profile') block = create(Block, :display => 'never', :box_id => box.id) assert block.update_attributes!(:display => 'always') block.reload assert_equal 'always', block.display end should 'display block in all languages by default' do profile = Profile.new block = Block.new block.stubs(:owner).returns(profile) assert_equal 'all', block.language end should 'be able to be displayed in all languages' do profile = Profile.new block = Block.new(:language => 'all') block.stubs(:owner).returns(profile) assert_equal true, block.visible?(:locale => 'pt') assert_equal true, block.visible?(:locale => 'en') end should 'be able to be displayed only in the selected language' do profile = Profile.new block = Block.new(:language => 'pt') block.stubs(:owner).returns(profile) assert_equal true, block.visible?(:locale => 'pt') assert_equal false, block.visible?(:locale => 'en') end should 'delegate environment to box' do box = fast_create(Box, :owner_id => fast_create(Profile).id) block = Block.new(:box => box) box.stubs(:environment).returns(Environment.default) assert_equal box.environment, block.environment end end
agpl-3.0
liveblog/liveblog
client/app/scripts/liveblog-edit/directives/select-text-on-click.js
240
export default function selectTextOnClick() { return { link: function(scope, elem, attrs) { elem.bind('click', () => { elem.focus(); elem.select(); }); }, }; }
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/object/building/corellia/filler_historic_24x16_s01.lua
2260
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_building_corellia_filler_historic_24x16_s01 = object_building_corellia_shared_filler_historic_24x16_s01:new { } ObjectTemplates:addTemplate(object_building_corellia_filler_historic_24x16_s01, "object/building/corellia/filler_historic_24x16_s01.iff")
agpl-3.0
ppericard/matamog
scripts/generate_scaffolding_blast.py
5040
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse from collections import defaultdict def read_tab_file_handle_sorted(tab_file_handle, factor_index=0): """ Parse a tab file (sorted by a column) and return a generator """ previous_factor_id = '' factor_tab_list = list() # Reading tab file for line in tab_file_handle: l = line.strip() if l: tab = l.split() current_factor = tab[factor_index] # Yield the previous factor tab list if current_factor != previous_factor_id: if previous_factor_id: yield factor_tab_list factor_tab_list = list() factor_tab_list.append(tab) previous_factor_id = current_factor # Yield the last tab list yield factor_tab_list # Close tab file tab_file_handle.close() if __name__ == '__main__': # Arguments parsing parser = argparse.ArgumentParser(description='') # -i / --input_tab parser.add_argument('-i', '--input_tab', metavar='INBLAST', type=argparse.FileType('r'), default='-', help='Input blast tab file. ' 'Only best matches should be kept') # -o / --output_tab parser.add_argument('-o', '--output_tab', metavar='OUTBLAST', type=argparse.FileType('w'), default='-', help='Ouput filtered blast tab file') args = parser.parse_args() # Variables initialization tab_list_list = list() # Reading blast tab file for tab_list in read_tab_file_handle_sorted(args.input_tab, 0): query_id = tab_list[0][0] tab_list_list.append(sorted(tab_list, key=lambda x: x[1])) # Sort by specificity (decreasing match number) and then # by decreasing alignment length. So the first seen contigs # are the long specific ones tab_list_list.sort(key=lambda x: (len(x), -int(x[0][3]))) # kept_references_ids_set = set() fillers_tab_list_list = list() # Count refs ref_count_dict = defaultdict(int) for tab_list in tab_list_list: for tab in tab_list: ref_count_dict[tab[1]] += 1 # Init a buffer for the output file output_tab_buffer = list() # Start iterating while (len(tab_list_list)): # Deal with specific contigs tab_list_buffer = list() # Get most specific contig so far selected_tab_list = tab_list_list[0] #~ print(selected_tab_list) tab_list_buffer = tab_list_list[1:] # Get the alignment against the reference with the most alignments selected_tab_list.sort(key=lambda t: (-ref_count_dict[t[1]], t[1])) selected_tab = selected_tab_list[0] kept_references_ids_set.add(selected_tab[1]) # Add the matching ref id to the set # Write the alignment output_tab_buffer.append('\t'.join(selected_tab)) tab_list_list = tab_list_buffer tab_list_buffer = list() # Uses already known fillers fillers_tab_list_buffer = list() for tab_list in fillers_tab_list_list: # references_ids_set = frozenset(x[1] for x in tab_list) references_intersection = references_ids_set & kept_references_ids_set # tab_buffer = list() for tab in tab_list: reference_id = tab[1] if reference_id in references_intersection: output_tab_buffer.append('\t'.join(tab)) else: # Store the alignments not already used tab_buffer.append(tab) if tab_buffer: fillers_tab_list_buffer.append(tab_buffer) fillers_tab_list_list = fillers_tab_list_buffer fillers_tab_list_buffer = list() # Deal with new fillers for tab_list in tab_list_list: # references_ids_set = frozenset(x[1] for x in tab_list) references_intersection = references_ids_set & kept_references_ids_set # if len(references_intersection): # So fillers tab_buffer = list() for tab in tab_list: reference_id = tab[1] if reference_id in references_intersection: output_tab_buffer.append('\t'.join(tab)) else: # Store the alignments not already used tab_buffer.append(tab) if tab_buffer: fillers_tab_list_list.append(tab_buffer) else: # Still specific tab_list_buffer.append(tab_list) tab_list_list = tab_list_buffer tab_list_buffer = list() # Write output file for line in output_tab_buffer: args.output_tab.write('{}\n'.format(line))
agpl-3.0
WoWAnalyzer/WoWAnalyzer
src/interface/reducers/reportHistory.js
891
import { APPEND_REPORT_HISTORY } from 'interface/actions/reportHistory'; import Cookies from 'universal-cookie'; const MAX_ITEMS = 5; const cookies = new Cookies(); const COOKIE_NAME = 'REPORT_HISTORY'; const cookieOptions = { path: '/', maxAge: 86400 * 365, // 1 year }; const defaultState = cookies.get(COOKIE_NAME) || []; export default function reportHistory(state = defaultState, action) { switch (action.type) { case APPEND_REPORT_HISTORY: { let newState = [ ...state.filter((item) => item.code !== action.payload.code), // remove existing report with this code action.payload, ]; const numItems = newState.length; if (numItems > MAX_ITEMS) { newState = newState.slice(numItems - MAX_ITEMS); } cookies.set(COOKIE_NAME, newState, cookieOptions); return newState; } default: return state; } }
agpl-3.0
aldridged/gtg-sugar
modules/Roles/vardefs.php
4211
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $dictionary['Role'] = array('table' => 'roles' ,'fields' => array ( 'id' => array ( 'name' => 'id', 'vname' => 'LBL_ID', 'required'=>true, 'type' => 'id', 'reportable'=>false, ), 'date_entered' => array ( 'name' => 'date_entered', 'vname' => 'LBL_DATE_ENTERED', 'type' => 'datetime', 'required'=>true ), 'date_modified' => array ( 'name' => 'date_modified', 'vname' => 'LBL_DATE_MODIFIED', 'type' => 'datetime', 'required'=>true, ), 'modified_user_id' => array ( 'name' => 'modified_user_id', 'rname' => 'user_name', 'id_name' => 'modified_user_id', 'vname' => 'LBL_MODIFIED', 'type' => 'assigned_user_name', 'table' => 'modified_user_id_users', 'isnull' => 'false', 'dbType' => 'id', 'required'=> false, 'len' => 36, 'reportable'=>true, ), 'created_by' => array ( 'name' => 'created_by', 'rname' => 'user_name', 'id_name' => 'created_by', 'vname' => 'LBL_CREATED', 'type' => 'assigned_user_name', 'table' => 'created_by_users', 'isnull' => 'false', 'dbType' => 'id', 'len' => 36, ), 'name' => array ( 'name' => 'name', 'type' => 'varchar', 'vname' => 'LBL_NAME', 'len' => 150, 'importable' => 'required', ), 'description' => array ( 'name' => 'description', 'vname' => 'LBL_DESCRIPTION', 'type' => 'text', ), 'modules' => array ( 'name' => 'modules', 'vname' => 'LBL_MODULES', 'type' => 'text', ), 'deleted' => array ( 'name' => 'deleted', 'vname' => 'LBL_DELETED', 'type' => 'bool', 'reportable'=>false, ), 'users' => array ( 'name' => 'users', 'type' => 'link', 'relationship' => 'roles_users', 'source'=>'non-db', 'vname'=>'LBL_USERS', ), ) , 'indices' => array ( array('name' =>'rolespk', 'type' =>'primary', 'fields'=>array('id')), array('name' =>'idx_role_id_del', 'type' =>'index', 'fields'=>array('id', 'deleted')), ) ); ?>
agpl-3.0
HotChalk/canvas-lms
public/javascripts/fixed-data-table.js
215131
/** * FixedDataTable v0.5.0 * * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["FixedDataTable"] = factory(require("react"), require("react-dom")); else root["FixedDataTable"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_30__, __WEBPACK_EXTERNAL_MODULE_48__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(5); __webpack_require__(7); __webpack_require__(9); __webpack_require__(11); __webpack_require__(13); __webpack_require__(15); __webpack_require__(17); __webpack_require__(19); __webpack_require__(21); __webpack_require__(23); module.exports = __webpack_require__(25); /***/ }, /* 1 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 2 */, /* 3 */, /* 4 */, /* 5 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 6 */, /* 7 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 8 */, /* 9 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 10 */, /* 11 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 12 */, /* 13 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 14 */, /* 15 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 16 */, /* 17 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 18 */, /* 19 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 20 */, /* 21 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 22 */, /* 23 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 24 */, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableRoot */ 'use strict'; var FixedDataTable = __webpack_require__(26); var FixedDataTableColumn = __webpack_require__(32); var FixedDataTableColumnGroup = __webpack_require__(31); var FixedDataTableRoot = { Column: FixedDataTableColumn, ColumnGroup: FixedDataTableColumnGroup, Table: FixedDataTable }; FixedDataTableRoot.version = '0.5.0'; module.exports = FixedDataTableRoot; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTable.react * @typechecks */ /* jslint bitwise: true */ 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var FixedDataTableHelper = __webpack_require__(27); var React = __webpack_require__(29); var ReactComponentWithPureRenderMixin = __webpack_require__(33); var ReactWheelHandler = __webpack_require__(34); var Scrollbar = __webpack_require__(42); var FixedDataTableBufferedRows = __webpack_require__(56); var FixedDataTableColumnResizeHandle = __webpack_require__(71); var FixedDataTableRow = __webpack_require__(61); var FixedDataTableScrollHelper = __webpack_require__(72); var FixedDataTableWidthHelper = __webpack_require__(74); var cx = __webpack_require__(50); var debounceCore = __webpack_require__(75); var emptyFunction = __webpack_require__(35); var invariant = __webpack_require__(55); var joinClasses = __webpack_require__(70); var shallowEqual = __webpack_require__(76); var translateDOMPositionXY = __webpack_require__(51); var PropTypes = React.PropTypes; var ReactChildren = React.Children; var renderToString = FixedDataTableHelper.renderToString; var EMPTY_OBJECT = {}; var BORDER_HEIGHT = 1; /** * Data grid component with fixed or scrollable header and columns. * * The layout of the data table is as follows: * * ``` * +---------------------------------------------------+ * | Fixed Column Group | Scrollable Column Group | * | Header | Header | * | | | * +---------------------------------------------------+ * | | | * | Fixed Header Columns | Scrollable Header Columns | * | | | * +-----------------------+---------------------------+ * | | | * | Fixed Body Columns | Scrollable Body Columns | * | | | * +-----------------------+---------------------------+ * | | | * | Fixed Footer Columns | Scrollable Footer Columns | * | | | * +-----------------------+---------------------------+ * ``` * * - Fixed Column Group Header: These are the headers for a group * of columns if included in the table that do not scroll * vertically or horizontally. * * - Scrollable Column Group Header: The header for a group of columns * that do not move while scrolling vertically, but move horizontally * with the horizontal scrolling. * * - Fixed Header Columns: The header columns that do not move while scrolling * vertically or horizontally. * * - Scrollable Header Columns: The header columns that do not move * while scrolling vertically, but move horizontally with the horizontal * scrolling. * * - Fixed Body Columns: The body columns that do not move while scrolling * horizontally, but move vertically with the vertical scrolling. * * - Scrollable Body Columns: The body columns that move while scrolling * vertically or horizontally. */ var FixedDataTable = React.createClass({ displayName: 'FixedDataTable', propTypes: { /** * Pixel width of table. If all columns do not fit, * a horizontal scrollbar will appear. */ width: PropTypes.number.isRequired, /** * Pixel height of table. If all rows do not fit, * a vertical scrollbar will appear. * * Either `height` or `maxHeight` must be specified. */ height: PropTypes.number, /** * Maximum pixel height of table. If all rows do not fit, * a vertical scrollbar will appear. * * Either `height` or `maxHeight` must be specified. */ maxHeight: PropTypes.number, /** * Pixel height of table's owner, this is used in a managed scrolling * situation when you want to slide the table up from below the fold * without having to constantly update the height on every scroll tick. * Instead, vary this property on scroll. By using `ownerHeight`, we * over-render the table while making sure the footer and horizontal * scrollbar of the table are visible when the current space for the table * in view is smaller than the final, over-flowing height of table. It * allows us to avoid resizing and reflowing table when it is moving in the * view. * * This is used if `ownerHeight < height` (or `maxHeight`). */ ownerHeight: PropTypes.number, overflowX: PropTypes.oneOf(['hidden', 'auto']), overflowY: PropTypes.oneOf(['hidden', 'auto']), /** * Number of rows in the table. */ rowsCount: PropTypes.number.isRequired, /** * Pixel height of rows unless `rowHeightGetter` is specified and returns * different value. */ rowHeight: PropTypes.number.isRequired, /** * If specified, `rowHeightGetter(index)` is called for each row and the * returned value overrides `rowHeight` for particular row. */ rowHeightGetter: PropTypes.func, /** * To get rows to display in table, `rowGetter(index)` * is called. `rowGetter` should be smart enough to handle async * fetching of data and return temporary objects * while data is being fetched. */ rowGetter: PropTypes.func.isRequired, /** * To get any additional CSS classes that should be added to a row, * `rowClassNameGetter(index)` is called. */ rowClassNameGetter: PropTypes.func, /** * Pixel height of the column group header. */ groupHeaderHeight: PropTypes.number, /** * Pixel height of header. */ headerHeight: PropTypes.number.isRequired, /** * Function that is called to get the data for the header row. * If the function returns null, the header will be set to the * Column's label property. */ headerDataGetter: PropTypes.func, /** * Pixel height of footer. */ footerHeight: PropTypes.number, /** * DEPRECATED - use footerDataGetter instead. * Data that will be passed to footer cell renderers. */ footerData: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), /** * Function that is called to get the data for the footer row. */ footerDataGetter: PropTypes.func, /** * Value of horizontal scroll. */ scrollLeft: PropTypes.number, /** * Index of column to scroll to. */ scrollToColumn: PropTypes.number, /** * Value of vertical scroll. */ scrollTop: PropTypes.number, /** * Index of row to scroll to. */ scrollToRow: PropTypes.number, /** * Callback that is called when scrolling starts with current horizontal * and vertical scroll values. */ onScrollStart: PropTypes.func, /** * Callback that is called when scrolling ends or stops with new horizontal * and vertical scroll values. */ onScrollEnd: PropTypes.func, /** * Callback that is called when `rowHeightGetter` returns a different height * for a row than the `rowHeight` prop. This is necessary because initially * table estimates heights of some parts of the content. */ onContentHeightChange: PropTypes.func, /** * Callback that is called when a row is clicked. */ onRowClick: PropTypes.func, /** * Callback that is called when a row is double clicked. */ onRowDoubleClick: PropTypes.func, /** * Callback that is called when a mouse-down event happens on a row. */ onRowMouseDown: PropTypes.func, /** * Callback that is called when a mouse-enter event happens on a row. */ onRowMouseEnter: PropTypes.func, /** * Callback that is called when a mouse-leave event happens on a row. */ onRowMouseLeave: PropTypes.func, /** * Callback that is called when resizer has been released * and column needs to be updated. * * Required if the isResizable property is true on any column. * * ``` * function( * newColumnWidth: number, * dataKey: string, * ) * ``` */ onColumnResizeEndCallback: PropTypes.func, /** * Whether a column is currently being resized. */ isColumnResizing: PropTypes.bool }, getDefaultProps: function getDefaultProps() /*object*/{ return { footerHeight: 0, groupHeaderHeight: 0, headerHeight: 0, scrollLeft: 0, scrollTop: 0 }; }, getInitialState: function getInitialState() /*object*/{ var props = this.props; var viewportHeight = (props.height === undefined ? props.maxHeight : props.height) - (props.headerHeight || 0) - (props.footerHeight || 0) - (props.groupHeaderHeight || 0); this._scrollHelper = new FixedDataTableScrollHelper(props.rowsCount, props.rowHeight, viewportHeight, props.rowHeightGetter); if (props.scrollTop) { this._scrollHelper.scrollTo(props.scrollTop); } this._didScrollStop = debounceCore(this._didScrollStop, 160, this); return this._calculateState(this.props); }, componentWillMount: function componentWillMount() { var scrollToRow = this.props.scrollToRow; if (scrollToRow !== undefined && scrollToRow !== null) { this._rowToScrollTo = scrollToRow; } var scrollToColumn = this.props.scrollToColumn; if (scrollToColumn !== undefined && scrollToColumn !== null) { this._columnToScrollTo = scrollToColumn; } this._wheelHandler = new ReactWheelHandler(this._onWheel, this._shouldHandleWheelX, this._shouldHandleWheelY); }, _shouldHandleWheelX: function _shouldHandleWheelX( /*number*/delta) /*boolean*/{ if (this.props.overflowX === 'hidden') { return false; } delta = Math.round(delta); if (delta === 0) { return false; } return delta < 0 && this.state.scrollX > 0 || delta >= 0 && this.state.scrollX < this.state.maxScrollX; }, _shouldHandleWheelY: function _shouldHandleWheelY( /*number*/delta) /*boolean*/{ if (this.props.overflowY === 'hidden' || delta === 0) { return false; } delta = Math.round(delta); if (delta === 0) { return false; } return delta < 0 && this.state.scrollY > 0 || delta >= 0 && this.state.scrollY < this.state.maxScrollY; }, _reportContentHeight: function _reportContentHeight() { var scrollContentHeight = this.state.scrollContentHeight; var reservedHeight = this.state.reservedHeight; var requiredHeight = scrollContentHeight + reservedHeight; var contentHeight; var useMaxHeight = this.props.height === undefined; if (useMaxHeight && this.props.maxHeight > requiredHeight) { contentHeight = requiredHeight; } else if (this.state.height > requiredHeight && this.props.ownerHeight) { contentHeight = Math.max(requiredHeight, this.props.ownerHeight); } else { contentHeight = this.state.height + this.state.maxScrollY; } if (contentHeight !== this._contentHeight && this.props.onContentHeightChange) { this.props.onContentHeightChange(contentHeight); } this._contentHeight = contentHeight; }, componentDidMount: function componentDidMount() { this._reportContentHeight(); }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/nextProps) { var scrollToRow = nextProps.scrollToRow; if (scrollToRow !== undefined && scrollToRow !== null) { this._rowToScrollTo = scrollToRow; } var scrollToColumn = nextProps.scrollToColumn; if (scrollToColumn !== undefined && scrollToColumn !== null) { this._columnToScrollTo = scrollToColumn; } var newOverflowX = nextProps.overflowX; var newOverflowY = nextProps.overflowY; if (newOverflowX !== this.props.overflowX || newOverflowY !== this.props.overflowY) { this._wheelHandler = new ReactWheelHandler(this._onWheel, newOverflowX !== 'hidden', // Should handle horizontal scroll newOverflowY !== 'hidden' // Should handle vertical scroll ); } this.setState(this._calculateState(nextProps, this.state)); }, componentDidUpdate: function componentDidUpdate() { this._reportContentHeight(); }, render: function render() /*object*/{ var state = this.state; var props = this.props; var groupHeader; if (state.useGroupHeader) { groupHeader = React.createElement(FixedDataTableRow, { key: 'group_header', className: joinClasses(cx('fixedDataTableLayout/header'), cx('public/fixedDataTable/header')), data: state.groupHeaderData, width: state.width, height: state.groupHeaderHeight, index: 0, zIndex: 1, offsetTop: 0, scrollLeft: state.scrollX, fixedColumns: state.groupHeaderFixedColumns, scrollableColumns: state.groupHeaderScrollableColumns }); } var maxScrollY = this.state.maxScrollY; var showScrollbarX = state.maxScrollX > 0 && state.overflowX !== 'hidden'; var showScrollbarY = maxScrollY > 0 && state.overflowY !== 'hidden'; var scrollbarXHeight = showScrollbarX ? Scrollbar.SIZE : 0; var scrollbarYHeight = state.height - scrollbarXHeight - 2 * BORDER_HEIGHT - state.footerHeight; var headerOffsetTop = state.useGroupHeader ? state.groupHeaderHeight : 0; var bodyOffsetTop = headerOffsetTop + state.headerHeight; scrollbarYHeight -= bodyOffsetTop; var bottomSectionOffset = 0; var footOffsetTop = props.maxHeight != null ? bodyOffsetTop + state.bodyHeight : bodyOffsetTop + scrollbarYHeight; var rowsContainerHeight = footOffsetTop + state.footerHeight; if (props.ownerHeight !== undefined && props.ownerHeight < state.height) { bottomSectionOffset = props.ownerHeight - state.height; footOffsetTop = Math.min(footOffsetTop, props.ownerHeight - state.footerHeight - scrollbarXHeight); scrollbarYHeight = Math.max(0, footOffsetTop - bodyOffsetTop); } var verticalScrollbar; if (showScrollbarY) { verticalScrollbar = React.createElement(Scrollbar, { size: scrollbarYHeight, contentSize: scrollbarYHeight + maxScrollY, onScroll: this._onVerticalScroll, verticalTop: bodyOffsetTop, position: state.scrollY }); } var horizontalScrollbar; if (showScrollbarX) { var scrollbarXWidth = state.width; horizontalScrollbar = React.createElement(HorizontalScrollbar, { contentSize: scrollbarXWidth + state.maxScrollX, offset: bottomSectionOffset, onScroll: this._onHorizontalScroll, position: state.scrollX, size: scrollbarXWidth }); } var dragKnob = React.createElement(FixedDataTableColumnResizeHandle, { height: state.height, initialWidth: state.columnResizingData.width || 0, minWidth: state.columnResizingData.minWidth || 0, maxWidth: state.columnResizingData.maxWidth || Number.MAX_VALUE, visible: !!state.isColumnResizing, leftOffset: state.columnResizingData.left || 0, knobHeight: state.headerHeight, initialEvent: state.columnResizingData.initialEvent, onColumnResizeEnd: props.onColumnResizeEndCallback, columnKey: state.columnResizingData.key }); var footer = null; if (state.footerHeight) { var footerData = props.footerDataGetter ? props.footerDataGetter() : props.footerData; footer = React.createElement(FixedDataTableRow, { key: 'footer', className: joinClasses(cx('fixedDataTableLayout/footer'), cx('public/fixedDataTable/footer')), data: footerData, fixedColumns: state.footFixedColumns, height: state.footerHeight, index: -1, zIndex: 1, offsetTop: footOffsetTop, scrollableColumns: state.footScrollableColumns, scrollLeft: state.scrollX, width: state.width }); } var rows = this._renderRows(bodyOffsetTop); var header = React.createElement(FixedDataTableRow, { key: 'header', className: joinClasses(cx('fixedDataTableLayout/header'), cx('public/fixedDataTable/header')), data: state.headData, width: state.width, height: state.headerHeight, index: -1, zIndex: 1, offsetTop: headerOffsetTop, scrollLeft: state.scrollX, fixedColumns: state.headFixedColumns, scrollableColumns: state.headScrollableColumns, onColumnResize: this._onColumnResize }); var topShadow; var bottomShadow; if (state.scrollY) { topShadow = React.createElement('div', { className: joinClasses(cx('fixedDataTableLayout/topShadow'), cx('public/fixedDataTable/topShadow')), style: { top: bodyOffsetTop } }); } if (state.ownerHeight != null && state.ownerHeight < state.height && state.scrollContentHeight + state.reservedHeight > state.ownerHeight || state.scrollY < maxScrollY) { bottomShadow = React.createElement('div', { className: joinClasses(cx('fixedDataTableLayout/bottomShadow'), cx('public/fixedDataTable/bottomShadow')), style: { top: footOffsetTop } }); } return React.createElement( 'div', { className: joinClasses(cx('fixedDataTableLayout/main'), cx('public/fixedDataTable/main')), onWheel: this._wheelHandler.onWheel, style: { height: state.height, width: state.width } }, React.createElement( 'div', { className: cx('fixedDataTableLayout/rowsContainer'), style: { height: rowsContainerHeight, width: state.width } }, dragKnob, groupHeader, header, rows, footer, topShadow, bottomShadow ), verticalScrollbar, horizontalScrollbar ); }, _renderRows: function _renderRows( /*number*/offsetTop) /*object*/{ var state = this.state; return React.createElement(FixedDataTableBufferedRows, { defaultRowHeight: state.rowHeight, firstRowIndex: state.firstRowIndex, firstRowOffset: state.firstRowOffset, fixedColumns: state.bodyFixedColumns, height: state.bodyHeight, offsetTop: offsetTop, onRowClick: state.onRowClick, onRowDoubleClick: state.onRowDoubleClick, onRowMouseDown: state.onRowMouseDown, onRowMouseEnter: state.onRowMouseEnter, onRowMouseLeave: state.onRowMouseLeave, rowClassNameGetter: state.rowClassNameGetter, rowsCount: state.rowsCount, rowGetter: state.rowGetter, rowHeightGetter: state.rowHeightGetter, scrollLeft: state.scrollX, scrollableColumns: state.bodyScrollableColumns, showLastRowBorder: true, width: state.width, rowPositionGetter: this._scrollHelper.getRowPosition }); }, /** * This is called when a cell that is in the header of a column has its * resizer knob clicked on. It displays the resizer and puts in the correct * location on the table. */ _onColumnResize: function _onColumnResize( /*number*/combinedWidth, /*number*/leftOffset, /*number*/cellWidth, /*?number*/cellMinWidth, /*?number*/cellMaxWidth, /*number|string*/columnKey, /*object*/event) { this.setState({ isColumnResizing: true, columnResizingData: { left: leftOffset + combinedWidth - cellWidth, width: cellWidth, minWidth: cellMinWidth, maxWidth: cellMaxWidth, initialEvent: { clientX: event.clientX, clientY: event.clientY, preventDefault: emptyFunction }, key: columnKey } }); }, _areColumnSettingsIdentical: function _areColumnSettingsIdentical(oldColumns, newColumns) { if (oldColumns.length !== newColumns.length) { return false; } for (var index = 0; index < oldColumns.length; ++index) { if (!shallowEqual(oldColumns[index].props, newColumns[index].props)) { return false; } } return true; }, _populateColumnsAndColumnData: function _populateColumnsAndColumnData(columns, columnGroups, oldState) { var canReuseColumnSettings = false; var canReuseColumnGroupSettings = false; if (oldState && oldState.columns) { canReuseColumnSettings = this._areColumnSettingsIdentical(columns, oldState.columns); } if (oldState && oldState.columnGroups && columnGroups) { canReuseColumnGroupSettings = this._areColumnSettingsIdentical(columnGroups, oldState.columnGroups); } var columnInfo = {}; if (canReuseColumnSettings) { columnInfo.bodyFixedColumns = oldState.bodyFixedColumns; columnInfo.bodyScrollableColumns = oldState.bodyScrollableColumns; columnInfo.headFixedColumns = oldState.headFixedColumns; columnInfo.headScrollableColumns = oldState.headScrollableColumns; columnInfo.footFixedColumns = oldState.footFixedColumns; columnInfo.footScrollableColumns = oldState.footScrollableColumns; } else { var bodyColumnTypes = this._splitColumnTypes(columns); columnInfo.bodyFixedColumns = bodyColumnTypes.fixed; columnInfo.bodyScrollableColumns = bodyColumnTypes.scrollable; var headColumnTypes = this._splitColumnTypes(this._createHeadColumns(columns)); columnInfo.headFixedColumns = headColumnTypes.fixed; columnInfo.headScrollableColumns = headColumnTypes.scrollable; var footColumnTypes = this._splitColumnTypes(this._createFootColumns(columns)); columnInfo.footFixedColumns = footColumnTypes.fixed; columnInfo.footScrollableColumns = footColumnTypes.scrollable; } if (canReuseColumnGroupSettings) { columnInfo.groupHeaderFixedColumns = oldState.groupHeaderFixedColumns; columnInfo.groupHeaderScrollableColumns = oldState.groupHeaderScrollableColumns; } else { if (columnGroups) { columnInfo.groupHeaderData = this._getGroupHeaderData(columnGroups); columnGroups = this._createGroupHeaderColumns(columnGroups); var groupHeaderColumnTypes = this._splitColumnTypes(columnGroups); columnInfo.groupHeaderFixedColumns = groupHeaderColumnTypes.fixed; columnInfo.groupHeaderScrollableColumns = groupHeaderColumnTypes.scrollable; } } columnInfo.headData = this._getHeadData(columns); return columnInfo; }, _calculateState: function _calculateState( /*object*/props, /*?object*/oldState) /*object*/{ invariant(props.height !== undefined || props.maxHeight !== undefined, 'You must set either a height or a maxHeight'); var children = []; ReactChildren.forEach(props.children, function (child, index) { if (child == null) { return; } invariant(child.type.__TableColumnGroup__ || child.type.__TableColumn__, 'child type should be <FixedDataTableColumn /> or ' + '<FixedDataTableColumnGroup />'); children.push(child); }); var useGroupHeader = false; if (children.length && children[0].type.__TableColumnGroup__) { useGroupHeader = true; } var firstRowIndex = oldState && oldState.firstRowIndex || 0; var firstRowOffset = oldState && oldState.firstRowOffset || 0; var scrollX, scrollY; if (oldState && props.overflowX !== 'hidden') { scrollX = oldState.scrollX; } else { scrollX = props.scrollLeft; } if (oldState && props.overflowY !== 'hidden') { scrollY = oldState.scrollY; } else { scrollState = this._scrollHelper.scrollTo(props.scrollTop); firstRowIndex = scrollState.index; firstRowOffset = scrollState.offset; scrollY = scrollState.position; } if (this._rowToScrollTo !== undefined) { scrollState = this._scrollHelper.scrollRowIntoView(this._rowToScrollTo); firstRowIndex = scrollState.index; firstRowOffset = scrollState.offset; scrollY = scrollState.position; delete this._rowToScrollTo; } var groupHeaderHeight = useGroupHeader ? props.groupHeaderHeight : 0; if (oldState && props.rowsCount !== oldState.rowsCount) { // Number of rows changed, try to scroll to the row from before the // change var viewportHeight = (props.height === undefined ? props.maxHeight : props.height) - (props.headerHeight || 0) - (props.footerHeight || 0) - (props.groupHeaderHeight || 0); this._scrollHelper = new FixedDataTableScrollHelper(props.rowsCount, props.rowHeight, viewportHeight, props.rowHeightGetter); var scrollState = this._scrollHelper.scrollToRow(firstRowIndex, firstRowOffset); firstRowIndex = scrollState.index; firstRowOffset = scrollState.offset; scrollY = scrollState.position; } else if (oldState && props.rowHeightGetter !== oldState.rowHeightGetter) { this._scrollHelper.setRowHeightGetter(props.rowHeightGetter); } var columnResizingData; if (props.isColumnResizing) { columnResizingData = oldState && oldState.columnResizingData; } else { columnResizingData = EMPTY_OBJECT; } var columns; var columnGroups; if (useGroupHeader) { var columnGroupSettings = FixedDataTableWidthHelper.adjustColumnGroupWidths(children, props.width); columns = columnGroupSettings.columns; columnGroups = columnGroupSettings.columnGroups; } else { columns = FixedDataTableWidthHelper.adjustColumnWidths(children, props.width); } var columnInfo = this._populateColumnsAndColumnData(columns, columnGroups, oldState); if (this._columnToScrollTo !== undefined) { // If selected column is a fixed column, don't scroll var fixedColumnsCount = columnInfo.bodyFixedColumns.length; if (this._columnToScrollTo >= fixedColumnsCount) { var totalFixedColumnsWidth = 0; var i, column; for (i = 0; i < columnInfo.bodyFixedColumns.length; ++i) { column = columnInfo.bodyFixedColumns[i]; totalFixedColumnsWidth += column.props.width; } var scrollableColumnIndex = Math.min(this._columnToScrollTo - fixedColumnsCount, columnInfo.bodyScrollableColumns.length - 1); var previousColumnsWidth = 0; for (i = 0; i < scrollableColumnIndex; ++i) { column = columnInfo.bodyScrollableColumns[i]; previousColumnsWidth += column.props.width; } var availableScrollWidth = props.width - totalFixedColumnsWidth; var selectedColumnWidth = columnInfo.bodyScrollableColumns[scrollableColumnIndex].props.width; var minAcceptableScrollPosition = previousColumnsWidth + selectedColumnWidth - availableScrollWidth; if (scrollX < minAcceptableScrollPosition) { scrollX = minAcceptableScrollPosition; } if (scrollX > previousColumnsWidth) { scrollX = previousColumnsWidth; } } delete this._columnToScrollTo; } var useMaxHeight = props.height === undefined; var height = Math.round(useMaxHeight ? props.maxHeight : props.height); var totalHeightReserved = props.footerHeight + props.headerHeight + groupHeaderHeight + 2 * BORDER_HEIGHT; var bodyHeight = height - totalHeightReserved; var scrollContentHeight = this._scrollHelper.getContentHeight(); var totalHeightNeeded = scrollContentHeight + totalHeightReserved; var scrollContentWidth = FixedDataTableWidthHelper.getTotalWidth(columns); var horizontalScrollbarVisible = scrollContentWidth > props.width && props.overflowX !== 'hidden'; if (horizontalScrollbarVisible) { bodyHeight -= Scrollbar.SIZE; totalHeightNeeded += Scrollbar.SIZE; totalHeightReserved += Scrollbar.SIZE; } var maxScrollX = Math.max(0, scrollContentWidth - props.width); var maxScrollY = Math.max(0, scrollContentHeight - bodyHeight); scrollX = Math.min(scrollX, maxScrollX); scrollY = Math.min(scrollY, maxScrollY); if (!maxScrollY) { // no vertical scrollbar necessary, use the totals we tracked so we // can shrink-to-fit vertically if (useMaxHeight) { height = totalHeightNeeded; } bodyHeight = totalHeightNeeded - totalHeightReserved; } this._scrollHelper.setViewportHeight(bodyHeight); // The order of elements in this object metters and bringing bodyHeight, // height or useGroupHeader to the top can break various features var newState = _extends({ isColumnResizing: oldState && oldState.isColumnResizing }, columnInfo, props, { columns: columns, columnGroups: columnGroups, columnResizingData: columnResizingData, firstRowIndex: firstRowIndex, firstRowOffset: firstRowOffset, horizontalScrollbarVisible: horizontalScrollbarVisible, maxScrollX: maxScrollX, maxScrollY: maxScrollY, reservedHeight: totalHeightReserved, scrollContentHeight: scrollContentHeight, scrollX: scrollX, scrollY: scrollY, // These properties may overwrite properties defined in // columnInfo and props bodyHeight: bodyHeight, height: height, groupHeaderHeight: groupHeaderHeight, useGroupHeader: useGroupHeader }); // Both `headData` and `groupHeaderData` are generated by // `FixedDataTable` will be passed to each header cell to render. // In order to prevent over-rendering the cells, we do not pass the // new `headData` or `groupHeaderData` // if they haven't changed. if (oldState) { if (oldState.headData && newState.headData && shallowEqual(oldState.headData, newState.headData)) { newState.headData = oldState.headData; } if (oldState.groupHeaderData && newState.groupHeaderData && shallowEqual(oldState.groupHeaderData, newState.groupHeaderData)) { newState.groupHeaderData = oldState.groupHeaderData; } } return newState; }, _createGroupHeaderColumns: function _createGroupHeaderColumns( /*array*/columnGroups) /*array*/{ var newColumnGroups = []; for (var i = 0; i < columnGroups.length; ++i) { newColumnGroups[i] = React.cloneElement(columnGroups[i], { dataKey: i, children: undefined, columnData: columnGroups[i].props.columnGroupData, cellRenderer: columnGroups[i].props.groupHeaderRenderer || renderToString, isHeaderCell: true }); } return newColumnGroups; }, _createHeadColumns: function _createHeadColumns( /*array*/columns) /*array*/{ var headColumns = []; for (var i = 0; i < columns.length; ++i) { var columnProps = columns[i].props; headColumns.push(React.cloneElement(columns[i], { cellRenderer: columnProps.headerRenderer || renderToString, columnData: columnProps.columnData, dataKey: columnProps.dataKey, isHeaderCell: true, label: columnProps.label })); } return headColumns; }, _createFootColumns: function _createFootColumns( /*array*/columns) /*array*/{ var footColumns = []; for (var i = 0; i < columns.length; ++i) { var columnProps = columns[i].props; footColumns.push(React.cloneElement(columns[i], { cellRenderer: columnProps.footerRenderer || renderToString, columnData: columnProps.columnData, dataKey: columnProps.dataKey, isFooterCell: true })); } return footColumns; }, _getHeadData: function _getHeadData( /*array*/columns) /*?object*/{ if (!this.props.headerDataGetter) { return null; } var headData = {}; for (var i = 0; i < columns.length; ++i) { var columnProps = columns[i].props; headData[columnProps.dataKey] = this.props.headerDataGetter(columnProps.dataKey); } return headData; }, _getGroupHeaderData: function _getGroupHeaderData( /*array*/columnGroups) /*array*/{ var groupHeaderData = []; for (var i = 0; i < columnGroups.length; ++i) { groupHeaderData[i] = columnGroups[i].props.label || ''; } return groupHeaderData; }, _splitColumnTypes: function _splitColumnTypes( /*array*/columns) /*object*/{ var fixedColumns = []; var scrollableColumns = []; for (var i = 0; i < columns.length; ++i) { if (columns[i].props.fixed) { fixedColumns.push(columns[i]); } else { scrollableColumns.push(columns[i]); } } return { fixed: fixedColumns, scrollable: scrollableColumns }; }, _onWheel: function _onWheel( /*number*/deltaX, /*number*/deltaY) { if (this.isMounted()) { if (!this._isScrolling) { this._didScrollStart(); } var x = this.state.scrollX; if (Math.abs(deltaY) > Math.abs(deltaX) && this.props.overflowY !== 'hidden') { var scrollState = this._scrollHelper.scrollBy(Math.round(deltaY)); var maxScrollY = Math.max(0, scrollState.contentHeight - this.state.bodyHeight); this.setState({ firstRowIndex: scrollState.index, firstRowOffset: scrollState.offset, scrollY: scrollState.position, scrollContentHeight: scrollState.contentHeight, maxScrollY: maxScrollY }); } else if (deltaX && this.props.overflowX !== 'hidden') { x += deltaX; x = x < 0 ? 0 : x; x = x > this.state.maxScrollX ? this.state.maxScrollX : x; this.setState({ scrollX: x }); } this._didScrollStop(); } }, _onHorizontalScroll: function _onHorizontalScroll( /*number*/scrollPos) { if (this.isMounted() && scrollPos !== this.state.scrollX) { if (!this._isScrolling) { this._didScrollStart(); } this.setState({ scrollX: scrollPos }); this._didScrollStop(); } }, _onVerticalScroll: function _onVerticalScroll( /*number*/scrollPos) { if (this.isMounted() && scrollPos !== this.state.scrollY) { if (!this._isScrolling) { this._didScrollStart(); } var scrollState = this._scrollHelper.scrollTo(Math.round(scrollPos)); this.setState({ firstRowIndex: scrollState.index, firstRowOffset: scrollState.offset, scrollY: scrollState.position, scrollContentHeight: scrollState.contentHeight }); this._didScrollStop(); } }, _didScrollStart: function _didScrollStart() { if (this.isMounted() && !this._isScrolling) { this._isScrolling = true; if (this.props.onScrollStart) { this.props.onScrollStart(this.state.scrollX, this.state.scrollY); } } }, _didScrollStop: function _didScrollStop() { if (this.isMounted() && this._isScrolling) { this._isScrolling = false; if (this.props.onScrollEnd) { this.props.onScrollEnd(this.state.scrollX, this.state.scrollY); } } } }); var HorizontalScrollbar = React.createClass({ displayName: 'HorizontalScrollbar', mixins: [ReactComponentWithPureRenderMixin], propTypes: { contentSize: PropTypes.number.isRequired, offset: PropTypes.number.isRequired, onScroll: PropTypes.func.isRequired, position: PropTypes.number.isRequired, size: PropTypes.number.isRequired }, render: function render() /*object*/{ var outerContainerStyle = { height: Scrollbar.SIZE, width: this.props.size }; var innerContainerStyle = { height: Scrollbar.SIZE, position: 'absolute', overflow: 'hidden', width: this.props.size }; translateDOMPositionXY(innerContainerStyle, 0, this.props.offset); return React.createElement( 'div', { className: joinClasses(cx('fixedDataTableLayout/horizontalScrollbar'), cx('public/fixedDataTable/horizontalScrollbar')), style: outerContainerStyle }, React.createElement( 'div', { style: innerContainerStyle }, React.createElement(Scrollbar, _extends({}, this.props, { isOpaque: true, orientation: 'horizontal', offset: undefined })) ) ); } }); module.exports = FixedDataTable; // isColumnResizing should be overwritten by value from props if // avaialble /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableHelper * @typechecks */ 'use strict'; var Locale = __webpack_require__(28); var React = __webpack_require__(29); var FixedDataTableColumnGroup = __webpack_require__(31); var FixedDataTableColumn = __webpack_require__(32); var DIR_SIGN = Locale.isRTL() ? -1 : +1; // A cell up to 5px outside of the visible area will still be considered visible var CELL_VISIBILITY_TOLERANCE = 5; // used for flyouts function renderToString(value) /*string*/{ if (value === null || value === undefined) { return ''; } else { return String(value); } } /** * Helper method to execute a callback against all columns given the children * of a table. * @param {?object|array} children * Children of a table. * @param {function} callback * Function to excecute for each column. It is passed the column. */ function forEachColumn(children, callback) { React.Children.forEach(children, function (child) { if (child.type === FixedDataTableColumnGroup) { forEachColumn(child.props.children, callback); } else if (child.type === FixedDataTableColumn) { callback(child); } }); } /** * Helper method to map columns to new columns. This takes into account column * groups and will generate a new column group if its columns change. * @param {?object|array} children * Children of a table. * @param {function} callback * Function to excecute for each column. It is passed the column and should * return a result column. */ function mapColumns(children, callback) { var newChildren = []; React.Children.forEach(children, function (originalChild) { var newChild = originalChild; // The child is either a column group or a column. If it is a column group // we need to iterate over its columns and then potentially generate a // new column group if (originalChild.type === FixedDataTableColumnGroup) { var haveColumnsChanged = false; var newColumns = []; forEachColumn(originalChild.props.children, function (originalcolumn) { var newColumn = callback(originalcolumn); if (newColumn !== originalcolumn) { haveColumnsChanged = true; } newColumns.push(newColumn); }); // If the column groups columns have changed clone the group and supply // new children if (haveColumnsChanged) { newChild = React.cloneElement(originalChild, { children: newColumns }); } } else if (originalChild.type === FixedDataTableColumn) { newChild = callback(originalChild); } newChildren.push(newChild); }); return newChildren; } var FixedDataTableHelper = { DIR_SIGN: DIR_SIGN, CELL_VISIBILITY_TOLERANCE: CELL_VISIBILITY_TOLERANCE, renderToString: renderToString, forEachColumn: forEachColumn, mapColumns: mapColumns }; module.exports = FixedDataTableHelper; /***/ }, /* 28 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Locale */ "use strict"; // Hard code this for now. var Locale = { isRTL: function isRTL() { return false; }, getDirection: function getDirection() { return 'LTR'; } }; module.exports = Locale; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ 'use strict'; module.exports = __webpack_require__(30); /***/ }, /* 30 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_30__; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableColumnGroup.react * @typechecks */ 'use strict'; var React = __webpack_require__(29); var PropTypes = React.PropTypes; /** * Component that defines the attributes of a table column group. */ var FixedDataTableColumnGroup = React.createClass({ displayName: 'FixedDataTableColumnGroup', statics: { __TableColumnGroup__: true }, propTypes: { /** * The horizontal alignment of the table cell content. */ align: PropTypes.oneOf(['left', 'center', 'right']), /** * Controls if the column group is fixed when scrolling in the X axis. */ fixed: PropTypes.bool, /** * Bucket for any data to be passed into column group renderer functions. */ columnGroupData: PropTypes.object, /** * The column group's header label. */ label: PropTypes.string, /** * The cell renderer that returns React-renderable content for a table * column group header. If it's not specified, the label from props will * be rendered as header content. * ``` * function( * label: ?string, * cellDataKey: string, * columnGroupData: any, * rowData: array<?object>, // array of labels of all columnGroups * width: number * ): ?$jsx * ``` */ groupHeaderRenderer: PropTypes.func }, getDefaultProps: function getDefaultProps() /*object*/{ return { fixed: false }; }, render: function render() { if (true) { throw new Error('Component <FixedDataTableColumnGroup /> should never render'); } return null; } }); module.exports = FixedDataTableColumnGroup; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableColumn.react * @typechecks */ 'use strict'; var React = __webpack_require__(29); var PropTypes = React.PropTypes; /** * Component that defines the attributes of table column. */ var FixedDataTableColumn = React.createClass({ displayName: 'FixedDataTableColumn', statics: { __TableColumn__: true }, propTypes: { /** * The horizontal alignment of the table cell content. */ align: PropTypes.oneOf(['left', 'center', 'right']), /** * className for this column's header cell. */ headerClassName: PropTypes.string, /** * className for this column's footer cell. */ footerClassName: PropTypes.string, /** * className for each of this column's data cells. */ cellClassName: PropTypes.string, /** * The cell renderer that returns React-renderable content for table cell. * ``` * function( * cellData: any, * cellDataKey: string, * rowData: object, * rowIndex: number, * columnData: any, * width: number * ): ?$jsx * ``` */ cellRenderer: PropTypes.func, /** * The getter `function(string_cellDataKey, object_rowData)` that returns * the cell data for the `cellRenderer`. * If not provided, the cell data will be collected from * `rowData[cellDataKey]` instead. The value that `cellDataGetter` returns * will be used to determine whether the cell should re-render. */ cellDataGetter: PropTypes.func, /** * The key to retrieve the cell data from the data row. Provided key type * must be either `string` or `number`. Since we use this * for keys, it must be specified for each column. */ dataKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, /** * Controls if the column is fixed when scrolling in the X axis. */ fixed: PropTypes.bool, /** * The cell renderer that returns React-renderable content for table column * header. * ``` * function( * label: ?string, * cellDataKey: string, * columnData: any, * rowData: array<?object>, * width: number * ): ?$jsx * ``` */ headerRenderer: PropTypes.func, /** * The cell renderer that returns React-renderable content for table column * footer. * ``` * function( * label: ?string, * cellDataKey: string, * columnData: any, * rowData: array<?object>, * width: number * ): ?$jsx * ``` */ footerRenderer: PropTypes.func, /** * Bucket for any data to be passed into column renderer functions. */ columnData: PropTypes.object, /** * The column's header label. */ label: PropTypes.string, /** * The pixel width of the column. */ width: PropTypes.number.isRequired, /** * If this is a resizable column this is its minimum pixel width. */ minWidth: PropTypes.number, /** * If this is a resizable column this is its maximum pixel width. */ maxWidth: PropTypes.number, /** * The grow factor relative to other columns. Same as the flex-grow API * from http://www.w3.org/TR/css3-flexbox/. Basically, take any available * extra width and distribute it proportionally according to all columns' * flexGrow values. Defaults to zero (no-flexing). */ flexGrow: PropTypes.number, /** * Whether the column can be resized with the * FixedDataTableColumnResizeHandle. Please note that if a column * has a flex grow, once you resize the column this will be set to 0. * * This property only provides the UI for the column resizing. If this * is set to true, you will need ot se the onColumnResizeEndCallback table * property and render your columns appropriately. */ isResizable: PropTypes.bool, /** * Experimental feature * Whether cells in this column can be removed from document when outside * of viewport as a result of horizontal scrolling. * Setting this property to true allows the table to not render cells in * particular column that are outside of viewport for visible rows. This * allows to create table with many columns and not have vertical scrolling * performance drop. * Setting the property to false will keep previous behaviour and keep * cell rendered if the row it belongs to is visible. */ allowCellsRecycling: PropTypes.bool }, getDefaultProps: function getDefaultProps() /*object*/{ return { allowCellsRecycling: false, fixed: false }; }, render: function render() { if (true) { throw new Error('Component <FixedDataTableColumn /> should never render'); } return null; } }); module.exports = FixedDataTableColumn; /***/ }, /* 33 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this Mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } }; module.exports = ReactComponentWithPureRenderMixin; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * This is utility that hanlds onWheel events and calls provided wheel * callback with correct frame rate. * * @providesModule ReactWheelHandler * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var emptyFunction = __webpack_require__(35); var normalizeWheel = __webpack_require__(36); var requestAnimationFramePolyfill = __webpack_require__(40); var ReactWheelHandler = (function () { /** * onWheel is the callback that will be called with right frame rate if * any wheel events happened * onWheel should is to be called with two arguments: deltaX and deltaY in * this order */ function ReactWheelHandler( /*function*/onWheel, /*boolean|function*/handleScrollX, /*boolean|function*/handleScrollY, /*?boolean|?function*/stopPropagation) { _classCallCheck(this, ReactWheelHandler); this._animationFrameID = null; this._deltaX = 0; this._deltaY = 0; this._didWheel = this._didWheel.bind(this); if (typeof handleScrollX !== 'function') { handleScrollX = handleScrollX ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse; } if (typeof handleScrollY !== 'function') { handleScrollY = handleScrollY ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse; } if (typeof stopPropagation !== 'function') { stopPropagation = stopPropagation ? emptyFunction.thatReturnsTrue : emptyFunction.thatReturnsFalse; } this._handleScrollX = handleScrollX; this._handleScrollY = handleScrollY; this._stopPropagation = stopPropagation; this._onWheelCallback = onWheel; this.onWheel = this.onWheel.bind(this); } _createClass(ReactWheelHandler, [{ key: 'onWheel', value: function onWheel( /*object*/event) { var normalizedEvent = normalizeWheel(event); var deltaX = this._deltaX + normalizedEvent.pixelX; var deltaY = this._deltaY + normalizedEvent.pixelY; var handleScrollX = this._handleScrollX(deltaX, deltaY); var handleScrollY = this._handleScrollY(deltaY, deltaX); if (!handleScrollX && !handleScrollY) { return; } this._deltaX += handleScrollX ? normalizedEvent.pixelX : 0; this._deltaY += handleScrollY ? normalizedEvent.pixelY : 0; event.preventDefault(); var changed; if (this._deltaX !== 0 || this._deltaY !== 0) { if (this._stopPropagation()) { event.stopPropagation(); } changed = true; } if (changed === true && this._animationFrameID === null) { this._animationFrameID = requestAnimationFramePolyfill(this._didWheel); } } }, { key: '_didWheel', value: function _didWheel() { this._animationFrameID = null; this._onWheelCallback(this._deltaX, this._deltaY); this._deltaX = 0; this._deltaY = 0; } }]); return ReactWheelHandler; })(); module.exports = ReactWheelHandler; /***/ }, /* 35 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ "use strict"; function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule normalizeWheel * @typechecks */ 'use strict'; var UserAgent_DEPRECATED = __webpack_require__(37); var isEventSupported = __webpack_require__(38); // Reasonable defaults var PIXEL_STEP = 10; var LINE_HEIGHT = 40; var PAGE_HEIGHT = 800; /** * Mouse wheel (and 2-finger trackpad) support on the web sucks. It is * complicated, thus this doc is long and (hopefully) detailed enough to answer * your questions. * * If you need to react to the mouse wheel in a predictable way, this code is * like your bestest friend. * hugs * * * As of today, there are 4 DOM event types you can listen to: * * 'wheel' -- Chrome(31+), FF(17+), IE(9+) * 'mousewheel' -- Chrome, IE(6+), Opera, Safari * 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother! * 'DOMMouseScroll' -- FF(0.9.7+) since 2003 * * So what to do? The is the best: * * normalizeWheel.getEventType(); * * In your event callback, use this code to get sane interpretation of the * deltas. This code will return an object with properties: * * spinX -- normalized spin speed (use for zoom) - x plane * spinY -- " - y plane * pixelX -- normalized distance (to pixels) - x plane * pixelY -- " - y plane * * Wheel values are provided by the browser assuming you are using the wheel to * scroll a web page by a number of lines or pixels (or pages). Values can vary * significantly on different platforms and browsers, forgetting that you can * scroll at different speeds. Some devices (like trackpads) emit more events * at smaller increments with fine granularity, and some emit massive jumps with * linear speed or acceleration. * * This code does its best to normalize the deltas for you: * * - spin is trying to normalize how far the wheel was spun (or trackpad * dragged). This is super useful for zoom support where you want to * throw away the chunky scroll steps on the PC and make those equal to * the slow and smooth tiny steps on the Mac. Key data: This code tries to * resolve a single slow step on a wheel to 1. * * - pixel is normalizing the desired scroll delta in pixel units. You'll * get the crazy differences between browsers, but at least it'll be in * pixels! * * - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This * should translate to positive value zooming IN, negative zooming OUT. * This matches the newer 'wheel' event. * * Why are there spinX, spinY (or pixels)? * * - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn * with a mouse. It results in side-scrolling in the browser by default. * * - spinY is what you expect -- it's the classic axis of a mouse wheel. * * - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and * probably is by browsers in conjunction with fancy 3D controllers .. but * you know. * * Implementation info: * * Examples of 'wheel' event if you scroll slowly (down) by one step with an * average mouse: * * OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120) * OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12) * OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A) * Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120) * Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120) * * On the trackpad: * * OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6) * OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A) * * On other/older browsers.. it's more complicated as there can be multiple and * also missing delta values. * * The 'wheel' event is more standard: * * http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents * * The basics is that it includes a unit, deltaMode (pixels, lines, pages), and * deltaX, deltaY and deltaZ. Some browsers provide other values to maintain * backward compatibility with older events. Those other values help us * better normalize spin speed. Example of what the browsers provide: * * | event.wheelDelta | event.detail * ------------------+------------------+-------------- * Safari v5/OS X | -120 | 0 * Safari v5/Win7 | -120 | 0 * Chrome v17/OS X | -120 | 0 * Chrome v17/Win7 | -120 | 0 * IE9/Win7 | -120 | undefined * Firefox v4/OS X | undefined | 1 * Firefox v4/Win7 | undefined | 3 * */ function normalizeWheel( /*object*/event) /*object*/{ var sX = 0, sY = 0, // spinX, spinY pX = 0, pY = 0; // pixelX, pixelY // Legacy if ('detail' in event) { sY = event.detail; } if ('wheelDelta' in event) { sY = -event.wheelDelta / 120; } if ('wheelDeltaY' in event) { sY = -event.wheelDeltaY / 120; } if ('wheelDeltaX' in event) { sX = -event.wheelDeltaX / 120; } // side scrolling on FF with DOMMouseScroll if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) { sX = sY; sY = 0; } pX = sX * PIXEL_STEP; pY = sY * PIXEL_STEP; if ('deltaY' in event) { pY = event.deltaY; } if ('deltaX' in event) { pX = event.deltaX; } if ((pX || pY) && event.deltaMode) { if (event.deltaMode == 1) { // delta in LINE units pX *= LINE_HEIGHT; pY *= LINE_HEIGHT; } else { // delta in PAGE units pX *= PAGE_HEIGHT; pY *= PAGE_HEIGHT; } } // Fall-back if spin cannot be determined if (pX && !sX) { sX = pX < 1 ? -1 : 1; } if (pY && !sY) { sY = pY < 1 ? -1 : 1; } return { spinX: sX, spinY: sY, pixelX: pX, pixelY: pY }; } /** * The best combination if you prefer spinX + spinY normalization. It favors * the older DOMMouseScroll for Firefox, as FF does not include wheelDelta with * 'wheel' event, making spin speed determination impossible. */ normalizeWheel.getEventType = function () /*string*/{ return UserAgent_DEPRECATED.firefox() ? 'DOMMouseScroll' : isEventSupported('wheel') ? 'wheel' : 'mousewheel'; }; module.exports = normalizeWheel; /***/ }, /* 37 */ /***/ function(module, exports) { /** * Copyright 2004-present Facebook. All Rights Reserved. * * @providesModule UserAgent_DEPRECATED */ /** * Provides entirely client-side User Agent and OS detection. You should prefer * the non-deprecated UserAgent module when possible, which exposes our * authoritative server-side PHP-based detection to the client. * * Usage is straightforward: * * if (UserAgent_DEPRECATED.ie()) { * // IE * } * * You can also do version checks: * * if (UserAgent_DEPRECATED.ie() >= 7) { * // IE7 or better * } * * The browser functions will return NaN if the browser does not match, so * you can also do version compares the other way: * * if (UserAgent_DEPRECATED.ie() < 7) { * // IE6 or worse * } * * Note that the version is a float and may include a minor version number, * so you should always use range operators to perform comparisons, not * strict equality. * * **Note:** You should **strongly** prefer capability detection to browser * version detection where it's reasonable: * * http://www.quirksmode.org/js/support.html * * Further, we have a large number of mature wrapper functions and classes * which abstract away many browser irregularities. Check the documentation, * grep for things, or ask on javascript@lists.facebook.com before writing yet * another copy of "event || window.event". * */ 'use strict'; var _populated = false; // Browsers var _ie, _firefox, _opera, _webkit, _chrome; // Actual IE browser for compatibility mode var _ie_real_version; // Platforms var _osx, _windows, _linux, _android; // Architectures var _win64; // Devices var _iphone, _ipad, _native; var _mobile; function _populate() { if (_populated) { return; } _populated = true; // To work around buggy JS libraries that can't handle multi-digit // version numbers, Opera 10's user agent string claims it's Opera // 9, then later includes a Version/X.Y field: // // Opera/9.80 (foo) Presto/2.2.15 Version/10.10 var uas = navigator.userAgent; var agent = /(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(uas); var os = /(Mac OS X)|(Windows)|(Linux)/.exec(uas); _iphone = /\b(iPhone|iP[ao]d)/.exec(uas); _ipad = /\b(iP[ao]d)/.exec(uas); _android = /Android/i.exec(uas); _native = /FBAN\/\w+;/i.exec(uas); _mobile = /Mobile/i.exec(uas); // Note that the IE team blog would have you believe you should be checking // for 'Win64; x64'. But MSDN then reveals that you can actually be coming // from either x64 or ia64; so ultimately, you should just check for Win64 // as in indicator of whether you're in 64-bit IE. 32-bit IE on 64-bit // Windows will send 'WOW64' instead. _win64 = !!/Win64/.exec(uas); if (agent) { _ie = agent[1] ? parseFloat(agent[1]) : agent[5] ? parseFloat(agent[5]) : NaN; // IE compatibility mode if (_ie && document && document.documentMode) { _ie = document.documentMode; } // grab the "true" ie version from the trident token if available var trident = /(?:Trident\/(\d+.\d+))/.exec(uas); _ie_real_version = trident ? parseFloat(trident[1]) + 4 : _ie; _firefox = agent[2] ? parseFloat(agent[2]) : NaN; _opera = agent[3] ? parseFloat(agent[3]) : NaN; _webkit = agent[4] ? parseFloat(agent[4]) : NaN; if (_webkit) { // We do not add the regexp to the above test, because it will always // match 'safari' only since 'AppleWebKit' appears before 'Chrome' in // the userAgent string. agent = /(?:Chrome\/(\d+\.\d+))/.exec(uas); _chrome = agent && agent[1] ? parseFloat(agent[1]) : NaN; } else { _chrome = NaN; } } else { _ie = _firefox = _opera = _chrome = _webkit = NaN; } if (os) { if (os[1]) { // Detect OS X version. If no version number matches, set _osx to true. // Version examples: 10, 10_6_1, 10.7 // Parses version number as a float, taking only first two sets of // digits. If only one set of digits is found, returns just the major // version number. var ver = /(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(uas); _osx = ver ? parseFloat(ver[1].replace('_', '.')) : true; } else { _osx = false; } _windows = !!os[2]; _linux = !!os[3]; } else { _osx = _windows = _linux = false; } } var UserAgent_DEPRECATED = { /** * Check if the UA is Internet Explorer. * * * @return float|NaN Version number (if match) or NaN. */ ie: function ie() { return _populate() || _ie; }, /** * Check if we're in Internet Explorer compatibility mode. * * @return bool true if in compatibility mode, false if * not compatibility mode or not ie */ ieCompatibilityMode: function ieCompatibilityMode() { return _populate() || _ie_real_version > _ie; }, /** * Whether the browser is 64-bit IE. Really, this is kind of weak sauce; we * only need this because Skype can't handle 64-bit IE yet. We need to remove * this when we don't need it -- tracked by #601957. */ ie64: function ie64() { return UserAgent_DEPRECATED.ie() && _win64; }, /** * Check if the UA is Firefox. * * * @return float|NaN Version number (if match) or NaN. */ firefox: function firefox() { return _populate() || _firefox; }, /** * Check if the UA is Opera. * * * @return float|NaN Version number (if match) or NaN. */ opera: function opera() { return _populate() || _opera; }, /** * Check if the UA is WebKit. * * * @return float|NaN Version number (if match) or NaN. */ webkit: function webkit() { return _populate() || _webkit; }, /** * For Push * WILL BE REMOVED VERY SOON. Use UserAgent_DEPRECATED.webkit */ safari: function safari() { return UserAgent_DEPRECATED.webkit(); }, /** * Check if the UA is a Chrome browser. * * * @return float|NaN Version number (if match) or NaN. */ chrome: function chrome() { return _populate() || _chrome; }, /** * Check if the user is running Windows. * * @return bool `true' if the user's OS is Windows. */ windows: function windows() { return _populate() || _windows; }, /** * Check if the user is running Mac OS X. * * @return float|bool Returns a float if a version number is detected, * otherwise true/false. */ osx: function osx() { return _populate() || _osx; }, /** * Check if the user is running Linux. * * @return bool `true' if the user's OS is some flavor of Linux. */ linux: function linux() { return _populate() || _linux; }, /** * Check if the user is running on an iPhone or iPod platform. * * @return bool `true' if the user is running some flavor of the * iPhone OS. */ iphone: function iphone() { return _populate() || _iphone; }, mobile: function mobile() { return _populate() || (_iphone || _ipad || _android || _mobile); }, nativeApp: function nativeApp() { // webviews inside of the native apps return _populate() || _native; }, android: function android() { return _populate() || _android; }, ipad: function ipad() { return _populate() || _ipad; } }; module.exports = UserAgent_DEPRECATED; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = __webpack_require__(39); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = (eventName in document); if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }, /* 39 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule requestAnimationFramePolyfill */ 'use strict'; var emptyFunction = __webpack_require__(35); var nativeRequestAnimationFrame = __webpack_require__(41); var lastTime = 0; /** * Here is the native and polyfill version of requestAnimationFrame. * Please don't use it directly and use requestAnimationFrame module instead. */ var requestAnimationFrame = nativeRequestAnimationFrame || function (callback) { var currTime = Date.now(); var timeDelay = Math.max(0, 16 - (currTime - lastTime)); lastTime = currTime + timeDelay; return global.setTimeout(function () { callback(Date.now()); }, timeDelay); }; // Works around a rare bug in Safari 6 where the first request is never invoked. requestAnimationFrame(emptyFunction); module.exports = requestAnimationFrame; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 41 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule nativeRequestAnimationFrame */ "use strict"; var nativeRequestAnimationFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame; module.exports = nativeRequestAnimationFrame; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Scrollbar.react * @typechecks */ 'use strict'; var DOMMouseMoveTracker = __webpack_require__(43); var Keys = __webpack_require__(46); var React = __webpack_require__(29); var ReactDOM = __webpack_require__(47); var ReactComponentWithPureRenderMixin = __webpack_require__(33); var ReactWheelHandler = __webpack_require__(34); var cssVar = __webpack_require__(49); var cx = __webpack_require__(50); var emptyFunction = __webpack_require__(35); var translateDOMPositionXY = __webpack_require__(51); var PropTypes = React.PropTypes; var UNSCROLLABLE_STATE = { position: 0, scrollable: false }; var FACE_MARGIN = parseInt(cssVar('scrollbar-face-margin'), 10); var FACE_MARGIN_2 = FACE_MARGIN * 2; var FACE_SIZE_MIN = 30; var KEYBOARD_SCROLL_AMOUNT = 40; var _lastScrolledScrollbar = null; var Scrollbar = React.createClass({ displayName: 'Scrollbar', mixins: [ReactComponentWithPureRenderMixin], propTypes: { contentSize: PropTypes.number.isRequired, defaultPosition: PropTypes.number, isOpaque: PropTypes.bool, orientation: PropTypes.oneOf(['vertical', 'horizontal']), onScroll: PropTypes.func, position: PropTypes.number, size: PropTypes.number.isRequired, trackColor: PropTypes.oneOf(['gray']), zIndex: PropTypes.number, verticalTop: PropTypes.number }, getInitialState: function getInitialState() /*object*/{ var props = this.props; return this._calculateState(props.position || props.defaultPosition || 0, props.size, props.contentSize, props.orientation); }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/nextProps) { var controlledPosition = nextProps.position; if (controlledPosition === undefined) { this._setNextState(this._calculateState(this.state.position, nextProps.size, nextProps.contentSize, nextProps.orientation)); } else { this._setNextState(this._calculateState(controlledPosition, nextProps.size, nextProps.contentSize, nextProps.orientation), nextProps); } }, getDefaultProps: function getDefaultProps() /*object*/{ return { defaultPosition: 0, isOpaque: false, onScroll: emptyFunction, orientation: 'vertical', zIndex: 99 }; }, render: function render() /*?object*/{ if (!this.state.scrollable) { return null; } var size = this.props.size; var mainStyle; var faceStyle; var isHorizontal = this.state.isHorizontal; var isVertical = !isHorizontal; var isActive = this.state.focused || this.state.isDragging; var faceSize = this.state.faceSize; var isOpaque = this.props.isOpaque; var verticalTop = this.props.verticalTop || 0; var mainClassName = cx({ 'ScrollbarLayout/main': true, 'ScrollbarLayout/mainVertical': isVertical, 'ScrollbarLayout/mainHorizontal': isHorizontal, 'public/Scrollbar/main': true, 'public/Scrollbar/mainOpaque': isOpaque, 'public/Scrollbar/mainActive': isActive }); var faceClassName = cx({ 'ScrollbarLayout/face': true, 'ScrollbarLayout/faceHorizontal': isHorizontal, 'ScrollbarLayout/faceVertical': isVertical, 'public/Scrollbar/faceActive': isActive, 'public/Scrollbar/face': true }); var position = this.state.position * this.state.scale + FACE_MARGIN; if (isHorizontal) { mainStyle = { width: size }; faceStyle = { width: faceSize - FACE_MARGIN_2 }; translateDOMPositionXY(faceStyle, position, 0); } else { mainStyle = { top: verticalTop, height: size }; faceStyle = { height: faceSize - FACE_MARGIN_2 }; translateDOMPositionXY(faceStyle, 0, position); } mainStyle.zIndex = this.props.zIndex; if (this.props.trackColor === 'gray') { mainStyle.backgroundColor = cssVar('fbui-desktop-background-light'); } return React.createElement( 'div', { onFocus: this._onFocus, onBlur: this._onBlur, onKeyDown: this._onKeyDown, onMouseDown: this._onMouseDown, onWheel: this._wheelHandler.onWheel, className: mainClassName, style: mainStyle, tabIndex: 0 }, React.createElement('div', { ref: 'face', className: faceClassName, style: faceStyle }) ); }, componentWillMount: function componentWillMount() { var isHorizontal = this.props.orientation === 'horizontal'; var onWheel = isHorizontal ? this._onWheelX : this._onWheelY; this._wheelHandler = new ReactWheelHandler(onWheel, this._shouldHandleX, // Should hanlde horizontal scroll this._shouldHandleY // Should handle vertical scroll ); }, componentDidMount: function componentDidMount() { this._mouseMoveTracker = new DOMMouseMoveTracker(this._onMouseMove, this._onMouseMoveEnd, document.documentElement); if (this.props.position !== undefined && this.state.position !== this.props.position) { this._didScroll(); } }, componentWillUnmount: function componentWillUnmount() { this._nextState = null; this._mouseMoveTracker.releaseMouseMoves(); if (_lastScrolledScrollbar === this) { _lastScrolledScrollbar = null; } delete this._mouseMoveTracker; }, scrollBy: function scrollBy( /*number*/delta) { this._onWheel(delta); }, _shouldHandleX: function _shouldHandleX( /*number*/delta) /*boolean*/{ return this.props.orientation === 'horizontal' ? this._shouldHandleChange(delta) : false; }, _shouldHandleY: function _shouldHandleY( /*number*/delta) /*boolean*/{ return this.props.orientation !== 'horizontal' ? this._shouldHandleChange(delta) : false; }, _shouldHandleChange: function _shouldHandleChange( /*number*/delta) /*boolean*/{ var nextState = this._calculateState(this.state.position + delta, this.props.size, this.props.contentSize, this.props.orientation); return nextState.position !== this.state.position; }, _calculateState: function _calculateState( /*number*/position, /*number*/size, /*number*/contentSize, /*string*/orientation) /*object*/{ if (size < 1 || contentSize <= size) { return UNSCROLLABLE_STATE; } var stateKey = position + '_' + size + '_' + contentSize + '_' + orientation; if (this._stateKey === stateKey) { return this._stateForKey; } // There are two types of positions here. // 1) Phisical position: changed by mouse / keyboard // 2) Logical position: changed by props. // The logical position will be kept as as internal state and the `render()` // function will translate it into physical position to render. var isHorizontal = orientation === 'horizontal'; var scale = size / contentSize; var faceSize = size * scale; if (faceSize < FACE_SIZE_MIN) { scale = (size - FACE_SIZE_MIN) / (contentSize - size); faceSize = FACE_SIZE_MIN; } var scrollable = true; var maxPosition = contentSize - size; if (position < 0) { position = 0; } else if (position > maxPosition) { position = maxPosition; } var isDragging = this._mouseMoveTracker ? this._mouseMoveTracker.isDragging() : false; // This function should only return flat values that can be compared quiclky // by `ReactComponentWithPureRenderMixin`. var state = { faceSize: faceSize, isDragging: isDragging, isHorizontal: isHorizontal, position: position, scale: scale, scrollable: scrollable }; // cache the state for later use. this._stateKey = stateKey; this._stateForKey = state; return state; }, _onWheelY: function _onWheelY( /*number*/deltaX, /*number*/deltaY) { this._onWheel(deltaY); }, _onWheelX: function _onWheelX( /*number*/deltaX, /*number*/deltaY) { this._onWheel(deltaX); }, _onWheel: function _onWheel( /*number*/delta) { var props = this.props; // The mouse may move faster then the animation frame does. // Use `requestAnimationFrame` to avoid over-updating. this._setNextState(this._calculateState(this.state.position + delta, props.size, props.contentSize, props.orientation)); }, _onMouseDown: function _onMouseDown( /*object*/event) { var nextState; if (event.target !== ReactDOM.findDOMNode(this.refs.face)) { // Both `offsetX` and `layerX` are non-standard DOM property but they are // magically available for browsers somehow. var nativeEvent = event.nativeEvent; var position = this.state.isHorizontal ? nativeEvent.offsetX || nativeEvent.layerX : nativeEvent.offsetY || nativeEvent.layerY; // MouseDown on the scroll-track directly, move the center of the // scroll-face to the mouse position. var props = this.props; position = position / this.state.scale; nextState = this._calculateState(position - this.state.faceSize * 0.5 / this.state.scale, props.size, props.contentSize, props.orientation); } else { nextState = {}; } nextState.focused = true; this._setNextState(nextState); this._mouseMoveTracker.captureMouseMoves(event); // Focus the node so it may receive keyboard event. ReactDOM.findDOMNode(this).focus(); }, _onMouseMove: function _onMouseMove( /*number*/deltaX, /*number*/deltaY) { var props = this.props; var delta = this.state.isHorizontal ? deltaX : deltaY; delta = delta / this.state.scale; this._setNextState(this._calculateState(this.state.position + delta, props.size, props.contentSize, props.orientation)); }, _onMouseMoveEnd: function _onMouseMoveEnd() { this._nextState = null; this._mouseMoveTracker.releaseMouseMoves(); this.setState({ isDragging: false }); }, _onKeyDown: function _onKeyDown( /*object*/event) { var keyCode = event.keyCode; if (keyCode === Keys.TAB) { // Let focus move off the scrollbar. return; } var distance = KEYBOARD_SCROLL_AMOUNT; var direction = 0; if (this.state.isHorizontal) { switch (keyCode) { case Keys.HOME: direction = -1; distance = this.props.contentSize; break; case Keys.LEFT: direction = -1; break; case Keys.RIGHT: direction = 1; break; default: return; } } if (!this.state.isHorizontal) { switch (keyCode) { case Keys.SPACE: if (event.shiftKey) { direction = -1; } else { direction = 1; } break; case Keys.HOME: direction = -1; distance = this.props.contentSize; break; case Keys.UP: direction = -1; break; case Keys.DOWN: direction = 1; break; case Keys.PAGE_UP: direction = -1; distance = this.props.size; break; case Keys.PAGE_DOWN: direction = 1; distance = this.props.size; break; default: return; } } event.preventDefault(); var props = this.props; this._setNextState(this._calculateState(this.state.position + distance * direction, props.size, props.contentSize, props.orientation)); }, _onFocus: function _onFocus() { this.setState({ focused: true }); }, _onBlur: function _onBlur() { this.setState({ focused: false }); }, _blur: function _blur() { if (this.isMounted()) { try { this._onBlur(); ReactDOM.findDOMNode(this).blur(); } catch (oops) { // pass } } }, _setNextState: function _setNextState( /*object*/nextState, /*?object*/props) { props = props || this.props; var controlledPosition = props.position; var willScroll = this.state.position !== nextState.position; if (controlledPosition === undefined) { var callback = willScroll ? this._didScroll : undefined; this.setState(nextState, callback); } else if (controlledPosition === nextState.position) { this.setState(nextState); } else { // Scrolling is controlled. Don't update the state and let the owner // to update the scrollbar instead. if (nextState.position !== undefined && nextState.position !== this.state.position) { this.props.onScroll(nextState.position); } return; } if (willScroll && _lastScrolledScrollbar !== this) { _lastScrolledScrollbar && _lastScrolledScrollbar._blur(); _lastScrolledScrollbar = this; } }, _didScroll: function _didScroll() { this.props.onScroll(this.state.position); } }); Scrollbar.KEYBOARD_SCROLL_AMOUNT = KEYBOARD_SCROLL_AMOUNT; Scrollbar.SIZE = parseInt(cssVar('scrollbar-size'), 10); module.exports = Scrollbar; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * This class listens to events on the document and then updates a react * component through callbacks. * Please note that captureMouseMove must be called in * order to initialize listeners on mousemove and mouseup. * releaseMouseMove must be called to remove them. It is important to * call releaseMouseMoves since mousemove is expensive to listen to. * * @providesModule DOMMouseMoveTracker * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var EventListener = __webpack_require__(44); var cancelAnimationFramePolyfill = __webpack_require__(45); var requestAnimationFramePolyfill = __webpack_require__(40); var DOMMouseMoveTracker = (function () { /** * onMove is the callback that will be called on every mouse move. * onMoveEnd is called on mouse up when movement has ended. */ function DOMMouseMoveTracker( /*function*/onMove, /*function*/onMoveEnd, /*DOMElement*/domNode) { _classCallCheck(this, DOMMouseMoveTracker); this._isDragging = false; this._animationFrameID = null; this._domNode = domNode; this._onMove = onMove; this._onMoveEnd = onMoveEnd; this._onMouseMove = this._onMouseMove.bind(this); this._onMouseUp = this._onMouseUp.bind(this); this._didMouseMove = this._didMouseMove.bind(this); } /** * This is to set up the listeners for listening to mouse move * and mouse up signaling the movement has ended. Please note that these * listeners are added at the document.body level. It takes in an event * in order to grab inital state. */ _createClass(DOMMouseMoveTracker, [{ key: 'captureMouseMoves', value: function captureMouseMoves( /*object*/event) { if (!this._eventMoveToken && !this._eventUpToken) { this._eventMoveToken = EventListener.listen(this._domNode, 'mousemove', this._onMouseMove); this._eventUpToken = EventListener.listen(this._domNode, 'mouseup', this._onMouseUp); } if (!this._isDragging) { this._deltaX = 0; this._deltaY = 0; this._isDragging = true; this._x = event.clientX; this._y = event.clientY; } event.preventDefault(); } /** * These releases all of the listeners on document.body. */ }, { key: 'releaseMouseMoves', value: function releaseMouseMoves() { if (this._eventMoveToken && this._eventUpToken) { this._eventMoveToken.remove(); this._eventMoveToken = null; this._eventUpToken.remove(); this._eventUpToken = null; } if (this._animationFrameID !== null) { cancelAnimationFramePolyfill(this._animationFrameID); this._animationFrameID = null; } if (this._isDragging) { this._isDragging = false; this._x = null; this._y = null; } } /** * Returns whether or not if the mouse movement is being tracked. */ }, { key: 'isDragging', value: function isDragging() /*boolean*/{ return this._isDragging; } /** * Calls onMove passed into constructor and updates internal state. */ }, { key: '_onMouseMove', value: function _onMouseMove( /*object*/event) { var x = event.clientX; var y = event.clientY; this._deltaX += x - this._x; this._deltaY += y - this._y; if (this._animationFrameID === null) { // The mouse may move faster then the animation frame does. // Use `requestAnimationFramePolyfill` to avoid over-updating. this._animationFrameID = requestAnimationFramePolyfill(this._didMouseMove); } this._x = x; this._y = y; event.preventDefault(); } }, { key: '_didMouseMove', value: function _didMouseMove() { this._animationFrameID = null; this._onMove(this._deltaX, this._deltaY); this._deltaX = 0; this._deltaY = 0; } /** * Calls onMoveEnd passed into constructor and updates internal state. */ }, { key: '_onMouseUp', value: function _onMouseUp() { if (this._animationFrameID) { this._didMouseMove(); } this._onMoveEnd(); } }]); return DOMMouseMoveTracker; })(); module.exports = DOMMouseMoveTracker; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventListener * @typechecks */ 'use strict'; var emptyFunction = __webpack_require__(35); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (!target.addEventListener) { if (true) { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } else { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; /***/ }, /* 45 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cancelAnimationFramePolyfill */ /** * Here is the native and polyfill version of cancelAnimationFrame. * Please don't use it directly and use cancelAnimationFrame module instead. */ "use strict"; var cancelAnimationFrame = global.cancelAnimationFrame || global.webkitCancelAnimationFrame || global.mozCancelAnimationFrame || global.oCancelAnimationFrame || global.msCancelAnimationFrame || global.clearTimeout; module.exports = cancelAnimationFrame; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 46 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Keys */ "use strict"; module.exports = { BACKSPACE: 8, TAB: 9, RETURN: 13, ALT: 18, ESC: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, DELETE: 46, COMMA: 188, PERIOD: 190, A: 65, Z: 90, ZERO: 48, NUMPAD_0: 96, NUMPAD_9: 105 }; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM */ 'use strict'; module.exports = __webpack_require__(48); /***/ }, /* 48 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_48__; /***/ }, /* 49 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cssVar * @typechecks */ "use strict"; var CSS_VARS = { 'scrollbar-face-active-color': '#7d7d7d', 'scrollbar-face-color': '#c2c2c2', 'scrollbar-face-margin': '4px', 'scrollbar-face-radius': '6px', 'scrollbar-size': '15px', 'scrollbar-size-large': '17px', 'scrollbar-track-color': 'rgba(255, 255, 255, 0.8)', 'fbui-white': '#fff', 'fbui-desktop-background-light': '#f6f7f8' }; /** * @param {string} name */ function cssVar(name) { if (CSS_VARS.hasOwnProperty(name)) { return CSS_VARS[name]; } throw new Error('cssVar' + '("' + name + '"): Unexpected class transformation.'); } cssVar.CSS_VARS = CSS_VARS; module.exports = cssVar; /***/ }, /* 50 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cx */ 'use strict'; var slashReplaceRegex = /\//g; var cache = {}; function getClassName(className) { if (cache[className]) { return cache[className]; } cache[className] = className.replace(slashReplaceRegex, '_'); return cache[className]; } /** * This function is used to mark string literals representing CSS class names * so that they can be transformed statically. This allows for modularization * and minification of CSS class names. * * In static_upstream, this function is actually implemented, but it should * eventually be replaced with something more descriptive, and the transform * that is used in the main stack should be ported for use elsewhere. * * @param string|object className to modularize, or an object of key/values. * In the object case, the values are conditions that * determine if the className keys should be included. * @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ function cx(classNames) { var classNamesArray; if (typeof classNames == 'object') { classNamesArray = Object.keys(classNames).filter(function (className) { return classNames[className]; }); } else { classNamesArray = Array.prototype.slice.call(arguments); } return classNamesArray.map(getClassName).join(' '); } module.exports = cx; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule translateDOMPositionXY * @typechecks */ 'use strict'; var BrowserSupportCore = __webpack_require__(52); var getVendorPrefixedName = __webpack_require__(53); var TRANSFORM = getVendorPrefixedName('transform'); var BACKFACE_VISIBILITY = getVendorPrefixedName('backfaceVisibility'); var translateDOMPositionXY = (function () { if (BrowserSupportCore.hasCSSTransforms()) { var ua = global.window ? global.window.navigator.userAgent : 'UNKNOWN'; var isSafari = /Safari\//.test(ua) && !/Chrome\//.test(ua); // It appears that Safari messes up the composition order // of GPU-accelerated layers // (see bug https://bugs.webkit.org/show_bug.cgi?id=61824). // Use 2D translation instead. if (!isSafari && BrowserSupportCore.hasCSS3DTransforms()) { return function ( /*object*/style, /*number*/x, /*number*/y) { style[TRANSFORM] = 'translate3d(' + x + 'px,' + y + 'px,0)'; style[BACKFACE_VISIBILITY] = 'hidden'; }; } else { return function ( /*object*/style, /*number*/x, /*number*/y) { style[TRANSFORM] = 'translate(' + x + 'px,' + y + 'px)'; }; } } else { return function ( /*object*/style, /*number*/x, /*number*/y) { style.left = x + 'px'; style.top = y + 'px'; }; } })(); module.exports = translateDOMPositionXY; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BrowserSupportCore */ 'use strict'; var getVendorPrefixedName = __webpack_require__(53); var BrowserSupportCore = { /** * @return {bool} True if browser supports css animations. */ hasCSSAnimations: function hasCSSAnimations() { return !!getVendorPrefixedName('animationName'); }, /** * @return {bool} True if browser supports css transforms. */ hasCSSTransforms: function hasCSSTransforms() { return !!getVendorPrefixedName('transform'); }, /** * @return {bool} True if browser supports css 3d transforms. */ hasCSS3DTransforms: function hasCSS3DTransforms() { return !!getVendorPrefixedName('perspective'); }, /** * @return {bool} True if browser supports css transitions. */ hasCSSTransitions: function hasCSSTransitions() { return !!getVendorPrefixedName('transition'); } }; module.exports = BrowserSupportCore; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedName * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(39); var camelize = __webpack_require__(54); var invariant = __webpack_require__(55); var memoized = {}; var prefixes = ['Webkit', 'ms', 'Moz', 'O']; var prefixRegex = new RegExp('^(' + prefixes.join('|') + ')'); var testStyle = ExecutionEnvironment.canUseDOM ? document.createElement('div').style : {}; function getWithPrefix(name) { for (var i = 0; i < prefixes.length; i++) { var prefixedName = prefixes[i] + name; if (prefixedName in testStyle) { return prefixedName; } } return null; } /** * @param {string} property Name of a css property to check for. * @return {?string} property name supported in the browser, or null if not * supported. */ function getVendorPrefixedName(property) { var name = camelize(property); if (memoized[name] === undefined) { var capitalizedName = name.charAt(0).toUpperCase() + name.slice(1); if (prefixRegex.test(capitalizedName)) { invariant(false, 'getVendorPrefixedName must only be called with unprefixed' + 'CSS property names. It was called with %s', property); } memoized[name] = name in testStyle ? name : getWithPrefix(capitalizedName); } return memoized[name]; } module.exports = getVendorPrefixedName; /***/ }, /* 54 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ "use strict"; var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function invariant(condition, format, a, b, c, d, e, f) { if (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error('Invariant Violation: ' + format.replace(/%s/g, function () { return args[argIndex++]; })); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableBufferedRows.react * @typechecks */ 'use strict'; var React = __webpack_require__(29); var FixedDataTableRowBuffer = __webpack_require__(57); var FixedDataTableRow = __webpack_require__(61); var cx = __webpack_require__(50); var emptyFunction = __webpack_require__(35); var joinClasses = __webpack_require__(70); var translateDOMPositionXY = __webpack_require__(51); var PropTypes = React.PropTypes; var FixedDataTableBufferedRows = React.createClass({ displayName: 'FixedDataTableBufferedRows', propTypes: { defaultRowHeight: PropTypes.number.isRequired, firstRowIndex: PropTypes.number.isRequired, firstRowOffset: PropTypes.number.isRequired, fixedColumns: PropTypes.array.isRequired, height: PropTypes.number.isRequired, offsetTop: PropTypes.number.isRequired, onRowClick: PropTypes.func, onRowDoubleClick: PropTypes.func, onRowMouseDown: PropTypes.func, onRowMouseEnter: PropTypes.func, onRowMouseLeave: PropTypes.func, rowClassNameGetter: PropTypes.func, rowsCount: PropTypes.number.isRequired, rowGetter: PropTypes.func.isRequired, rowHeightGetter: PropTypes.func, rowPositionGetter: PropTypes.func.isRequired, scrollLeft: PropTypes.number.isRequired, scrollableColumns: PropTypes.array.isRequired, showLastRowBorder: PropTypes.bool, width: PropTypes.number.isRequired }, getInitialState: function getInitialState() /*object*/{ this._rowBuffer = new FixedDataTableRowBuffer(this.props.rowsCount, this.props.defaultRowHeight, this.props.height, this._getRowHeight); return { rowsToRender: this._rowBuffer.getRows(this.props.firstRowIndex, this.props.firstRowOffset) }; }, componentWillMount: function componentWillMount() { this._staticRowArray = []; }, componentDidMount: function componentDidMount() { this._bufferUpdateTimer = setTimeout(this._updateBuffer, 1000); }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/nextProps) { if (nextProps.rowsCount !== this.props.rowsCount || nextProps.defaultRowHeight !== this.props.defaultRowHeight || nextProps.height !== this.props.height) { this._rowBuffer = new FixedDataTableRowBuffer(nextProps.rowsCount, nextProps.defaultRowHeight, nextProps.height, this._getRowHeight); } this.setState({ rowsToRender: this._rowBuffer.getRows(nextProps.firstRowIndex, nextProps.firstRowOffset) }); if (this._bufferUpdateTimer) { clearTimeout(this._bufferUpdateTimer); } this._bufferUpdateTimer = setTimeout(this._updateBuffer, 400); }, _updateBuffer: function _updateBuffer() { this._bufferUpdateTimer = null; if (this.isMounted()) { this.setState({ rowsToRender: this._rowBuffer.getRowsWithUpdatedBuffer() }); } }, shouldComponentUpdate: function shouldComponentUpdate() /*boolean*/{ // Don't add PureRenderMixin to this component please. return true; }, componentWillUnmount: function componentWillUnmount() { this._staticRowArray.length = 0; }, render: function render() /*object*/{ var props = this.props; var rowClassNameGetter = props.rowClassNameGetter || emptyFunction; var rowGetter = props.rowGetter; var rowPositionGetter = props.rowPositionGetter; var rowsToRender = this.state.rowsToRender; this._staticRowArray.length = rowsToRender.length; for (var i = 0; i < rowsToRender.length; ++i) { var rowIndex = rowsToRender[i]; var currentRowHeight = this._getRowHeight(rowIndex); var rowOffsetTop = rowPositionGetter(rowIndex); var hasBottomBorder = rowIndex === props.rowsCount - 1 && props.showLastRowBorder; this._staticRowArray[i] = React.createElement(FixedDataTableRow, { key: i, index: rowIndex, data: rowGetter(rowIndex), width: props.width, height: currentRowHeight, scrollLeft: Math.round(props.scrollLeft), offsetTop: Math.round(rowOffsetTop), fixedColumns: props.fixedColumns, scrollableColumns: props.scrollableColumns, onClick: props.onRowClick, onDoubleClick: props.onRowDoubleClick, onMouseDown: props.onRowMouseDown, onMouseEnter: props.onRowMouseEnter, onMouseLeave: props.onRowMouseLeave, className: joinClasses(rowClassNameGetter(rowIndex), cx('public/fixedDataTable/bodyRow'), cx({ 'fixedDataTableLayout/hasBottomBorder': hasBottomBorder, 'public/fixedDataTable/hasBottomBorder': hasBottomBorder })) }); } var firstRowPosition = props.rowPositionGetter(props.firstRowIndex); var style = { position: 'absolute' }; translateDOMPositionXY(style, 0, props.firstRowOffset - firstRowPosition + props.offsetTop); return React.createElement( 'div', { style: style }, this._staticRowArray ); }, _getRowHeight: function _getRowHeight( /*number*/index) /*number*/{ return this.props.rowHeightGetter ? this.props.rowHeightGetter(index) : this.props.defaultRowHeight; } }); module.exports = FixedDataTableBufferedRows; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableRowBuffer * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var IntegerBufferSet = __webpack_require__(58); var clamp = __webpack_require__(60); var invariant = __webpack_require__(55); var MIN_BUFFER_ROWS = 3; var MAX_BUFFER_ROWS = 6; // FixedDataTableRowBuffer is a helper class that executes row buffering // logic for FixedDataTable. It figures out which rows should be rendered // and in which positions. var FixedDataTableRowBuffer = (function () { function FixedDataTableRowBuffer( /*number*/rowsCount, /*number*/defaultRowHeight, /*number*/viewportHeight, /*?function*/rowHeightGetter) { _classCallCheck(this, FixedDataTableRowBuffer); invariant(defaultRowHeight !== 0, "defaultRowHeight musn't be equal 0 in FixedDataTableRowBuffer"); this._bufferSet = new IntegerBufferSet(); this._defaultRowHeight = defaultRowHeight; this._viewportRowsBegin = 0; this._viewportRowsEnd = 0; this._maxVisibleRowCount = Math.ceil(viewportHeight / defaultRowHeight) + 1; this._bufferRowsCount = clamp(MIN_BUFFER_ROWS, Math.floor(this._maxVisibleRowCount / 2), MAX_BUFFER_ROWS); this._rowsCount = rowsCount; this._rowHeightGetter = rowHeightGetter; this._rows = []; this._viewportHeight = viewportHeight; this.getRows = this.getRows.bind(this); this.getRowsWithUpdatedBuffer = this.getRowsWithUpdatedBuffer.bind(this); } _createClass(FixedDataTableRowBuffer, [{ key: 'getRowsWithUpdatedBuffer', value: function getRowsWithUpdatedBuffer() /*array*/{ var remainingBufferRows = 2 * this._bufferRowsCount; var bufferRowIndex = Math.max(this._viewportRowsBegin - this._bufferRowsCount, 0); while (bufferRowIndex < this._viewportRowsBegin) { this._addRowToBuffer(bufferRowIndex, this._viewportRowsBegin, this._viewportRowsEnd - 1); bufferRowIndex++; remainingBufferRows--; } bufferRowIndex = this._viewportRowsEnd; while (bufferRowIndex < this._rowsCount && remainingBufferRows > 0) { this._addRowToBuffer(bufferRowIndex, this._viewportRowsBegin, this._viewportRowsEnd - 1); bufferRowIndex++; remainingBufferRows--; } return this._rows; } }, { key: 'getRows', value: function getRows( /*number*/firstRowIndex, /*number*/firstRowOffset) /*array*/{ var top = firstRowOffset; var totalHeight = top; var rowIndex = firstRowIndex; var endIndex = Math.min(firstRowIndex + this._maxVisibleRowCount, this._rowsCount); this._viewportRowsBegin = firstRowIndex; while (rowIndex < endIndex || totalHeight < this._viewportHeight && rowIndex < this._rowsCount) { this._addRowToBuffer(rowIndex, firstRowIndex, endIndex - 1); totalHeight += this._rowHeightGetter(rowIndex); ++rowIndex; // Store index after the last viewport row as end, to be able to // distinguish when there are no rows rendered in viewport this._viewportRowsEnd = rowIndex; } return this._rows; } }, { key: '_addRowToBuffer', value: function _addRowToBuffer( /*number*/rowIndex, /*number*/firstViewportRowIndex, /*number*/lastViewportRowIndex) { var rowPosition = this._bufferSet.getValuePosition(rowIndex); var viewportRowsCount = lastViewportRowIndex - firstViewportRowIndex + 1; var allowedRowsCount = viewportRowsCount + this._bufferRowsCount * 2; if (rowPosition === null && this._bufferSet.getSize() >= allowedRowsCount) { rowPosition = this._bufferSet.replaceFurthestValuePosition(firstViewportRowIndex, lastViewportRowIndex, rowIndex); } if (rowPosition === null) { // We can't reuse any of existing positions for this row. We have to // create new position rowPosition = this._bufferSet.getNewPositionForValue(rowIndex); this._rows[rowPosition] = rowIndex; } else { // This row already is in the table with rowPosition position or it // can replace row that is in that position this._rows[rowPosition] = rowIndex; } } }]); return FixedDataTableRowBuffer; })(); module.exports = FixedDataTableRowBuffer; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule IntegerBufferSet * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Heap = __webpack_require__(59); var invariant = __webpack_require__(55); // Data structure that allows to store values and assign positions to them // in a way to minimize changing positions of stored values when new ones are // added or when some values are replaced. Stored elements are alwasy assigned // a consecutive set of positoins startin from 0 up to count of elements less 1 // Following actions can be executed // * get position assigned to given value (null if value is not stored) // * create new entry for new value and get assigned position back // * replace value that is furthest from specified value range with new value // and get it's position back // All operations take amortized log(n) time where n is number of elements in // the set. var IntegerBufferSet = (function () { function IntegerBufferSet() { _classCallCheck(this, IntegerBufferSet); this._valueToPositionMap = {}; this._size = 0; this._smallValues = new Heap([], // Initial data in the heap this._smallerComparator); this._largeValues = new Heap([], // Initial data in the heap this._greaterComparator); this.getNewPositionForValue = this.getNewPositionForValue.bind(this); this.getValuePosition = this.getValuePosition.bind(this); this.getSize = this.getSize.bind(this); this.replaceFurthestValuePosition = this.replaceFurthestValuePosition.bind(this); } _createClass(IntegerBufferSet, [{ key: 'getSize', value: function getSize() /*number*/{ return this._size; } }, { key: 'getValuePosition', value: function getValuePosition( /*number*/value) /*?number*/{ if (this._valueToPositionMap[value] === undefined) { return null; } return this._valueToPositionMap[value]; } }, { key: 'getNewPositionForValue', value: function getNewPositionForValue( /*number*/value) /*number*/{ invariant(this._valueToPositionMap[value] === undefined, "Shouldn't try to find new position for value already stored in BufferSet"); var newPosition = this._size; this._size++; this._pushToHeaps(newPosition, value); this._valueToPositionMap[value] = newPosition; return newPosition; } }, { key: 'replaceFurthestValuePosition', value: function replaceFurthestValuePosition( /*number*/lowValue, /*number*/highValue, /*number*/newValue) /*?number*/{ invariant(this._valueToPositionMap[newValue] === undefined, "Shouldn't try to replace values with value already stored value in " + "BufferSet"); this._cleanHeaps(); if (this._smallValues.empty() || this._largeValues.empty()) { // Threre are currently no values stored. We will have to create new // position for this value. return null; } var minValue = this._smallValues.peek().value; var maxValue = this._largeValues.peek().value; if (minValue >= lowValue && maxValue <= highValue) { // All values currently stored are necessary, we can't reuse any of them. return null; } var valueToReplace; if (lowValue - minValue > maxValue - highValue) { // minValue is further from provided range. We will reuse it's position. valueToReplace = minValue; this._smallValues.pop(); } else { valueToReplace = maxValue; this._largeValues.pop(); } var position = this._valueToPositionMap[valueToReplace]; delete this._valueToPositionMap[valueToReplace]; this._valueToPositionMap[newValue] = position; this._pushToHeaps(position, newValue); return position; } }, { key: '_pushToHeaps', value: function _pushToHeaps( /*number*/position, /*number*/value) { var element = { position: position, value: value }; // We can reuse the same object in both heaps, because we don't mutate them this._smallValues.push(element); this._largeValues.push(element); } }, { key: '_cleanHeaps', value: function _cleanHeaps() { // We not usually only remove object from one heap while moving value. // Here we make sure that there is no stale data on top of heaps. this._cleanHeap(this._smallValues); this._cleanHeap(this._largeValues); var minHeapSize = Math.min(this._smallValues.size(), this._largeValues.size()); var maxHeapSize = Math.max(this._smallValues.size(), this._largeValues.size()); if (maxHeapSize > 10 * minHeapSize) { // There are many old values in one of heaps. We nned to get rid of them // to not use too avoid memory leaks this._recreateHeaps(); } } }, { key: '_recreateHeaps', value: function _recreateHeaps() { var sourceHeap = this._smallValues.size() < this._largeValues.size() ? this._smallValues : this._largeValues; var newSmallValues = new Heap([], // Initial data in the heap this._smallerComparator); var newLargeValues = new Heap([], // Initial datat in the heap this._greaterComparator); while (!sourceHeap.empty()) { var element = sourceHeap.pop(); // Push all stil valid elements to new heaps if (this._valueToPositionMap[element.value] !== undefined) { newSmallValues.push(element); newLargeValues.push(element); } } this._smallValues = newSmallValues; this._largeValues = newLargeValues; } }, { key: '_cleanHeap', value: function _cleanHeap( /*object*/heap) { while (!heap.empty() && this._valueToPositionMap[heap.peek().value] === undefined) { heap.pop(); } } }, { key: '_smallerComparator', value: function _smallerComparator( /*object*/lhs, /*object*/rhs) /*boolean*/{ return lhs.value < rhs.value; } }, { key: '_greaterComparator', value: function _greaterComparator( /*object*/lhs, /*object*/rhs) /*boolean*/{ return lhs.value > rhs.value; } }]); return IntegerBufferSet; })(); module.exports = IntegerBufferSet; /***/ }, /* 59 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Heap * @typechecks * @preventMunge */ 'use strict'; /* * @param {*} a * @param {*} b * @return {boolean} */ var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function defaultComparator(a, b) { return a < b; } var Heap = (function () { function Heap(items, comparator) { _classCallCheck(this, Heap); this._items = items || []; this._size = this._items.length; this._comparator = comparator || defaultComparator; this._heapify(); } /* * @return {boolean} */ _createClass(Heap, [{ key: 'empty', value: function empty() { return this._size === 0; } /* * @return {*} */ }, { key: 'pop', value: function pop() { if (this._size === 0) { return; } var elt = this._items[0]; var lastElt = this._items.pop(); this._size--; if (this._size > 0) { this._items[0] = lastElt; this._sinkDown(0); } return elt; } /* * @param {*} item */ }, { key: 'push', value: function push(item) { this._items[this._size++] = item; this._bubbleUp(this._size - 1); } /* * @return {number} */ }, { key: 'size', value: function size() { return this._size; } /* * @return {*} */ }, { key: 'peek', value: function peek() { if (this._size === 0) { return; } return this._items[0]; } }, { key: '_heapify', value: function _heapify() { for (var index = Math.floor((this._size + 1) / 2); index >= 0; index--) { this._sinkDown(index); } } /* * @parent {number} index */ }, { key: '_bubbleUp', value: function _bubbleUp(index) { var elt = this._items[index]; while (index > 0) { var parentIndex = Math.floor((index + 1) / 2) - 1; var parentElt = this._items[parentIndex]; // if parentElt < elt, stop if (this._comparator(parentElt, elt)) { return; } // swap this._items[parentIndex] = elt; this._items[index] = parentElt; index = parentIndex; } } /* * @parent {number} index */ }, { key: '_sinkDown', value: function _sinkDown(index) { var elt = this._items[index]; while (true) { var leftChildIndex = 2 * (index + 1) - 1; var rightChildIndex = 2 * (index + 1); var swapIndex = -1; if (leftChildIndex < this._size) { var leftChild = this._items[leftChildIndex]; if (this._comparator(leftChild, elt)) { swapIndex = leftChildIndex; } } if (rightChildIndex < this._size) { var rightChild = this._items[rightChildIndex]; if (this._comparator(rightChild, elt)) { if (swapIndex === -1 || this._comparator(rightChild, this._items[swapIndex])) { swapIndex = rightChildIndex; } } } // if we don't have a swap, stop if (swapIndex === -1) { return; } this._items[index] = this._items[swapIndex]; this._items[swapIndex] = elt; index = swapIndex; } } }]); return Heap; })(); module.exports = Heap; /***/ }, /* 60 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule clamp * @typechecks */ /** * @param {number} min * @param {number} value * @param {number} max * @return {number} */ "use strict"; function clamp(min, value, max) { if (value < min) { return min; } if (value > max) { return max; } return value; } module.exports = clamp; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableRow.react * @typechecks */ 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(29); var ReactComponentWithPureRenderMixin = __webpack_require__(33); var FixedDataTableCellGroup = __webpack_require__(62); var cx = __webpack_require__(50); var joinClasses = __webpack_require__(70); var translateDOMPositionXY = __webpack_require__(51); var PropTypes = React.PropTypes; /** * Component that renders the row for <FixedDataTable />. * This component should not be used directly by developer. Instead, * only <FixedDataTable /> should use the component internally. */ var FixedDataTableRowImpl = React.createClass({ displayName: 'FixedDataTableRowImpl', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * The row data to render. The data format can be a simple Map object * or an Array of data. */ data: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), /** * Array of <FixedDataTableColumn /> for the fixed columns. */ fixedColumns: PropTypes.array.isRequired, /** * Height of the row. */ height: PropTypes.number.isRequired, /** * The row index. */ index: PropTypes.number.isRequired, /** * Array of <FixedDataTableColumn /> for the scrollable columns. */ scrollableColumns: PropTypes.array.isRequired, /** * The distance between the left edge of the table and the leftmost portion * of the row currently visible in the table. */ scrollLeft: PropTypes.number.isRequired, /** * Width of the row. */ width: PropTypes.number.isRequired, /** * Fire when a row is clicked. */ onClick: PropTypes.func, /** * Fire when a row is double clicked. */ onDoubleClick: PropTypes.func, /** * Callback for when resizer knob (in FixedDataTableCell) is clicked * to initialize resizing. Please note this is only on the cells * in the header. * @param number combinedWidth * @param number leftOffset * @param number cellWidth * @param number|string columnKey * @param object event */ onColumnResize: PropTypes.func }, render: function render() /*object*/{ var style = { width: this.props.width, height: this.props.height }; var className = cx({ 'fixedDataTableRowLayout/main': true, 'public/fixedDataTableRow/main': true, 'public/fixedDataTableRow/highlighted': this.props.index % 2 === 1, 'public/fixedDataTableRow/odd': this.props.index % 2 === 1, 'public/fixedDataTableRow/even': this.props.index % 2 === 0 }); var isHeaderOrFooterRow = this.props.index === -1; if (!this.props.data && !isHeaderOrFooterRow) { return React.createElement('div', { className: joinClasses(className, this.props.className), style: style }); } var fixedColumnsWidth = this._getColumnsWidth(this.props.fixedColumns); var fixedColumns = React.createElement(FixedDataTableCellGroup, { key: 'fixed_cells', height: this.props.height, left: 0, width: fixedColumnsWidth, zIndex: 2, columns: this.props.fixedColumns, data: this.props.data, onColumnResize: this.props.onColumnResize, rowHeight: this.props.height, rowIndex: this.props.index }); var columnsShadow = this._renderColumnsShadow(fixedColumnsWidth); var scrollableColumns = React.createElement(FixedDataTableCellGroup, { key: 'scrollable_cells', height: this.props.height, left: this.props.scrollLeft, offsetLeft: fixedColumnsWidth, width: this.props.width - fixedColumnsWidth, zIndex: 0, columns: this.props.scrollableColumns, data: this.props.data, onColumnResize: this.props.onColumnResize, rowHeight: this.props.height, rowIndex: this.props.index }); return React.createElement( 'div', { className: joinClasses(className, this.props.className), onClick: this.props.onClick ? this._onClick : null, onDoubleClick: this.props.onDoubleClick ? this._onDoubleClick : null, onMouseDown: this.props.onMouseDown ? this._onMouseDown : null, onMouseEnter: this.props.onMouseEnter ? this._onMouseEnter : null, onMouseLeave: this.props.onMouseLeave ? this._onMouseLeave : null, style: style }, React.createElement( 'div', { className: cx('fixedDataTableRowLayout/body') }, fixedColumns, scrollableColumns, columnsShadow ) ); }, _getColumnsWidth: function _getColumnsWidth( /*array*/columns) /*number*/{ var width = 0; for (var i = 0; i < columns.length; ++i) { width += columns[i].props.width; } return width; }, _renderColumnsShadow: function _renderColumnsShadow( /*number*/left) /*?object*/{ if (left > 0) { var className = cx({ 'fixedDataTableRowLayout/fixedColumnsDivider': true, 'fixedDataTableRowLayout/columnsShadow': this.props.scrollLeft > 0, 'public/fixedDataTableRow/fixedColumnsDivider': true, 'public/fixedDataTableRow/columnsShadow': this.props.scrollLeft > 0 }); var style = { left: left, height: this.props.height }; return React.createElement('div', { className: className, style: style }); } }, _onClick: function _onClick( /*object*/event) { this.props.onClick(event, this.props.index, this.props.data); }, _onDoubleClick: function _onDoubleClick( /*object*/event) { this.props.onDoubleClick(event, this.props.index, this.props.data); }, _onMouseDown: function _onMouseDown( /*object*/event) { this.props.onMouseDown(event, this.props.index, this.props.data); }, _onMouseEnter: function _onMouseEnter( /*object*/event) { this.props.onMouseEnter(event, this.props.index, this.props.data); }, _onMouseLeave: function _onMouseLeave( /*object*/event) { this.props.onMouseLeave(event, this.props.index, this.props.data); } }); var FixedDataTableRow = React.createClass({ displayName: 'FixedDataTableRow', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * Height of the row. */ height: PropTypes.number.isRequired, /** * Z-index on which the row will be displayed. Used e.g. for keeping * header and footer in front of other rows. */ zIndex: PropTypes.number, /** * The vertical position where the row should render itself */ offsetTop: PropTypes.number.isRequired, /** * Width of the row. */ width: PropTypes.number.isRequired }, render: function render() /*object*/{ var style = { width: this.props.width, height: this.props.height, zIndex: this.props.zIndex ? this.props.zIndex : 0 }; translateDOMPositionXY(style, 0, this.props.offsetTop); return React.createElement( 'div', { style: style, className: cx('fixedDataTableRowLayout/rowWrapper') }, React.createElement(FixedDataTableRowImpl, _extends({}, this.props, { offsetTop: undefined, zIndex: undefined })) ); } }); module.exports = FixedDataTableRow; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableCellGroup.react * @typechecks */ 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var FixedDataTableHelper = __webpack_require__(27); var ImmutableObject = __webpack_require__(63); var React = __webpack_require__(29); var ReactComponentWithPureRenderMixin = __webpack_require__(33); var FixedDataTableCell = __webpack_require__(69); var cx = __webpack_require__(50); var renderToString = FixedDataTableHelper.renderToString; var translateDOMPositionXY = __webpack_require__(51); var PropTypes = React.PropTypes; var DIR_SIGN = FixedDataTableHelper.DIR_SIGN; var EMPTY_OBJECT = new ImmutableObject({}); var FixedDataTableCellGroupImpl = React.createClass({ displayName: 'FixedDataTableCellGroupImpl', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * Array of <FixedDataTableColumn />. */ columns: PropTypes.array.isRequired, /** * The row data to render. The data format can be a simple Map object * or an Array of data. */ data: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), left: PropTypes.number, onColumnResize: PropTypes.func, rowHeight: PropTypes.number.isRequired, rowIndex: PropTypes.number.isRequired, width: PropTypes.number.isRequired, zIndex: PropTypes.number.isRequired }, render: function render() /*object*/{ var props = this.props; var columns = props.columns; var cells = new Array(columns.length); var currentPosition = 0; for (var i = 0, j = columns.length; i < j; i++) { var columnProps = columns[i].props; if (!columnProps.allowCellsRecycling || currentPosition - props.left <= props.width && currentPosition - props.left + columnProps.width >= 0) { var key = 'cell_' + i; cells[i] = this._renderCell(props.data, props.rowIndex, props.rowHeight, columnProps, currentPosition, key); } currentPosition += columnProps.width; } var contentWidth = this._getColumnsWidth(columns); var style = { height: props.height, position: 'absolute', width: contentWidth, zIndex: props.zIndex }; translateDOMPositionXY(style, -1 * DIR_SIGN * props.left, 0); return React.createElement( 'div', { className: cx('fixedDataTableCellGroupLayout/cellGroup'), style: style }, cells ); }, _renderCell: function _renderCell( /*?object|array*/rowData, /*number*/rowIndex, /*number*/height, /*object*/columnProps, /*number*/left, /*string*/key) /*object*/{ var cellRenderer = columnProps.cellRenderer || renderToString; var columnData = columnProps.columnData || EMPTY_OBJECT; var cellDataKey = columnProps.dataKey; var isFooterCell = columnProps.isFooterCell; var isHeaderCell = columnProps.isHeaderCell; var cellData; if (isHeaderCell || isFooterCell) { if (rowData == null || rowData[cellDataKey] == null) { cellData = columnProps.label; } else { cellData = rowData[cellDataKey]; } } else { var cellDataGetter = columnProps.cellDataGetter; cellData = cellDataGetter ? cellDataGetter(cellDataKey, rowData) : rowData[cellDataKey]; } var cellIsResizable = columnProps.isResizable && this.props.onColumnResize; var onColumnResize = cellIsResizable ? this.props.onColumnResize : null; var className; if (isHeaderCell || isFooterCell) { className = isHeaderCell ? columnProps.headerClassName : columnProps.footerClassName; } else { className = columnProps.cellClassName; } return React.createElement(FixedDataTableCell, { align: columnProps.align, cellData: cellData, cellDataKey: cellDataKey, cellRenderer: cellRenderer, className: className, columnData: columnData, height: height, isFooterCell: isFooterCell, isHeaderCell: isHeaderCell, key: key, maxWidth: columnProps.maxWidth, minWidth: columnProps.minWidth, onColumnResize: onColumnResize, rowData: rowData, rowIndex: rowIndex, width: columnProps.width, left: left }); }, _getColumnsWidth: function _getColumnsWidth(columns) { var width = 0; for (var i = 0; i < columns.length; ++i) { width += columns[i].props.width; } return width; } }); var FixedDataTableCellGroup = React.createClass({ displayName: 'FixedDataTableCellGroup', mixins: [ReactComponentWithPureRenderMixin], propTypes: { /** * Height of the row. */ height: PropTypes.number.isRequired, offsetLeft: PropTypes.number, /** * Z-index on which the row will be displayed. Used e.g. for keeping * header and footer in front of other rows. */ zIndex: PropTypes.number.isRequired }, getDefaultProps: function getDefaultProps() /*object*/{ return { offsetLeft: 0 }; }, render: function render() /*object*/{ var _props = this.props; var offsetLeft = _props.offsetLeft; var props = _objectWithoutProperties(_props, ['offsetLeft']); var style = { height: props.height }; if (DIR_SIGN === 1) { style.left = offsetLeft; } else { style.right = offsetLeft; } var onColumnResize = props.onColumnResize ? this._onColumnResize : null; return React.createElement( 'div', { style: style, className: cx('fixedDataTableCellGroupLayout/cellGroupWrapper') }, React.createElement(FixedDataTableCellGroupImpl, _extends({}, props, { onColumnResize: onColumnResize })) ); }, _onColumnResize: function _onColumnResize( /*number*/left, /*number*/width, /*?number*/minWidth, /*?number*/maxWidth, /*string|number*/cellDataKey, /*object*/event) { this.props.onColumnResize && this.props.onColumnResize(this.props.offsetLeft, left - this.props.left + width, width, minWidth, maxWidth, cellDataKey, event); } }); module.exports = FixedDataTableCellGroup; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ImmutableObject * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ImmutableValue = __webpack_require__(64); var invariant = __webpack_require__(55); var keyOf = __webpack_require__(66); var mergeHelpers = __webpack_require__(67); var checkMergeObjectArgs = mergeHelpers.checkMergeObjectArgs; var isTerminal = mergeHelpers.isTerminal; var SECRET_KEY = keyOf({ _DONT_EVER_TYPE_THIS_SECRET_KEY: null }); /** * Static methods creating and operating on instances of `ImmutableValue`. */ function assertImmutable(immutable) { invariant(immutable instanceof ImmutableValue, 'ImmutableObject: Attempted to set fields on an object that is not an ' + 'instance of ImmutableValue.'); } /** * Static methods for reasoning about instances of `ImmutableObject`. Execute * the freeze commands in `__DEV__` mode to alert the programmer that something * is attempting to mutate. Since freezing is very expensive, we avoid doing it * at all in production. */ var ImmutableObject = (function (_ImmutableValue) { _inherits(ImmutableObject, _ImmutableValue); /** * @arguments {array<object>} The arguments is an array of objects that, when * merged together, will form the immutable objects. */ function ImmutableObject() { _classCallCheck(this, ImmutableObject); _get(Object.getPrototypeOf(ImmutableObject.prototype), 'constructor', this).call(this, ImmutableValue[SECRET_KEY]); ImmutableValue.mergeAllPropertiesInto(this, arguments); if (true) { ImmutableValue.deepFreezeRootNode(this); } } /** * DEPRECATED - prefer to instantiate with new ImmutableObject(). * * @arguments {array<object>} The arguments is an array of objects that, when * merged together, will form the immutable objects. */ _createClass(ImmutableObject, null, [{ key: 'create', value: function create() { var obj = Object.create(ImmutableObject.prototype); ImmutableObject.apply(obj, arguments); return obj; } /** * Returns a new `ImmutableValue` that is identical to the supplied * `ImmutableValue` but with the specified changes, `put`. Any keys that are * in the intersection of `immutable` and `put` retain the ordering of * `immutable`. New keys are placed after keys that exist in `immutable`. * * @param {ImmutableValue} immutable Starting object. * @param {?object} put Fields to merge into the object. * @return {ImmutableValue} The result of merging in `put` fields. */ }, { key: 'set', value: function set(immutable, put) { assertImmutable(immutable); invariant(typeof put === 'object' && put !== undefined && !Array.isArray(put), 'Invalid ImmutableMap.set argument `put`'); return new ImmutableObject(immutable, put); } /** * Sugar for `ImmutableObject.set(ImmutableObject, {fieldName: putField})`. * Look out for key crushing: Use `keyOf()` to guard against it. * * @param {ImmutableValue} immutableObject Object on which to set properties. * @param {string} fieldName Name of the field to set. * @param {*} putField Value of the field to set. * @return {ImmutableValue} new ImmutableValue as described in `set`. */ }, { key: 'setProperty', value: function setProperty(immutableObject, fieldName, putField) { var put = {}; put[fieldName] = putField; return ImmutableObject.set(immutableObject, put); } /** * Returns a new immutable object with the given field name removed. * Look out for key crushing: Use `keyOf()` to guard against it. * * @param {ImmutableObject} immutableObject from which to delete the key. * @param {string} droppedField Name of the field to delete. * @return {ImmutableObject} new ImmutableObject without the key */ }, { key: 'deleteProperty', value: function deleteProperty(immutableObject, droppedField) { var copy = {}; for (var key in immutableObject) { if (key !== droppedField && immutableObject.hasOwnProperty(key)) { copy[key] = immutableObject[key]; } } return new ImmutableObject(copy); } /** * Returns a new `ImmutableValue` that is identical to the supplied object but * with the supplied changes recursively applied. * * Experimental. Likely does not handle `Arrays` correctly. * * @param {ImmutableValue} immutable Object on which to set fields. * @param {object} put Fields to merge into the object. * @return {ImmutableValue} The result of merging in `put` fields. */ }, { key: 'setDeep', value: function setDeep(immutable, put) { assertImmutable(immutable); return _setDeep(immutable, put); } /** * Retrieves an ImmutableObject's values as an array. * * @param {ImmutableValue} immutable * @return {array} */ }, { key: 'values', value: function values(immutable) { return Object.keys(immutable).map(function (key) { return immutable[key]; }); } }]); return ImmutableObject; })(ImmutableValue); function _setDeep(obj, put) { checkMergeObjectArgs(obj, put); var totalNewFields = {}; // To maintain the order of the keys, copy the base object's entries first. var keys = Object.keys(obj); for (var ii = 0; ii < keys.length; ii++) { var key = keys[ii]; if (!put.hasOwnProperty(key)) { totalNewFields[key] = obj[key]; } else if (isTerminal(obj[key]) || isTerminal(put[key])) { totalNewFields[key] = put[key]; } else { totalNewFields[key] = _setDeep(obj[key], put[key]); } } // Apply any new keys that the base obj didn't have. var newKeys = Object.keys(put); for (ii = 0; ii < newKeys.length; ii++) { var newKey = newKeys[ii]; if (obj.hasOwnProperty(newKey)) { continue; } totalNewFields[newKey] = put[newKey]; } return obj instanceof ImmutableValue ? new ImmutableObject(totalNewFields) : put instanceof ImmutableValue ? new ImmutableObject(totalNewFields) : totalNewFields; } module.exports = ImmutableObject; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ImmutableValue * @typechecks */ 'use strict'; var invariant = __webpack_require__(55); var isNode = __webpack_require__(65); var keyOf = __webpack_require__(66); var SECRET_KEY = keyOf({ _DONT_EVER_TYPE_THIS_SECRET_KEY: null }); /** * `ImmutableValue` provides a guarantee of immutability at developer time when * strict mode is used. The extra computations required to enforce immutability * are stripped out in production for performance reasons. `ImmutableValue` * guarantees to enforce immutability for enumerable, own properties. This * allows easy wrapping of `ImmutableValue` with the ability to store * non-enumerable properties on the instance that only your static methods * reason about. In order to achieve IE8 compatibility (which doesn't have the * ability to define non-enumerable properties), modules that want to build * their own reasoning of `ImmutableValue`s and store computations can define * their non-enumerable properties under the name `toString`, and in IE8 only * define a standard property called `toString` which will mistakenly be * considered not enumerable due to its name (but only in IE8). The only * limitation is that no one can store their own `toString` property. * https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug */ var ImmutableValue = (function () { /** * An instance of `ImmutableValue` appears to be a plain JavaScript object, * except `instanceof ImmutableValue` evaluates to `true`, and it is deeply * frozen in development mode. * * @param {number} secret Ensures this isn't accidentally constructed outside * of convenience constructors. If created outside of a convenience * constructor, may not be frozen. Forbidding that use case for now until we * have a better API. */ function ImmutableValue(secret) { _classCallCheck(this, ImmutableValue); invariant(secret === ImmutableValue[SECRET_KEY], 'Only certain classes should create instances of `ImmutableValue`.' + 'You probably want something like ImmutableValueObject.create.'); } /** * Helper method for classes that make use of `ImmutableValue`. * @param {ImmutableValue} destination Object to merge properties into. * @param {object} propertyObjects List of objects to merge into * `destination`. */ _createClass(ImmutableValue, null, [{ key: 'mergeAllPropertiesInto', value: function mergeAllPropertiesInto(destination, propertyObjects) { var argLength = propertyObjects.length; for (var i = 0; i < argLength; i++) { _extends(destination, propertyObjects[i]); } } /** * Freezes the supplied object deeply. Other classes may implement their own * version based on this. * * @param {*} object The object to freeze. */ }, { key: 'deepFreezeRootNode', value: function deepFreezeRootNode(object) { if (isNode(object)) { return; // Don't try to freeze DOM nodes. } Object.freeze(object); // First freeze the object. for (var prop in object) { if (object.hasOwnProperty(prop)) { ImmutableValue.recurseDeepFreeze(object[prop]); } } Object.seal(object); } /** * Differs from `deepFreezeRootNode`, in that we first check if this is a * necessary recursion. If the object is already an `ImmutableValue`, then the * recursion is unnecessary as it is already frozen. That check obviously * wouldn't work for the root node version `deepFreezeRootNode`! */ }, { key: 'recurseDeepFreeze', value: function recurseDeepFreeze(object) { if (isNode(object) || !ImmutableValue.shouldRecurseFreeze(object)) { return; // Don't try to freeze DOM nodes. } Object.freeze(object); // First freeze the object. for (var prop in object) { if (object.hasOwnProperty(prop)) { ImmutableValue.recurseDeepFreeze(object[prop]); } } Object.seal(object); } /** * Checks if an object should be deep frozen. Instances of `ImmutableValue` * are assumed to have already been deep frozen, so we can have large * `__DEV__` time savings by skipping freezing of them. * * @param {*} object The object to check. * @return {boolean} Whether or not deep freeze is needed. */ }, { key: 'shouldRecurseFreeze', value: function shouldRecurseFreeze(object) { return typeof object === 'object' && !(object instanceof ImmutableValue) && object !== null; } }]); return ImmutableValue; })(); ImmutableValue._DONT_EVER_TYPE_THIS_SECRET_KEY = Math.random(); module.exports = ImmutableValue; /***/ }, /* 65 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ 'use strict'; function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }, /* 66 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function keyOf(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mergeHelpers * * requiresPolyfills: Array.isArray */ 'use strict'; var invariant = __webpack_require__(55); var keyMirror = __webpack_require__(68); /** * Maximum number of levels to traverse. Will catch circular structures. * @const */ var MAX_MERGE_DEPTH = 36; /** * We won't worry about edge cases like new String('x') or new Boolean(true). * Functions and Dates are considered terminals, and arrays are not. * @param {*} o The item/object/value to test. * @return {boolean} true iff the argument is a terminal. */ var isTerminal = function isTerminal(o) { return typeof o !== 'object' || o instanceof Date || o === null; }; var mergeHelpers = { MAX_MERGE_DEPTH: MAX_MERGE_DEPTH, isTerminal: isTerminal, /** * Converts null/undefined values into empty object. * * @param {?Object=} arg Argument to be normalized (nullable optional) * @return {!Object} */ normalizeMergeArg: function normalizeMergeArg(arg) { return arg === undefined || arg === null ? {} : arg; }, /** * If merging Arrays, a merge strategy *must* be supplied. If not, it is * likely the caller's fault. If this function is ever called with anything * but `one` and `two` being `Array`s, it is the fault of the merge utilities. * * @param {*} one Array to merge into. * @param {*} two Array to merge from. */ checkMergeArrayArgs: function checkMergeArrayArgs(one, two) { invariant(Array.isArray(one) && Array.isArray(two), 'Tried to merge arrays, instead got %s and %s.', one, two); }, /** * @param {*} one Object to merge into. * @param {*} two Object to merge from. */ checkMergeObjectArgs: function checkMergeObjectArgs(one, two) { mergeHelpers.checkMergeObjectArg(one); mergeHelpers.checkMergeObjectArg(two); }, /** * @param {*} arg */ checkMergeObjectArg: function checkMergeObjectArg(arg) { invariant(!isTerminal(arg) && !Array.isArray(arg), 'Tried to merge an object, instead got %s.', arg); }, /** * @param {*} arg */ checkMergeIntoObjectArg: function checkMergeIntoObjectArg(arg) { invariant((!isTerminal(arg) || typeof arg === 'function') && !Array.isArray(arg), 'Tried to merge into an object, instead got %s.', arg); }, /** * Checks that a merge was not given a circular object or an object that had * too great of depth. * * @param {number} Level of recursion to validate against maximum. */ checkMergeLevel: function checkMergeLevel(level) { invariant(level < MAX_MERGE_DEPTH, 'Maximum deep merge depth exceeded. You may be attempting to merge ' + 'circular structures in an unsupported way.'); }, /** * Checks that the supplied merge strategy is valid. * * @param {string} Array merge strategy. */ checkArrayStrategy: function checkArrayStrategy(strategy) { invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies, 'You must provide an array strategy to deep merge functions to ' + 'instruct the deep merge how to resolve merging two arrays.'); }, /** * Set of possible behaviors of merge algorithms when encountering two Arrays * that must be merged together. * - `clobber`: The left `Array` is ignored. * - `indexByIndex`: The result is achieved by recursively deep merging at * each index. (not yet supported.) */ ArrayStrategies: keyMirror({ Clobber: true, IndexByIndex: true }) }; module.exports = mergeHelpers; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(55); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function keyMirror(obj) { var ret = {}; var key; invariant(obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.'); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableCell.react * @typechecks */ 'use strict'; var FixedDataTableHelper = __webpack_require__(27); var ImmutableObject = __webpack_require__(63); var React = __webpack_require__(29); var ReactComponentWithPureRenderMixin = __webpack_require__(33); var cx = __webpack_require__(50); var joinClasses = __webpack_require__(70); var DIR_SIGN = FixedDataTableHelper.DIR_SIGN; var PropTypes = React.PropTypes; var DEFAULT_PROPS = new ImmutableObject({ align: 'left', highlighted: false, isFooterCell: false, isHeaderCell: false }); var FixedDataTableCell = React.createClass({ displayName: 'FixedDataTableCell', mixins: [ReactComponentWithPureRenderMixin], propTypes: { align: PropTypes.oneOf(['left', 'center', 'right']), className: PropTypes.string, highlighted: PropTypes.bool, isFooterCell: PropTypes.bool, isHeaderCell: PropTypes.bool, width: PropTypes.number.isRequired, minWidth: PropTypes.number, maxWidth: PropTypes.number, height: PropTypes.number.isRequired, /** * The cell data that will be passed to `cellRenderer` to render. */ cellData: PropTypes.any, /** * The key to retrieve the cell data from the `rowData`. */ cellDataKey: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.number.isRequired]), /** * The function to render the `cellData`. */ cellRenderer: PropTypes.func.isRequired, /** * The column data that will be passed to `cellRenderer` to render. */ columnData: PropTypes.any, /** * The row data that will be passed to `cellRenderer` to render. */ rowData: PropTypes.oneOfType([PropTypes.object.isRequired, PropTypes.array.isRequired]), /** * The row index that will be passed to `cellRenderer` to render. */ rowIndex: PropTypes.number.isRequired, /** * Callback for when resizer knob (in FixedDataTableCell) is clicked * to initialize resizing. Please note this is only on the cells * in the header. * @param number combinedWidth * @param number left * @param number width * @param number minWidth * @param number maxWidth * @param number|string columnKey * @param object event */ onColumnResize: PropTypes.func, /** * The left offset in pixels of the cell. */ left: PropTypes.number }, getDefaultProps: function getDefaultProps() /*object*/{ return DEFAULT_PROPS; }, render: function render() /*object*/{ var props = this.props; var style = { height: props.height, width: props.width }; if (DIR_SIGN === 1) { style.left = props.left; } else { style.right = props.left; } var className = joinClasses(cx({ 'fixedDataTableCellLayout/main': true, 'fixedDataTableCellLayout/lastChild': props.lastChild, 'fixedDataTableCellLayout/alignRight': props.align === 'right', 'fixedDataTableCellLayout/alignCenter': props.align === 'center', 'public/fixedDataTableCell/alignRight': props.align === 'right', 'public/fixedDataTableCell/highlighted': props.highlighted, 'public/fixedDataTableCell/main': true }), props.className); var content; if (props.isHeaderCell || props.isFooterCell) { content = props.cellRenderer(props.cellData, props.cellDataKey, props.columnData, props.rowData, props.width); } else { content = props.cellRenderer(props.cellData, props.cellDataKey, props.rowData, props.rowIndex, props.columnData, props.width); } var contentClass = cx('public/fixedDataTableCell/cellContent'); if (React.isValidElement(content)) { content = React.cloneElement(content, { className: joinClasses(content.props.className, contentClass) }); } else { content = React.createElement( 'div', { className: contentClass }, content ); } var columnResizerComponent; if (props.onColumnResize) { var columnResizerStyle = { height: props.height }; columnResizerComponent = React.createElement( 'div', { className: cx('fixedDataTableCellLayout/columnResizerContainer'), style: columnResizerStyle, onMouseDown: this._onColumnResizerMouseDown }, React.createElement('div', { className: joinClasses(cx('fixedDataTableCellLayout/columnResizerKnob'), cx('public/fixedDataTableCell/columnResizerKnob')), style: columnResizerStyle }) ); } var innerStyle = { height: props.height, width: props.width }; return React.createElement( 'div', { className: className, style: style }, columnResizerComponent, React.createElement( 'div', { className: joinClasses(cx('fixedDataTableCellLayout/wrap1'), cx('public/fixedDataTableCell/wrap1')), style: innerStyle }, React.createElement( 'div', { className: joinClasses(cx('fixedDataTableCellLayout/wrap2'), cx('public/fixedDataTableCell/wrap2')) }, React.createElement( 'div', { className: joinClasses(cx('fixedDataTableCellLayout/wrap3'), cx('public/fixedDataTableCell/wrap3')) }, content ) ) ) ); }, _onColumnResizerMouseDown: function _onColumnResizerMouseDown( /*object*/event) { this.props.onColumnResize(this.props.left, this.props.width, this.props.minWidth, this.props.maxWidth, this.props.cellDataKey, event); } }); module.exports = FixedDataTableCell; /***/ }, /* 70 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} className * @return {string} */ function joinClasses(className /*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * This is to be used with the FixedDataTable. It is a read line * that when you click on a column that is resizable appears and allows * you to resize the corresponding column. * * @providesModule FixedDataTableColumnResizeHandle.react * @typechecks */ 'use strict'; var DOMMouseMoveTracker = __webpack_require__(43); var Locale = __webpack_require__(28); var React = __webpack_require__(29); var ReactComponentWithPureRenderMixin = __webpack_require__(33); var clamp = __webpack_require__(60); var cx = __webpack_require__(50); var PropTypes = React.PropTypes; var FixedDataTableColumnResizeHandle = React.createClass({ displayName: 'FixedDataTableColumnResizeHandle', mixins: [ReactComponentWithPureRenderMixin], propTypes: { visible: PropTypes.bool.isRequired, /** * This is the height of the line */ height: PropTypes.number.isRequired, /** * Offset from left border of the table, please note * that the line is a border on diff. So this is really the * offset of the column itself. */ leftOffset: PropTypes.number.isRequired, /** * Height of the clickable region of the line. * This is assumed to be at the top of the line. */ knobHeight: PropTypes.number.isRequired, /** * The line is a border on a diff, so this is essentially * the width of column. */ initialWidth: PropTypes.number, /** * The minimum width this dragger will collapse to */ minWidth: PropTypes.number, /** * The maximum width this dragger will collapse to */ maxWidth: PropTypes.number, /** * Initial click event on the header cell. */ initialEvent: PropTypes.object, /** * When resizing is complete this is called. */ onColumnResizeEnd: PropTypes.func, /** * Column key for the column being resized. */ columnKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }, getInitialState: function getInitialState() /*object*/{ return { width: 0, cursorDelta: 0 }; }, componentWillReceiveProps: function componentWillReceiveProps( /*object*/newProps) { if (newProps.initialEvent && !this._mouseMoveTracker.isDragging()) { this._mouseMoveTracker.captureMouseMoves(newProps.initialEvent); this.setState({ width: newProps.initialWidth, cursorDelta: newProps.initialWidth }); } }, componentDidMount: function componentDidMount() { this._mouseMoveTracker = new DOMMouseMoveTracker(this._onMove, this._onColumnResizeEnd, document.body); }, componentWillUnmount: function componentWillUnmount() { this._mouseMoveTracker.releaseMouseMoves(); this._mouseMoveTracker = null; }, render: function render() /*object*/{ var style = { width: this.state.width, height: this.props.height }; if (Locale.isRTL()) { style.right = this.props.leftOffset; } else { style.left = this.props.leftOffset; } return React.createElement( 'div', { className: cx({ 'fixedDataTableColumnResizerLineLayout/main': true, 'fixedDataTableColumnResizerLineLayout/hiddenElem': !this.props.visible, 'public/fixedDataTableColumnResizerLine/main': true }), style: style }, React.createElement('div', { className: cx('fixedDataTableColumnResizerLineLayout/mouseArea'), style: { height: this.props.height } }) ); }, _onMove: function _onMove( /*number*/deltaX) { if (Locale.isRTL()) { deltaX = -deltaX; } var newWidth = this.state.cursorDelta + deltaX; var newColumnWidth = clamp(this.props.minWidth, newWidth, this.props.maxWidth); // Please note cursor delta is the different between the currently width // and the new width. this.setState({ width: newColumnWidth, cursorDelta: newWidth }); }, _onColumnResizeEnd: function _onColumnResizeEnd() { this._mouseMoveTracker.releaseMouseMoves(); this.props.onColumnResizeEnd(this.state.width, this.props.columnKey); } }); module.exports = FixedDataTableColumnResizeHandle; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableScrollHelper * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var PrefixIntervalTree = __webpack_require__(73); var clamp = __webpack_require__(60); var BUFFER_ROWS = 5; var NO_ROWS_SCROLL_RESULT = { index: 0, offset: 0, position: 0, contentHeight: 0 }; var FixedDataTableScrollHelper = (function () { function FixedDataTableScrollHelper( /*number*/rowCount, /*number*/defaultRowHeight, /*number*/viewportHeight, /*?function*/rowHeightGetter) { _classCallCheck(this, FixedDataTableScrollHelper); this._rowOffsets = PrefixIntervalTree.uniform(rowCount, defaultRowHeight); this._storedHeights = new Array(rowCount); for (var i = 0; i < rowCount; ++i) { this._storedHeights[i] = defaultRowHeight; } this._rowCount = rowCount; this._position = 0; this._contentHeight = rowCount * defaultRowHeight; this._defaultRowHeight = defaultRowHeight; this._rowHeightGetter = rowHeightGetter ? rowHeightGetter : function () { return defaultRowHeight; }; this._viewportHeight = viewportHeight; this.scrollRowIntoView = this.scrollRowIntoView.bind(this); this.setViewportHeight = this.setViewportHeight.bind(this); this.scrollBy = this.scrollBy.bind(this); this.scrollTo = this.scrollTo.bind(this); this.scrollToRow = this.scrollToRow.bind(this); this.setRowHeightGetter = this.setRowHeightGetter.bind(this); this.getContentHeight = this.getContentHeight.bind(this); this.getRowPosition = this.getRowPosition.bind(this); this._updateHeightsInViewport(0, 0); } _createClass(FixedDataTableScrollHelper, [{ key: 'setRowHeightGetter', value: function setRowHeightGetter( /*function*/rowHeightGetter) { this._rowHeightGetter = rowHeightGetter; } }, { key: 'setViewportHeight', value: function setViewportHeight( /*number*/viewportHeight) { this._viewportHeight = viewportHeight; } }, { key: 'getContentHeight', value: function getContentHeight() /*number*/{ return this._contentHeight; } }, { key: '_updateHeightsInViewport', value: function _updateHeightsInViewport( /*number*/firstRowIndex, /*number*/firstRowOffset) { var top = firstRowOffset; var index = firstRowIndex; while (top <= this._viewportHeight && index < this._rowCount) { this._updateRowHeight(index); top += this._storedHeights[index]; index++; } } }, { key: '_updateHeightsAboveViewport', value: function _updateHeightsAboveViewport( /*number*/firstRowIndex) { var index = firstRowIndex - 1; while (index >= 0 && index >= firstRowIndex - BUFFER_ROWS) { var delta = this._updateRowHeight(index); this._position += delta; index--; } } }, { key: '_updateRowHeight', value: function _updateRowHeight( /*number*/rowIndex) /*number*/{ if (rowIndex < 0 || rowIndex >= this._rowCount) { return 0; } var newHeight = this._rowHeightGetter(rowIndex); if (newHeight !== this._storedHeights[rowIndex]) { var change = newHeight - this._storedHeights[rowIndex]; this._rowOffsets.set(rowIndex, newHeight); this._storedHeights[rowIndex] = newHeight; this._contentHeight += change; return change; } return 0; } }, { key: 'getRowPosition', value: function getRowPosition( /*number*/rowIndex) /*number*/{ this._updateRowHeight(rowIndex); return this._rowOffsets.sumUntil(rowIndex); } }, { key: 'scrollBy', value: function scrollBy( /*number*/delta) /*object*/{ if (this._rowCount === 0) { return NO_ROWS_SCROLL_RESULT; } var firstRow = this._rowOffsets.greatestLowerBound(this._position); firstRow = clamp(0, firstRow, Math.max(this._rowCount - 1, 0)); var firstRowPosition = this._rowOffsets.sumUntil(firstRow); var rowIndex = firstRow; var position = this._position; var rowHeightChange = this._updateRowHeight(rowIndex); if (firstRowPosition !== 0) { position += rowHeightChange; } var visibleRowHeight = this._storedHeights[rowIndex] - (position - firstRowPosition); if (delta >= 0) { while (delta > 0 && rowIndex < this._rowCount) { if (delta < visibleRowHeight) { position += delta; delta = 0; } else { delta -= visibleRowHeight; position += visibleRowHeight; rowIndex++; } if (rowIndex < this._rowCount) { this._updateRowHeight(rowIndex); visibleRowHeight = this._storedHeights[rowIndex]; } } } else if (delta < 0) { delta = -delta; var invisibleRowHeight = this._storedHeights[rowIndex] - visibleRowHeight; while (delta > 0 && rowIndex >= 0) { if (delta < invisibleRowHeight) { position -= delta; delta = 0; } else { position -= invisibleRowHeight; delta -= invisibleRowHeight; rowIndex--; } if (rowIndex >= 0) { var change = this._updateRowHeight(rowIndex); invisibleRowHeight = this._storedHeights[rowIndex]; position += change; } } } var maxPosition = this._contentHeight - this._viewportHeight; position = clamp(0, position, maxPosition); this._position = position; var firstRowIndex = this._rowOffsets.greatestLowerBound(position); firstRowIndex = clamp(0, firstRowIndex, Math.max(this._rowCount - 1, 0)); firstRowPosition = this._rowOffsets.sumUntil(firstRowIndex); var firstRowOffset = firstRowPosition - position; this._updateHeightsInViewport(firstRowIndex, firstRowOffset); this._updateHeightsAboveViewport(firstRowIndex); return { index: firstRowIndex, offset: firstRowOffset, position: this._position, contentHeight: this._contentHeight }; } }, { key: '_getRowAtEndPosition', value: function _getRowAtEndPosition( /*number*/rowIndex) /*number*/{ // We need to update enough rows above the selected one to be sure that when // we scroll to selected position all rows between first shown and selected // one have most recent heights computed and will not resize this._updateRowHeight(rowIndex); var currentRowIndex = rowIndex; var top = this._storedHeights[currentRowIndex]; while (top < this._viewportHeight && currentRowIndex >= 0) { currentRowIndex--; if (currentRowIndex >= 0) { this._updateRowHeight(currentRowIndex); top += this._storedHeights[currentRowIndex]; } } var position = this._rowOffsets.sumTo(rowIndex) - this._viewportHeight; if (position < 0) { position = 0; } return position; } }, { key: 'scrollTo', value: function scrollTo( /*number*/position) /*object*/{ if (this._rowCount === 0) { return NO_ROWS_SCROLL_RESULT; } if (position <= 0) { // If position less than or equal to 0 first row should be fully visible // on top this._position = 0; this._updateHeightsInViewport(0, 0); return { index: 0, offset: 0, position: this._position, contentHeight: this._contentHeight }; } else if (position >= this._contentHeight - this._viewportHeight) { // If position is equal to or greater than max scroll value, we need // to make sure to have bottom border of last row visible. var rowIndex = this._rowCount - 1; position = this._getRowAtEndPosition(rowIndex); } this._position = position; var firstRowIndex = this._rowOffsets.greatestLowerBound(position); firstRowIndex = clamp(0, firstRowIndex, Math.max(this._rowCount - 1, 0)); var firstRowPosition = this._rowOffsets.sumUntil(firstRowIndex); var firstRowOffset = firstRowPosition - position; this._updateHeightsInViewport(firstRowIndex, firstRowOffset); this._updateHeightsAboveViewport(firstRowIndex); return { index: firstRowIndex, offset: firstRowOffset, position: this._position, contentHeight: this._contentHeight }; } /** * Allows to scroll to selected row with specified offset. It always * brings that row to top of viewport with that offset */ }, { key: 'scrollToRow', value: function scrollToRow( /*number*/rowIndex, /*number*/offset) /*object*/{ rowIndex = clamp(0, rowIndex, Math.max(this._rowCount - 1, 0)); offset = clamp(-this._storedHeights[rowIndex], offset, 0); var firstRow = this._rowOffsets.sumUntil(rowIndex); return this.scrollTo(firstRow - offset); } /** * Allows to scroll to selected row by bringing it to viewport with minimal * scrolling. This that if row is fully visible, scroll will not be changed. * If top border of row is above top of viewport it will be scrolled to be * fully visible on the top of viewport. If the bottom border of row is * below end of viewport, it will be scrolled up to be fully visible on the * bottom of viewport. */ }, { key: 'scrollRowIntoView', value: function scrollRowIntoView( /*number*/rowIndex) /*object*/{ rowIndex = clamp(0, rowIndex, Math.max(this._rowCount - 1, 0)); var rowBegin = this._rowOffsets.sumUntil(rowIndex); var rowEnd = rowBegin + this._storedHeights[rowIndex]; if (rowBegin < this._position) { return this.scrollTo(rowBegin); } else if (this._position + this._viewportHeight < rowEnd) { var position = this._getRowAtEndPosition(rowIndex); return this.scrollTo(position); } return this.scrollTo(this._position); } }]); return FixedDataTableScrollHelper; })(); module.exports = FixedDataTableScrollHelper; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PrefixIntervalTree * * @typechecks */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var invariant = __webpack_require__(55); var parent = function parent(node) { return Math.floor(node / 2); }; var Int32Array = global.Int32Array || function (size) { var xs = []; for (var i = size - 1; i >= 0; --i) { xs[i] = 0; } return xs; }; /** * Computes the next power of 2 after or equal to x. */ function ceilLog2(x) { var y = 1; while (y < x) { y *= 2; } return y; } /** * A prefix interval tree stores an numeric array and the partial sums of that * array. It is optimized for updating the values of the array without * recomputing all of the partial sums. * * - O(ln n) update * - O(1) lookup * - O(ln n) compute a partial sum * - O(n) space * * Note that the sequence of partial sums is one longer than the array, so that * the first partial sum is always 0, and the last partial sum is the sum of the * entire array. */ var PrefixIntervalTree = (function () { function PrefixIntervalTree(xs) { _classCallCheck(this, PrefixIntervalTree); this._size = xs.length; this._half = ceilLog2(this._size); this._heap = new Int32Array(2 * this._half); var i; for (i = 0; i < this._size; ++i) { this._heap[this._half + i] = xs[i]; } for (i = this._half - 1; i > 0; --i) { this._heap[i] = this._heap[2 * i] + this._heap[2 * i + 1]; } } _createClass(PrefixIntervalTree, [{ key: 'set', value: function set(index, value) { invariant(0 <= index && index < this._size, 'Index out of range %s', index); var node = this._half + index; this._heap[node] = value; node = parent(node); for (; node !== 0; node = parent(node)) { this._heap[node] = this._heap[2 * node] + this._heap[2 * node + 1]; } } }, { key: 'get', value: function get(index) { invariant(0 <= index && index < this._size, 'Index out of range %s', index); var node = this._half + index; return this._heap[node]; } }, { key: 'getSize', value: function getSize() { return this._size; } /** * Returns the sum get(0) + get(1) + ... + get(end - 1). */ }, { key: 'sumUntil', value: function sumUntil(end) { invariant(0 <= end && end < this._size + 1, 'Index out of range %s', end); if (end === 0) { return 0; } var node = this._half + end - 1; var sum = this._heap[node]; for (; node !== 1; node = parent(node)) { if (node % 2 === 1) { sum += this._heap[node - 1]; } } return sum; } /** * Returns the sum get(0) + get(1) + ... + get(inclusiveEnd). */ }, { key: 'sumTo', value: function sumTo(inclusiveEnd) { invariant(0 <= inclusiveEnd && inclusiveEnd < this._size, 'Index out of range %s', inclusiveEnd); return this.sumUntil(inclusiveEnd + 1); } /** * Returns the sum get(begin) + get(begin + 1) + ... + get(end - 1). */ }, { key: 'sum', value: function sum(begin, end) { invariant(begin <= end, 'Begin must precede end'); return this.sumUntil(end) - this.sumUntil(begin); } /** * Returns the smallest i such that 0 <= i <= size and sumUntil(i) <= t, or * -1 if no such i exists. */ }, { key: 'greatestLowerBound', value: function greatestLowerBound(t) { if (t < 0) { return -1; } var node = 1; if (this._heap[node] <= t) { return this._size; } while (node < this._half) { var leftSum = this._heap[2 * node]; if (t < leftSum) { node = 2 * node; } else { node = 2 * node + 1; t -= leftSum; } } return node - this._half; } /** * Returns the smallest i such that 0 <= i <= size and sumUntil(i) < t, or * -1 if no such i exists. */ }, { key: 'greatestStrictLowerBound', value: function greatestStrictLowerBound(t) { if (t <= 0) { return -1; } var node = 1; if (this._heap[node] < t) { return this._size; } while (node < this._half) { var leftSum = this._heap[2 * node]; if (t <= leftSum) { node = 2 * node; } else { node = 2 * node + 1; t -= leftSum; } } return node - this._half; } /** * Returns the smallest i such that 0 <= i <= size and t <= sumUntil(i), or * size + 1 if no such i exists. */ }, { key: 'leastUpperBound', value: function leastUpperBound(t) { return this.greatestStrictLowerBound(t) + 1; } /** * Returns the smallest i such that 0 <= i <= size and t < sumUntil(i), or * size + 1 if no such i exists. */ }, { key: 'leastStrictUpperBound', value: function leastStrictUpperBound(t) { return this.greatestLowerBound(t) + 1; } }], [{ key: 'uniform', value: function uniform(size, initialValue) { var xs = []; for (var i = size - 1; i >= 0; --i) { xs[i] = initialValue; } return new PrefixIntervalTree(xs); } }, { key: 'empty', value: function empty(size) { return PrefixIntervalTree.uniform(size, 0); } }]); return PrefixIntervalTree; })(); module.exports = PrefixIntervalTree; /** * Number of elements in the array */ /** * Half the size of the heap. It is also the number of non-leaf nodes, and the * index of the first element in the heap. Always a power of 2. */ /** * Binary heap */ /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FixedDataTableWidthHelper * @typechecks */ 'use strict'; var React = __webpack_require__(29); function getTotalWidth( /*array*/columns) /*number*/{ var totalWidth = 0; for (var i = 0; i < columns.length; ++i) { totalWidth += columns[i].props.width; } return totalWidth; } function getTotalFlexGrow( /*array*/columns) /*number*/{ var totalFlexGrow = 0; for (var i = 0; i < columns.length; ++i) { totalFlexGrow += columns[i].props.flexGrow || 0; } return totalFlexGrow; } function distributeFlexWidth( /*array*/columns, /*number*/flexWidth) /*object*/{ if (flexWidth <= 0) { return { columns: columns, width: getTotalWidth(columns) }; } var remainingFlexGrow = getTotalFlexGrow(columns); var remainingFlexWidth = flexWidth; var newColumns = []; var totalWidth = 0; for (var i = 0; i < columns.length; ++i) { var column = columns[i]; if (!column.props.flexGrow) { totalWidth += column.props.width; newColumns.push(column); continue; } var columnFlexWidth = Math.floor(column.props.flexGrow / remainingFlexGrow * remainingFlexWidth); var newColumnWidth = Math.floor(column.props.width + columnFlexWidth); totalWidth += newColumnWidth; remainingFlexGrow -= column.props.flexGrow; remainingFlexWidth -= columnFlexWidth; newColumns.push(React.cloneElement(column, { width: newColumnWidth })); } return { columns: newColumns, width: totalWidth }; } function adjustColumnGroupWidths( /*array*/columnGroups, /*number*/expectedWidth) /*object*/{ var allColumns = []; var i; for (i = 0; i < columnGroups.length; ++i) { React.Children.forEach(columnGroups[i].props.children, function (column) { allColumns.push(column); }); } var columnsWidth = getTotalWidth(allColumns); var remainingFlexGrow = getTotalFlexGrow(allColumns); var remainingFlexWidth = Math.max(expectedWidth - columnsWidth, 0); var newAllColumns = []; var newColumnGroups = []; for (i = 0; i < columnGroups.length; ++i) { var columnGroup = columnGroups[i]; var currentColumns = []; React.Children.forEach(columnGroup.props.children, function (column) { currentColumns.push(column); }); var columnGroupFlexGrow = getTotalFlexGrow(currentColumns); var columnGroupFlexWidth = Math.floor(columnGroupFlexGrow / remainingFlexGrow * remainingFlexWidth); var newColumnSettings = distributeFlexWidth(currentColumns, columnGroupFlexWidth); remainingFlexGrow -= columnGroupFlexGrow; remainingFlexWidth -= columnGroupFlexWidth; for (var j = 0; j < newColumnSettings.columns.length; ++j) { newAllColumns.push(newColumnSettings.columns[j]); } newColumnGroups.push(React.cloneElement(columnGroup, { width: newColumnSettings.width })); } return { columns: newAllColumns, columnGroups: newColumnGroups }; } function adjustColumnWidths( /*array*/columns, /*number*/expectedWidth) /*array*/{ var columnsWidth = getTotalWidth(columns); if (columnsWidth < expectedWidth) { return distributeFlexWidth(columns, expectedWidth - columnsWidth).columns; } return columns; } var FixedDataTableWidthHelper = { getTotalWidth: getTotalWidth, getTotalFlexGrow: getTotalFlexGrow, distributeFlexWidth: distributeFlexWidth, adjustColumnWidths: adjustColumnWidths, adjustColumnGroupWidths: adjustColumnGroupWidths }; module.exports = FixedDataTableWidthHelper; /***/ }, /* 75 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule debounceCore * @typechecks */ /** * Invokes the given callback after a specified number of milliseconds have * elapsed, ignoring subsequent calls. * * For example, if you wanted to update a preview after the user stops typing * you could do the following: * * elem.addEventListener('keyup', debounce(this.updatePreview, 250), false); * * The returned function has a reset method which can be called to cancel a * pending invocation. * * var debouncedUpdatePreview = debounce(this.updatePreview, 250); * elem.addEventListener('keyup', debouncedUpdatePreview, false); * * // later, to cancel pending calls * debouncedUpdatePreview.reset(); * * @param {function} func - the function to debounce * @param {number} wait - how long to wait in milliseconds * @param {*} context - optional context to invoke the function in * @param {?function} setTimeoutFunc - an implementation of setTimeout * if nothing is passed in the default setTimeout function is used * @param {?function} clearTimeoutFunc - an implementation of clearTimeout * if nothing is passed in the default clearTimeout function is used */ "use strict"; function debounce(func, wait, context, setTimeoutFunc, clearTimeoutFunc) { setTimeoutFunc = setTimeoutFunc || setTimeout; clearTimeoutFunc = clearTimeoutFunc || clearTimeout; var timeout; function debouncer() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } debouncer.reset(); var callback = function callback() { func.apply(context, args); }; callback.__SMmeta = func.__SMmeta; timeout = setTimeoutFunc(callback, wait); } debouncer.reset = function () { clearTimeoutFunc(timeout); }; return debouncer; } module.exports = debounce; /***/ }, /* 76 */ /***/ function(module, exports) { /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; /***/ } /******/ ]) }); ;
agpl-3.0