code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/*********************************************************************************** * * * Voreen - The Volume Rendering Engine * * * * Copyright (C) 2005-2013 University of Muenster, Germany. * * Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> * * For a list of authors please refer to the file "CREDITS.txt". * * * * This file is part of the Voreen software package. Voreen is free software: * * you can redistribute it and/or modify it under the terms of the GNU General * * Public License version 2 as published by the Free Software Foundation. * * * * Voreen 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 in the file * * "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. * * * * For non-commercial academic use see the license exception specified in the file * * "LICENSE-academic.txt". To get information about commercial licensing please * * contact the authors. * * * ***********************************************************************************/ #include "shiftscaleimagefilter.h" #include "voreen/core/datastructures/volume/volumeram.h" #include "voreen/core/datastructures/volume/volume.h" #include "voreen/core/datastructures/volume/volumeatomic.h" #include "voreen/core/ports/conditions/portconditionvolumetype.h" #include "modules/itk/utils/itkwrapper.h" #include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h" #include "itkImage.h" #include "itkShiftScaleImageFilter.h" #include <iostream> namespace voreen { const std::string ShiftScaleImageFilterITK::loggerCat_("voreen.ShiftScaleImageFilterITK"); ShiftScaleImageFilterITK::ShiftScaleImageFilterITK() : ITKProcessor(), inport1_(Port::INPORT, "InputImage"), outport1_(Port::OUTPORT, "OutputImage"), enableProcessing_("enabled", "Enable", false), scale_("scale", "Scale", 1.0f, 0.0f, 5000.0f), shift_("shift", "Shift", 1.0f, 0.0f, 5000.0f) { addPort(inport1_); PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr(); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble()); inport1_.addCondition(orCondition1); addPort(outport1_); addProperty(enableProcessing_); addProperty(scale_); addProperty(shift_); } Processor* ShiftScaleImageFilterITK::create() const { return new ShiftScaleImageFilterITK(); } template<class T> void ShiftScaleImageFilterITK::shiftScaleImageFilterITK() { if (!enableProcessing_.get()) { outport1_.setData(inport1_.getData(), false); return; } typedef itk::Image<T, 3> InputImageType1; typedef itk::Image<T, 3> OutputImageType1; typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData()); //Filter define typedef itk::ShiftScaleImageFilter<InputImageType1, OutputImageType1> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetScale(scale_.get()); filter->SetShift(shift_.get()); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } void ShiftScaleImageFilterITK::process() { const VolumeBase* inputHandle1 = inport1_.getData(); const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation<VolumeRAM>(); if (dynamic_cast<const VolumeRAM_UInt8*>(inputVolume1)) { shiftScaleImageFilterITK<uint8_t>(); } else if (dynamic_cast<const VolumeRAM_Int8*>(inputVolume1)) { shiftScaleImageFilterITK<int8_t>(); } else if (dynamic_cast<const VolumeRAM_UInt16*>(inputVolume1)) { shiftScaleImageFilterITK<uint16_t>(); } else if (dynamic_cast<const VolumeRAM_Int16*>(inputVolume1)) { shiftScaleImageFilterITK<int16_t>(); } else if (dynamic_cast<const VolumeRAM_UInt32*>(inputVolume1)) { shiftScaleImageFilterITK<uint32_t>(); } else if (dynamic_cast<const VolumeRAM_Int32*>(inputVolume1)) { shiftScaleImageFilterITK<int32_t>(); } else if (dynamic_cast<const VolumeRAM_Float*>(inputVolume1)) { shiftScaleImageFilterITK<float>(); } else if (dynamic_cast<const VolumeRAM_Double*>(inputVolume1)) { shiftScaleImageFilterITK<double>(); } else { LERROR("Inputformat of Volume 1 is not supported!"); } } } // namespace
lathen/voreen
modules/itk_generated/processors/itk_ImageIntensity/shiftscaleimagefilter.cpp
C++
gpl-2.0
6,242
<?php /** * OpenSocialWebsite * * @package OpenSocialWebsite * @author Open Social Website Core Team <info@opensocialwebsite.com> * @copyright 2014 iNFORMATIKON TECHNOLOGIES * @license General Public Licence http://www.opensocialwebsite.com/licence * @link http://www.opensocialwebsite.com/licence */ define('__OSSN_SEARCH__', ossn_route()->com.'OssnSearch/'); require_once(__OSSN_SEARCH__.'classes/OssnSearch.php'); function ossn_search(){ ossn_register_page('search', 'ossn_search_page'); ossn_add_hook('search', "left", 'search_menu_handler'); ossn_extend_view('css/ossn.default', 'components/OssnSearch/css/search'); } function search_menu_handler($hook, $type, $return){ $return[] = ossn_view_menu('search'); return $return; } function ossn_search_page($pages){ $page = $pages[0]; if(empty($page)){ $page = 'search'; } ossn_trigger_callback('page', 'load:search'); switch($page){ case 'search': $query = input('q'); $type = input('type'); if(empty($type)){ $params['type'] = 'users'; } else { $params['type'] = $type; } $type = $params['type']; if(ossn_is_hook('search', "type:{$type}")){ $contents['contents'] = ossn_call_hook('search', "type:{$type}", array('q' => input('q'))); } $contents = array( 'content' => ossn_view('components/OssnSearch/pages/search', $contents), ); $content = ossn_set_page_layout('search', $contents); echo ossn_view_page($title, $content); break; default: ossn_error_page(); break; } } ossn_register_callback('ossn', 'init', 'ossn_search');
lianglee/opensource-socialnetwork
components/OssnSearch/ossn_com.php
PHP
gpl-2.0
1,627
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * * 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData Name: gm_commandscript %Complete: 100 Comment: All gm related commands Category: commandscripts EndScriptData */ #include "ScriptMgr.h" #include "ObjectMgr.h" #include "Chat.h" #include "AccountMgr.h" class gm_commandscript : public CommandScript { public: gm_commandscript() : CommandScript("gm_commandscript") { } ChatCommand* GetCommands() const { static ChatCommand gmCommandTable[] = { { "chat", SEC_MODERATOR, false, &HandleGMChatCommand, "", NULL }, { "fly", SEC_ADMINISTRATOR, false, &HandleGMFlyCommand, "", NULL }, { "ingame", SEC_PLAYER, true, &HandleGMListIngameCommand, "", NULL }, { "list", SEC_ADMINISTRATOR, true, &HandleGMListFullCommand, "", NULL }, { "visible", SEC_MODERATOR, false, &HandleGMVisibleCommand, "", NULL }, { "", SEC_MODERATOR, false, &HandleGMCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; static ChatCommand commandTable[] = { { "gm", SEC_MODERATOR, false, NULL, "", gmCommandTable }, { NULL, 0, false, NULL, "", NULL } }; return commandTable; } // Enables or disables hiding of the staff badge static bool HandleGMChatCommand(ChatHandler* handler, char const* args) { if (!*args) { WorldSession* session = handler->GetSession(); if (!AccountMgr::IsPlayerAccount(session->GetSecurity()) && session->GetPlayer()->isGMChat()) session->SendNotification(LANG_GM_CHAT_ON); else session->SendNotification(LANG_GM_CHAT_OFF); return true; } std::string param = (char*)args; if (param == "on") { handler->GetSession()->GetPlayer()->SetGMChat(true); handler->GetSession()->SendNotification(LANG_GM_CHAT_ON); return true; } if (param == "off") { handler->GetSession()->GetPlayer()->SetGMChat(false); handler->GetSession()->SendNotification(LANG_GM_CHAT_OFF); return true; } handler->SendSysMessage(LANG_USE_BOL); handler->SetSentErrorMessage(true); return false; } static bool HandleGMFlyCommand(ChatHandler* handler, char const* args) { if (!*args) return false; Player* target = handler->getSelectedPlayer(); if (!target) target = handler->GetSession()->GetPlayer(); WorldPacket data(12); if (strncmp(args, "on", 3) == 0) data.SetOpcode(SMSG_MOVE_SET_CAN_FLY); else if (strncmp(args, "off", 4) == 0) data.SetOpcode(SMSG_MOVE_UNSET_CAN_FLY); else { handler->SendSysMessage(LANG_USE_BOL); return false; } data.append(target->GetPackGUID()); data << uint32(0); // unknown target->SendMessageToSet(&data, true); handler->PSendSysMessage(LANG_COMMAND_FLYMODE_STATUS, handler->GetNameLink(target).c_str(), args); return true; } static bool HandleGMListIngameCommand(ChatHandler* handler, char const* /*args*/) { bool first = true; bool footer = false; TRINITY_READ_GUARD(HashMapHolder<Player>::LockType, *HashMapHolder<Player>::GetLock()); HashMapHolder<Player>::MapType const& m = sObjectAccessor->GetPlayers(); for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) { AccountTypes itrSec = itr->second->GetSession()->GetSecurity(); if ((itr->second->isGameMaster() || (!AccountMgr::IsPlayerAccount(itrSec) && itrSec <= AccountTypes(sWorld->getIntConfig(CONFIG_GM_LEVEL_IN_GM_LIST)))) && (!handler->GetSession() || itr->second->IsVisibleGloballyFor(handler->GetSession()->GetPlayer()))) { if (first) { first = false; footer = true; handler->SendSysMessage(LANG_GMS_ON_SRV); handler->SendSysMessage("========================"); } char const* name = itr->second->GetName(); uint8 security = itrSec; uint8 max = ((16 - strlen(name)) / 2); uint8 max2 = max; if ((max + max2 + strlen(name)) == 16) max2 = max - 1; if (handler->GetSession()) handler->PSendSysMessage("| %s GMLevel %u", name, security); else handler->PSendSysMessage("|%*s%s%*s| %u |", max, " ", name, max2, " ", security); } } if (footer) handler->SendSysMessage("========================"); if (first) handler->SendSysMessage(LANG_GMS_NOT_LOGGED); return true; } /// Display the list of GMs static bool HandleGMListFullCommand(ChatHandler* handler, char const* /*args*/) { ///- Get the accounts with GM Level >0 QueryResult result = LoginDatabase.PQuery("SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel >= %u", SEC_MODERATOR); if (result) { handler->SendSysMessage(LANG_GMLIST); handler->SendSysMessage("========================"); ///- Cycle through them. Display username and GM level do { Field* fields = result->Fetch(); char const* name = fields[0].GetCString(); uint8 security = fields[1].GetUInt8(); uint8 max = (16 - strlen(name)) / 2; uint8 max2 = max; if ((max + max2 + strlen(name)) == 16) max2 = max - 1; if (handler->GetSession()) handler->PSendSysMessage("| %s GMLevel %u", name, security); else handler->PSendSysMessage("|%*s%s%*s| %u |", max, " ", name, max2, " ", security); } while (result->NextRow()); handler->SendSysMessage("========================"); } else handler->PSendSysMessage(LANG_GMLIST_EMPTY); return true; } //Enable\Disable Invisible mode static bool HandleGMVisibleCommand(ChatHandler* handler, char const* args) { if (!*args) { handler->PSendSysMessage(LANG_YOU_ARE, handler->GetSession()->GetPlayer()->isGMVisible() ? handler->GetTrinityString(LANG_VISIBLE) : handler->GetTrinityString(LANG_INVISIBLE)); return true; } std::string param = (char*)args; if (param == "on") { handler->GetSession()->GetPlayer()->SetGMVisible(true); handler->GetSession()->SendNotification(LANG_INVISIBLE_VISIBLE); return true; } if (param == "off") { handler->GetSession()->SendNotification(LANG_INVISIBLE_INVISIBLE); handler->GetSession()->GetPlayer()->SetGMVisible(false); return true; } handler->SendSysMessage(LANG_USE_BOL); handler->SetSentErrorMessage(true); return false; } //Enable\Disable GM Mode static bool HandleGMCommand(ChatHandler* handler, char const* args) { if (!*args) { if (handler->GetSession()->GetPlayer()->isGameMaster()) handler->GetSession()->SendNotification(LANG_GM_ON); else handler->GetSession()->SendNotification(LANG_GM_OFF); return true; } std::string param = (char*)args; if (param == "on") { handler->GetSession()->GetPlayer()->SetGameMaster(true); handler->GetSession()->SendNotification(LANG_GM_ON); handler->GetSession()->GetPlayer()->UpdateTriggerVisibility(); #ifdef _DEBUG_VMAPS VMAP::IVMapManager* vMapManager = VMAP::VMapFactory::createOrGetVMapManager(); vMapManager->processCommand("stoplog"); #endif return true; } if (param == "off") { handler->GetSession()->GetPlayer()->SetGameMaster(false); handler->GetSession()->SendNotification(LANG_GM_OFF); handler->GetSession()->GetPlayer()->UpdateTriggerVisibility(); #ifdef _DEBUG_VMAPS VMAP::IVMapManager* vMapManager = VMAP::VMapFactory::createOrGetVMapManager(); vMapManager->processCommand("startlog"); #endif return true; } handler->SendSysMessage(LANG_USE_BOL); handler->SetSentErrorMessage(true); return false; } }; void AddSC_gm_commandscript() { new gm_commandscript(); }
rebirth-core/Rebirth---old
src/server/scripts/Commands/cs_gm.cpp
C++
gpl-2.0
9,929
/* Copyright (C) 2014 InfiniDB, Inc. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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. */ /***************************************************************************** * $Id: we_getfilesizes.cpp 4450 2013-01-21 14:13:24Z rdempsey $ * ****************************************************************************/ #include "we_getfilesizes.h" #include <iostream> #include <stdexcept> using namespace std; #include "calpontsystemcatalog.h" using namespace execplan; #include "threadpool.h" using namespace threadpool; #include "bytestream.h" using namespace messageqcpp; #include "we_fileop.h" #include "idbcompress.h" using namespace compress; #include "IDBFileSystem.h" #include "IDBPolicy.h" using namespace idbdatafile; namespace WriteEngine { struct FileInfo { uint32_t partition; /** @brief Partition for a file*/ uint16_t segment; /** @brief Segment for a file */ uint16_t dbRoot; /** @brief DbRoot for a file */ std::string segFileName; /** @brief seg file path */ double fileSize; /** @brief seg file size in giga bytes */ void serialize(messageqcpp::ByteStream& bs) { bs << partition; bs << segment; bs << dbRoot; bs << segFileName; bs << (*(uint64_t*)(&fileSize)); } }; typedef std::vector<FileInfo> Files; typedef std::map<uint32_t, Files> columnMap; typedef std::map<int, columnMap*> allColumnMap; allColumnMap wholeMap; boost::mutex columnMapLock; ActiveThreadCounter *activeThreadCounter; size_t readFillBuffer( idbdatafile::IDBDataFile* pFile, char* buffer, size_t bytesReq) { char* pBuf = buffer; ssize_t nBytes; size_t bytesToRead = bytesReq; size_t totalBytesRead = 0; while (1) { nBytes = pFile->read(pBuf, bytesToRead); if (nBytes > 0) totalBytesRead += nBytes; else break; if ((size_t)nBytes == bytesToRead) break; pBuf += nBytes; bytesToRead = bytesToRead - (size_t)nBytes; } return totalBytesRead; } off64_t getCompressedDataSize(string& fileName) { off64_t dataSize = 0; IDBDataFile* pFile = 0; size_t nBytes; // Some IDBPolicy functions can throw exceptions, caller will catch it IDBPolicy::configIDBPolicy(); bool bHdfsFile = IDBPolicy::useHdfs(); if (bHdfsFile) pFile = IDBDataFile::open(IDBDataFile::HDFS, fileName.c_str(), "r", 0); else pFile = IDBDataFile::open(IDBDataFile::BUFFERED, fileName.c_str(), "r", 0); if (!pFile) { std::ostringstream oss; oss << "Cannot open file " << fileName << " for read."; throw std::runtime_error(oss.str()); } IDBCompressInterface decompressor; //-------------------------------------------------------------------------- // Read headers and extract compression pointers //-------------------------------------------------------------------------- char hdr1[IDBCompressInterface::HDR_BUF_LEN]; nBytes = readFillBuffer( pFile,hdr1,IDBCompressInterface::HDR_BUF_LEN); if ( nBytes != IDBCompressInterface::HDR_BUF_LEN ) { std::ostringstream oss; oss << "Error reading first header from file " << fileName; throw std::runtime_error(oss.str()); } int64_t ptrSecSize = decompressor.getHdrSize(hdr1) - IDBCompressInterface::HDR_BUF_LEN; char* hdr2 = new char[ptrSecSize]; nBytes = readFillBuffer( pFile,hdr2,ptrSecSize); if ( (int64_t)nBytes != ptrSecSize ) { std::ostringstream oss; oss << "Error reading second header from file " << fileName; throw std::runtime_error(oss.str()); } CompChunkPtrList chunkPtrs; int rc = decompressor.getPtrList(hdr2, ptrSecSize, chunkPtrs); delete[] hdr2; if (rc != 0) { std::ostringstream oss; oss << "Error decompressing second header from file " << fileName; throw std::runtime_error(oss.str()); } unsigned k = chunkPtrs.size(); // last header's offset + length will be the data bytes dataSize = chunkPtrs[k-1].first + chunkPtrs[k-1].second; delete pFile; return dataSize; } struct ColumnThread { ColumnThread(uint32_t oid, int32_t compressionType, bool reportRealUse, int key) : fOid(oid), fCompressionType(compressionType), fReportRealUse(reportRealUse), fKey(key) {} void operator()() { Config config; config.initConfigCache(); std::vector<uint16_t> rootList; config.getRootIdList( rootList ); FileOp fileOp; Files aFiles; // This function relies on IDBPolicy being initialized by // IDBPolicy::init(). This is done when WriteEngineServer main() calls // IDBPolicy::configIDBPolicy(); IDBDataFile::Types fileType; bool bUsingHdfs = IDBPolicy::useHdfs(); if (bUsingHdfs) fileType = IDBDataFile::HDFS; else fileType = IDBDataFile::UNBUFFERED; IDBFileSystem& fs = IDBFileSystem::getFs( fileType ); for (uint32_t i=0; i < rootList.size(); i++) { std::vector<struct BRM::EMEntry> entries; (void)BRMWrapper::getInstance()->getExtents_dbroot(fOid, entries, rootList[i]); std::vector<struct BRM::EMEntry>::const_iterator iter = entries.begin(); while ( iter != entries.end() ) //organize extents into files { //Find the size of this file //string fileName; char fileName[200]; (void)fileOp.getFileName( fOid, fileName, rootList[i], entries[0].partitionNum, entries[0].segmentNum); string aFile(fileName); //convert between char* and string off64_t fileSize = 0; if (fReportRealUse && (fCompressionType > 0)) { try { fileSize = getCompressedDataSize(aFile); } catch (std::exception& ex) { cerr << ex.what(); } } else fileSize = fs.size( fileName ); if (fileSize > 0) // File exists, add to list { FileInfo aFileInfo; aFileInfo.partition = entries[0].partitionNum; aFileInfo.segment = entries[0].segmentNum; aFileInfo.dbRoot = rootList[i]; aFileInfo.segFileName = aFile; aFileInfo.fileSize = (double)fileSize / (1024 * 1024 * 1024); aFiles.push_back(aFileInfo); //cout.precision(15); //cout << "The file " << aFileInfo.segFileName << " has size " << fixed << aFileInfo.fileSize << "GB" << endl; } //erase the entries from this dbroot. std::vector<struct BRM::EMEntry> entriesTrimed; for (uint32_t m=0; m<entries.size(); m++) { if ((entries[0].partitionNum != entries[m].partitionNum) || (entries[0].segmentNum != entries[m].segmentNum)) entriesTrimed.push_back(entries[m]); } entriesTrimed.swap(entries); iter = entries.begin(); } } boost::mutex::scoped_lock lk(columnMapLock); //cout << "Current size of columnsMap is " << columnsMap.size() << endl; allColumnMap::iterator colMapiter = wholeMap.find(fKey); if (colMapiter != wholeMap.end()) { (colMapiter->second)->insert(make_pair(fOid,aFiles)); activeThreadCounter->decr(); //cout << "Added to columnsMap aFiles with size " << aFiles.size() << " for oid " << fOid << endl; } } uint32_t fOid; int32_t fCompressionType; bool fReportRealUse; int fKey; }; //------------------------------------------------------------------------------ // Process a table size based on input from the // bytestream object. //------------------------------------------------------------------------------ int WE_GetFileSizes::processTable( messageqcpp::ByteStream& bs, std::string& errMsg, int key) { uint8_t rc = 0; errMsg.clear(); try { std::string aTableName; std::string schemaName; bool reportRealUse = false; ByteStream::byte tmp8; bs >> schemaName; //cout << "schema: "<< schemaName << endl; bs >> aTableName; //cout << "tableName: " << aTableName << endl; bs >> tmp8; reportRealUse = (tmp8 != 0); //get column oids boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(0); CalpontSystemCatalog::TableName tableName; tableName.schema = schemaName; tableName.table = aTableName; CalpontSystemCatalog::RIDList columnList = systemCatalogPtr->columnRIDs(tableName); CalpontSystemCatalog::ColType colType; CalpontSystemCatalog::DictOIDList dictOidList = systemCatalogPtr->dictOIDs(tableName); int serverThreads = 20; int serverQueueSize = serverThreads * 100; threadpool::ThreadPool tp(serverThreads,serverQueueSize); int totalSize = columnList.size() + dictOidList.size(); activeThreadCounter = new ActiveThreadCounter(totalSize); columnMap *columnsMap = new columnMap(); { boost::mutex::scoped_lock lk(columnMapLock); wholeMap[key] = columnsMap; } for (uint32_t i=0; i < columnList.size(); i++) { colType = systemCatalogPtr->colType(columnList[i].objnum); tp.invoke(ColumnThread(columnList[i].objnum, colType.compressionType, reportRealUse, key)); if (colType.ddn.dictOID > 0) tp.invoke(ColumnThread(colType.ddn.dictOID, colType.compressionType, reportRealUse, key)); } /* for (uint32_t i=0; i < dictOidList.size(); i++) { tp.invoke(ColumnThread(dictOidList[i].dictOID)); } */ //check whether all threads finish int sleepTime = 100; // sleep 100 milliseconds between checks struct timespec rm_ts; rm_ts.tv_sec = sleepTime/1000; rm_ts.tv_nsec = sleepTime%1000 *1000000; uint32_t currentActiveThreads = 10; while (currentActiveThreads > 0) { #ifdef _MSC_VER Sleep(sleepTime); #else struct timespec abs_ts; do { abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_nsec = rm_ts.tv_nsec; } while(nanosleep(&abs_ts,&rm_ts) < 0); #endif currentActiveThreads = activeThreadCounter->cur(); } } catch(std::exception& ex) { //cout << "WE_GetFileSizes got exception-" << ex.what() << // std::endl; errMsg = ex.what(); rc = 1; } //Build the message to send to the caller bs.reset(); boost::mutex::scoped_lock lk(columnMapLock); allColumnMap::iterator colMapiter = wholeMap.find(key); if (colMapiter != wholeMap.end()) { columnMap::iterator iter = colMapiter->second->begin(); uint64_t size; Files::iterator it; while ( iter != colMapiter->second->end()) { bs << iter->first; //cout << "processTable::coloid = " << iter->first << endl; size = iter->second.size(); bs << size; for (it = iter->second.begin(); it != iter->second.end(); it++) it->serialize(bs); //cout << "length now is " << bs.length() << endl; iter++; } wholeMap.erase(colMapiter); } return rc; } }
infinidb/infinidb
writeengine/server/we_getfilesizes.cpp
C++
gpl-2.0
11,001
package kawigi.util; import java.util.Comparator; /** */ public final class StringsUtil { /** * Line separator in current Operating System. */ public static final String CRLF = System.getProperty("line.separator"); /** * Regular expression for line separator matching. */ public static final String sCRLFregex = "\r?\n"; private static StringsComparator compar = new StringsComparator(); private StringsUtil() {} public static int getFirstNonSpaceInd(CharSequence val, int startInd) { int res = startInd; while (val.length() > res) { char c = val.charAt(res); if (!Character.isSpaceChar(c) && !Character.isWhitespace(c)) break; ++res; } return res; } public static int getFirstNonSpaceInd(CharSequence val) { return getFirstNonSpaceInd(val, 0); } public static int getLastNonSpaceInd(CharSequence val, int startInd) { int res = startInd; while (0 <= res) { char c = val.charAt(res); if (!Character.isSpaceChar(c) && !Character.isWhitespace(c)) break; --res; } return res; } public static int getLastNonSpaceInd(CharSequence val) { return getLastNonSpaceInd(val, val.length() - 1); } public static void removeAllNextSpace(StringBuilder val, int startInd) { int endInd = getFirstNonSpaceInd(val, startInd); val.delete(startInd, endInd); } public static void removeAllPrevSpace(StringBuilder val, int endInd) { int startInd = getLastNonSpaceInd(val, endInd); val.delete(startInd + 1, endInd + 1); } public static void trim(StringBuilder val) { removeAllNextSpace(val, 0); removeAllPrevSpace(val, val.length() - 1); } public static void addArrayMarks(StringBuilder val) { val.insert(0, '{').append('}'); } public static void removeArrayMarks(StringBuilder val) { trim(val); if (0 < val.length()) { if ('{' == val.charAt(0)) { val.deleteCharAt(0); if ('}' == val.charAt(val.length() - 1)) val.setLength(val.length() - 1); } } } public static void addStringMarks(StringBuilder val) { val.insert(0, '"').append('"'); } public static void removeStringMarks(StringBuilder val) { trim(val); if (0 < val.length()) { if ('"' == val.charAt(0)) { val.deleteCharAt(0); if ('"' == val.charAt(val.length() - 1)) val.setLength(val.length() - 1); } } } public static Comparator<CharSequence> getComparator() { return compar; } /** * Compares two strings in CharSequences on equality. CharSequences can't * do this check themselves, so I was bound to write this method. * * @param val1 First value to compare * @param val2 Second value to compare * @return <code>true</code> if two values given are equal, * <code>false</code> otherwise */ public static boolean isEqual(CharSequence val1, CharSequence val2) { return 0 == compar.compare(val1, val2); } /** * Converts string value to lowercase. Converting made inplace. * * @param val Value to be converted and place to make result */ public static void toLower(StringBuilder val) { for (int i = 0; val.length() > i; ++i) { val.setCharAt(i, Character.toLowerCase(val.charAt(i))); } } /** * Replaces the value in StringBuilder with another CharSeqence. * * @param val StringBuilder for the result to be placed * @param seq Value that must be placed into <code>val</code> */ public static void reset(StringBuilder val, CharSequence seq) { val.setLength(0); val.append(seq); } /** * Replaces the part of string with another string without unnecessary * deletions and insertions. Value is changed inplace. * * @param val Value to be changed * @param start Start index of replacement object * @param end End index (one char behind end) of replacement object * @param seq Sequence to be inserted instead */ public static void replace(StringBuilder val, int start, int end, CharSequence seq) { int valPos = start, seqPos = 0; // First we char-by-char replace what we can for (; valPos != end && seqPos != seq.length(); ++valPos, ++seqPos) val.setCharAt(valPos, seq.charAt(seqPos)); // Then we do deletion and insertion of the rest if (valPos < end) val.delete(valPos, end); else if (seqPos < seq.length()) val.insert(end, seq, seqPos, seq.length()); } /** * Finds first occurence of character in CharSequence starting from index start. * * @param val Sequence to search for character * @param c Character to search for * @param start Starting index in sequence to search * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int indexOf(CharSequence val, char c, int start) { int res = -1; for (int i = start; val.length() > i; ++i) { if (val.charAt(i) == c) { res = i; break; } } return res; } /** * Finds first occurence of character in CharSequence starting from the beginning. * * @param val Sequence to search for character * @param c Character to search for * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int indexOf(CharSequence val, char c) { return indexOf(val, c, 0); } /** * Finds last occurence of character in CharSequence starting from index start. * * @param val Sequence to search for character * @param c Character to search for * @param start Starting index in sequence to search * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int lastIndexOf(CharSequence val, char c, int start) { int res = -1; int i = start; if (val.length() <= i) i = val.length() - 1; for (; 0 <= i; --i) { if (val.charAt(i) == c) { res = i; break; } } return res; } /** * Finds last occurence of character in CharSequence starting from the beginning. * * @param val Sequence to search for character * @param c Character to search for * @return Index in sequence where character is found or -1 * if it wasn't found */ public static int lastIndexOf(CharSequence val, char c) { return lastIndexOf(val, c, val.length() - 1); } /** * Checks if some string ('needle') stands at particular point ('startInd') in * another string ('hay'). * * @param hay String to look for 'needle' in * @param needle String to check for appearance in 'hay' * @param startInd Index in 'hay' at which 'needle' should stand * @return <code>true</code> if 'needle' stands in 'hay' at position * 'startInd'. <code>false</code> otherwise. */ public static boolean isStringAt(CharSequence hay, CharSequence needle, int startInd) { boolean res = false; if (hay.length() >= startInd + needle.length()) { res = true; for (int i = 0, j = startInd; needle.length() > i; ++i, ++j) { if (hay.charAt(j) != needle.charAt(i)) { res = false; break; } } } return res; } /** * Appends some excerpt from character sequence to StringBuilder trimming all * white space from excerpt beforehand. * * @param val Value to be modified * @param fromVal Sequence to make excerpt from * @param start Starting index of excerpt from sequence * @param end Ending index of excerpt from sequence (one character after end) */ public static void appendTrimmed(StringBuilder val, CharSequence fromVal, int start, int end) { val.append(fromVal, getFirstNonSpaceInd(fromVal, start), getLastNonSpaceInd(fromVal, end - 1) + 1); } }
vexorian/kawigi-edit
kawigi/util/StringsUtil.java
Java
gpl-2.0
8,044
package org.oztrack.validator; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.apache.commons.lang3.StringUtils; import org.oztrack.app.OzTrackApplication; import org.oztrack.data.access.UserDao; import org.oztrack.data.model.User; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class UserFormValidator implements Validator { private UserDao userDao; public UserFormValidator(UserDao userDao) { this.userDao = userDao; } @Override public boolean supports(@SuppressWarnings("rawtypes") Class clazz) { return User.class.isAssignableFrom(clazz); } @Override public void validate(Object obj, Errors errors) { User loginUser = (User) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.empty.field", "Please enter username"); User existingUserByUsername = userDao.getByUsername(loginUser.getUsername()); if ((existingUserByUsername != null) && (existingUserByUsername != loginUser)) { errors.rejectValue("username", "unavailable.user", "This username is unavailable. Please try another."); } User existingUserByEmail = userDao.getByEmail(loginUser.getEmail()); if ((existingUserByEmail != null) && (existingUserByEmail != loginUser)) { errors.rejectValue("email", "unavailable.email", "This email address is already associated with another account."); } if (OzTrackApplication.getApplicationContext().isAafEnabled() && StringUtils.isNotBlank(loginUser.getAafId())) { User existingUserByAafId = userDao.getByAafId(loginUser.getAafId()); if ((existingUserByAafId != null) && (existingUserByAafId != loginUser)) { errors.rejectValue("aafId", "aafId.user", "This AAF ID is already associated with another account."); } } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.empty.field", "Please enter first name"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.empty.field", "Please enter last name"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.empty.field", "Please enter email"); if (!errors.hasFieldErrors("email")) { try { InternetAddress emailAddr = new InternetAddress(loginUser.getEmail()); emailAddr.validate(); } catch (AddressException ex) { errors.rejectValue("email", "invalid.email", "Email error: " + ex.getMessage()); } } } }
uq-eresearch/oztrack
src/main/java/org/oztrack/validator/UserFormValidator.java
Java
gpl-2.0
2,724
<?php class EmployeesSubjectsController extends RController { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout='//layouts/column2'; /** * @return array action filters */ public function filters() { return array( 'rights', // perform access control for CRUD operations ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions'=>array('index','view','Assign','Deleterow'), 'users'=>array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions'=>array('create','update','subject','current','remove','employee'), 'users'=>array('@'), ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions'=>array('admin','delete'), 'users'=>array('admin'), ), array('deny', // deny all users 'users'=>array('*'), ), ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $this->render('view',array( 'model'=>$this->loadModel($id), )); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new EmployeesSubjects; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['EmployeesSubjects'])) { $model->attributes=$_POST['EmployeesSubjects']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('create',array( 'model'=>$model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['EmployeesSubjects'])) { $model->attributes=$_POST['EmployeesSubjects']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('update',array( 'model'=>$model, )); } public function actionDeleterow() { $postRecord = EmployeesSubjects::model()->findByPk($_REQUEST['id']); $postRecord->delete(); $this->redirect(array('create','cou'=>$_REQUEST['cou'],'sub'=>$_REQUEST['sub'],'dept'=>$_REQUEST['dept'])); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if(Yii::app()->request->isPostRequest) { // we only allow deletion via POST request $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); } else throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } /** * Lists all models. */ public function actionIndex() { $dataProvider=new CActiveDataProvider('EmployeesSubjects'); $this->render('index',array( 'dataProvider'=>$dataProvider, )); } public function actionAssign() { $model = new EmployeesSubjects; $model->employee_id = $_REQUEST['emp_id']; $model->subject_id = $_REQUEST['sub']; $model->save(); $this->redirect(array('create','cou'=>$_REQUEST['cou'],'sub'=>$_REQUEST['sub'],'dept'=>$_REQUEST['dept'])); } /** * Manages all models. */ public function actionAdmin() { $model=new EmployeesSubjects('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['EmployeesSubjects'])) $model->attributes=$_GET['EmployeesSubjects']; $this->render('admin',array( 'model'=>$model, )); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model=EmployeesSubjects::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='employees-subjects-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } public function actionSubject() { $data=Subjects::model()->findAll(array('join' => 'JOIN batches ON batch_id = batches.id','condition'=>'batches.course_id=:id', 'params'=>array(':id'=>(int) $_POST['id']))); $data=CHtml::listData($data,'id','name'); foreach($data as $value=>$name) { echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true); } } public function actionEmployee() { $data=Employees::model()->findAll(array('order'=>'first_name DESC','condition'=>'employee_department_id=:id', 'params'=>array(':id'=>(int) $_POST['did']))); $data=CHtml::listData($data,'id','first_name'); foreach($data as $value=>$name) { echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true); } } public function actionCurrent() { if(isset($_POST['EmployeesSubjects']['subject_id'])) { $this->renderPartial('assign',array('subject_id' =>$_POST['EmployeesSubjects']['subject_id'])); } else { echo 'remove'; } } public function actionRemove() { EmployeesSubjects::model()->findByAttributes(array('subject_id'=>$_REQUEST['subject_id'],'employee_id'=>$_REQUEST['employee_id']))->delete(); $this->redirect(Yii::app()->createUrl('EmployeesSubjects/create')); } }
napoleon789/qlkh
osv/protected/modules/employees/controllers/EmployeesSubjectsController.php
PHP
gpl-2.0
6,334
<article <?php hybrid_attr( 'post' ); ?>> <?php if ( is_singular( get_post_type() ) ) : // If viewing a single post. ?> <header class="entry-header"> <h1 <?php hybrid_attr( 'entry-title' ); ?>><?php single_post_title(); ?></h1> <?php hybrid_post_terms( array( 'taxonomy' => 'category' ) ); ?> <div class="entry-byline"> </div><!-- .entry-byline --> </header><!-- .entry-header --> <div <?php hybrid_attr( 'entry-content' ); ?>> <?php the_content(); ?> <?php wp_link_pages(); ?> </div><!-- .entry-content --> <footer class="entry-footer"> <time <?php hybrid_attr( 'entry-published' ); ?>><?php echo get_the_date(); ?></time> <?php esc_html_e('by', 'rakiya' ); ?> <span <?php hybrid_attr( 'entry-author' ); ?>><?php the_author_posts_link(); ?></span> <?php edit_post_link(); ?> <?php hybrid_post_terms( array( 'taxonomy' => 'post_tag', 'text' => esc_html__( 'Tagged: %s', 'rakiya' ), 'before' => '<br />' ) ); ?> </footer><!-- .entry-footer --> <?php else : // If not viewing a single post. ?> <?php get_the_image(); ?> <header class="entry-header"> <?php the_title( '<h2 ' . hybrid_get_attr( 'entry-title' ) . '><a href="' . get_permalink() . '" rel="bookmark" itemprop="url">', '</a></h2>' ); ?> <?php hybrid_post_terms( array( 'taxonomy' => 'category' ) ); ?> </header><!-- .entry-header --> <div <?php hybrid_attr( 'entry-summary' ); ?>> <?php the_excerpt(); ?> </div><!-- .entry-summary --> <footer class="entry-footer"> <time <?php hybrid_attr( 'entry-published' ); ?>><?php echo get_the_date(); ?></time> <?php esc_html_e( 'by', 'rakiya' ); ?> <span <?php hybrid_attr( 'entry-author' ); ?>><?php the_author_posts_link(); ?></span> </footer> <?php endif; // End single post check. ?> </article><!-- .entry -->
mlloewen/chinhama
wp-content/themes/rakiya/content/content.php
PHP
gpl-2.0
1,824
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2017 Paco Avila & Josep Llort * <p> * No bytes were intentionally harmed during the development of this application. * <p> * 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. * <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 General Public License for more details. * <p> * 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. */ package com.openkm.api; import com.openkm.bean.AppVersion; import com.openkm.bean.ExtendedAttributes; import com.openkm.bean.Folder; import com.openkm.core.*; import com.openkm.module.ModuleManager; import com.openkm.module.RepositoryModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OKMRepository implements RepositoryModule { private static Logger log = LoggerFactory.getLogger(OKMRepository.class); private static OKMRepository instance = new OKMRepository(); private OKMRepository() { } public static OKMRepository getInstance() { return instance; } @Override public Folder getRootFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getRootFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder rootFolder = rm.getRootFolder(token); log.debug("getRootFolder: {}", rootFolder); return rootFolder; } @Override public Folder getTrashFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getTrashFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder trashFolder = rm.getTrashFolder(token); log.debug("getTrashFolder: {}", trashFolder); return trashFolder; } @Override public Folder getTrashFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getTrashFolderBase({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder trashFolder = rm.getTrashFolderBase(token); log.debug("getTrashFolderBase: {}", trashFolder); return trashFolder; } @Override public Folder getTemplatesFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getTemplatesFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder templatesFolder = rm.getTemplatesFolder(token); log.debug("getTemplatesFolder: {}", templatesFolder); return templatesFolder; } @Override public Folder getPersonalFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getPersonalFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder personalFolder = rm.getPersonalFolder(token); log.debug("getPersonalFolder: {}", personalFolder); return personalFolder; } @Override public Folder getPersonalFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getPersonalFolderBase({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder personalFolder = rm.getPersonalFolderBase(token); log.debug("getPersonalFolderBase: {}", personalFolder); return personalFolder; } @Override public Folder getMailFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getMailFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder mailFolder = rm.getMailFolder(token); log.debug("getMailFolder: {}", mailFolder); return mailFolder; } @Override public Folder getMailFolderBase(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getMailFolderBase({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder mailFolder = rm.getMailFolderBase(token); log.debug("getMailFolderBase: {}", mailFolder); return mailFolder; } @Override public Folder getThesaurusFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getThesaurusFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder thesaurusFolder = rm.getThesaurusFolder(token); log.debug("getThesaurusFolder: {}", thesaurusFolder); return thesaurusFolder; } @Override public Folder getCategoriesFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getCategoriesFolder({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); Folder categoriesFolder = rm.getCategoriesFolder(token); log.debug("getCategoriesFolder: {}", categoriesFolder); return categoriesFolder; } @Override public void purgeTrash(String token) throws PathNotFoundException, AccessDeniedException, LockException, RepositoryException, DatabaseException { log.debug("purgeTrash({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); rm.purgeTrash(token); log.debug("purgeTrash: void"); } @Override public String getUpdateMessage(String token) throws RepositoryException { log.debug("getUpdateMessage({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); String updateMessage = rm.getUpdateMessage(token); log.debug("getUpdateMessage: {}", updateMessage); return updateMessage; } @Override public String getRepositoryUuid(String token) throws RepositoryException { log.debug("getRepositoryUuid({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); String uuid = rm.getRepositoryUuid(token); log.debug("getRepositoryUuid: {}", uuid); return uuid; } @Override public boolean hasNode(String token, String path) throws AccessDeniedException, RepositoryException, DatabaseException { log.debug("hasNode({})", token, path); RepositoryModule rm = ModuleManager.getRepositoryModule(); boolean ret = rm.hasNode(token, path); log.debug("hasNode: {}", ret); return ret; } @Override public String getNodePath(String token, String uuid) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getNodePath({}, {})", token, uuid); RepositoryModule rm = ModuleManager.getRepositoryModule(); String ret = rm.getNodePath(token, uuid); log.debug("getNodePath: {}", ret); return ret; } @Override public String getNodeUuid(String token, String path) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { log.debug("getNodeUuid({}, {})", token, path); RepositoryModule rm = ModuleManager.getRepositoryModule(); String ret = rm.getNodeUuid(token, path); log.debug("getNodeUuid: {}", ret); return ret; } public AppVersion getAppVersion(String token) throws AccessDeniedException, RepositoryException, DatabaseException { log.debug("getAppVersion({})", token); RepositoryModule rm = ModuleManager.getRepositoryModule(); AppVersion ret = rm.getAppVersion(token); log.debug("getAppVersion: {}", ret); return ret; } @Override public void copyAttributes(String token, String srcId, String dstId, ExtendedAttributes extAttr) throws AccessDeniedException, PathNotFoundException, DatabaseException { log.debug("copyAttributes({}, {}, {}, {})", new Object[]{token, srcId, dstId, extAttr}); RepositoryModule rm = ModuleManager.getRepositoryModule(); rm.copyAttributes(token, srcId, dstId, extAttr); log.debug("copyAttributes: void"); } }
Beau-M/document-management-system
src/main/java/com/openkm/api/OKMRepository.java
Java
gpl-2.0
8,219
akeeba.jQuery(document).ready(function($){ akeeba.jQuery('#addTickets').click(function(){ if(document.adminForm.boxchecked.value == 0) { alert(akeeba.jQuery('#chooseone').val()); return false; } if(document.adminForm.boxchecked.value > 1) { alert(akeeba.jQuery('#chooseonlyone').val()); return false; } Joomla.submitbutton('addtickets'); }); });
SirPiter/folk
www/media/com_ats/js/adm_buckets_choose.js
JavaScript
gpl-2.0
382
# -*- coding: utf-8 -*- """ *************************************************************************** PostGISExecuteSQL.py --------------------- Date : October 2012 Copyright : (C) 2012 by Victor Olaya and Carterix Geomatics Email : volayaf at gmail dot 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. * * * *************************************************************************** """ from sextante.core.GeoAlgorithm import GeoAlgorithm __author__ = 'Victor Olaya, Carterix Geomatics' __date__ = 'October 2012' __copyright__ = '(C) 2012, Victor Olaya, Carterix Geomatics' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.core import * from PyQt4.QtCore import * from PyQt4.QtGui import * from sextante.parameters.ParameterString import ParameterString from sextante.admintools import postgis_utils from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException class PostGISExecuteSQL(GeoAlgorithm): DATABASE = "DATABASE" SQL = "SQL" def getIcon(self): return QIcon(os.path.dirname(__file__) + "/../images/postgis.png") def processAlgorithm(self, progress): connection = self.getParameterValue(self.DATABASE) settings = QSettings() mySettings = "/PostgreSQL/connections/"+ connection try: database = settings.value(mySettings+"/database").toString() username = settings.value(mySettings+"/username").toString() host = settings.value(mySettings+"/host").toString() port = int(settings.value(mySettings+"/port").toString()) password = settings.value(mySettings+"/password").toString() except Exception, e: raise GeoAlgorithmExecutionException("Wrong database connection name: " + connection) try: self.db = postgis_utils.GeoDB(host=host, port=port, dbname=database, user=username, passwd=password) except postgis_utils.DbError, e: raise GeoAlgorithmExecutionException("Couldn't connect to database:\n"+e.message) sql = self.getParameterValue(self.SQL).replace("\n", " ") try: self.db._exec_sql_and_commit(str(sql)) except postgis_utils.DbError, e: raise GeoAlgorithmExecutionException("Error executing SQL:\n"+e.message) def defineCharacteristics(self): self.name = "PostGIS execute SQL" self.group = "PostGIS management tools" self.addParameter(ParameterString(self.DATABASE, "Database")) self.addParameter(ParameterString(self.SQL, "SQL query", "", True))
bstroebl/QGIS
python/plugins/sextante/admintools/PostGISExecuteSQL.py
Python
gpl-2.0
3,170
<?php /* * Theme Note * ------------------- * - Changed the location of cross-sells section (woocommerce_cart_collaterals action) and adjusted the layout a bit * - Added if-else for "wc_print_notices()", "wp_nonce_field( 'woocommerce-cart' );" * - Note: This file is based on WooC 2.1.9 * */ /** * Cart Page * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce; if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) { wc_print_notices(); } else { $woocommerce->show_messages(); } do_action( 'woocommerce_before_cart' ); ?> <form action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post"> <?php do_action( 'woocommerce_before_cart_table' ); ?> <table class="shop_table cart" cellspacing="0"> <thead> <tr> <th class="product-remove">&nbsp;</th> <th class="product-thumbnail">&nbsp;</th> <th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th> <th class="product-price"><?php _e( 'Price', 'woocommerce' ); ?></th> <th class="product-quantity"><?php _e( 'Quantity', 'woocommerce' ); ?></th> <th class="product-subtotal"><?php _e( 'Total', 'woocommerce' ); ?></th> </tr> </thead> <tbody> <?php do_action( 'woocommerce_before_cart_contents' ); ?> <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) { ?> <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>"> <td class="product-remove"> <?php echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf( '<a href="%s" class="remove" title="%s">&times;</a>', esc_url( WC()->cart->get_remove_url( $cart_item_key ) ), __( 'Remove this item', 'woocommerce' ) ), $cart_item_key ); ?> </td> <td class="product-thumbnail"> <?php $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key ); if ( ! $_product->is_visible() ) echo $thumbnail; else printf( '<a href="%s">%s</a>', $_product->get_permalink(), $thumbnail ); ?> </td> <td class="product-name"> <?php if ( ! $_product->is_visible() ) echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key ); else echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', $_product->get_permalink(), $_product->get_title() ), $cart_item, $cart_item_key ); // Meta data echo WC()->cart->get_item_data( $cart_item ); // Backorder notification if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) echo '<p class="backorder_notification">' . __( 'Available on backorder', 'woocommerce' ) . '</p>'; ?> </td> <td class="product-price"> <?php echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); ?> </td> <td class="product-quantity"> <?php if ( $_product->is_sold_individually() ) { $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key ); } else { $product_quantity = woocommerce_quantity_input( array( 'input_name' => "cart[{$cart_item_key}][qty]", 'input_value' => $cart_item['quantity'], 'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(), 'min_value' => '0' ), $_product, false ); } echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key ); ?> </td> <td class="product-subtotal"> <?php echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); ?> </td> </tr> <?php } } do_action( 'woocommerce_cart_contents' ); ?> <tr> <td colspan="6" class="actions"> <?php if ( WC()->cart->coupons_enabled() ) { ?> <div class="coupon"> <label for="coupon_code"><?php _e( 'Coupon', 'woocommerce' ); ?>:</label> <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" /> <input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" /> <?php do_action('woocommerce_cart_coupon'); ?> </div> <?php } ?> <input type="submit" class="button" name="update_cart" value="<?php _e( 'Update Cart', 'woocommerce' ); ?>" /> <input type="submit" class="checkout-button button alt wc-forward" name="proceed" value="<?php _e( 'Proceed to Checkout', 'woocommerce' ); ?>" /> <?php do_action( 'woocommerce_proceed_to_checkout' ); ?> <?php if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) { wp_nonce_field( 'woocommerce-cart' ); } else { $woocommerce->nonce_field('cart'); } ?> </td> </tr> <?php do_action( 'woocommerce_after_cart_contents' ); ?> </tbody> </table> <?php do_action( 'woocommerce_after_cart_table' ); ?> </form> <div class="row"> <div class="uxb-col large-6 columns"> <?php woocommerce_cart_totals(); ?> </div> <div class="uxb-col large-6 columns"> <?php woocommerce_shipping_calculator(); ?> </div> </div> <?php do_action( 'woocommerce_cart_collaterals' ); ?> <?php do_action( 'woocommerce_after_cart' ); ?>
gitprj/samantha-ohlsen-photography
wp-content/themes/fineliner/woocommerce/cart/cart.php
PHP
gpl-2.0
6,140
package com.numhero.client.model.datacargo.auth; import com.numhero.shared.datacargo.CommandResponse; import java.util.Date; public class AuthResponse implements CommandResponse { private String sessionID; private Date expirationDate; public String getSessionID() { return sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public Date getExpirationDate() { return expirationDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } }
midaboghetich/netnumero
src/com/numhero/client/model/datacargo/auth/AuthResponse.java
Java
gpl-2.0
594
<?php class bx_streams_db2xml extends bx_streams_buffer { function contentOnRead($path) { $db2xml = new XML_db2xml(NULL, NULL, 'Extended'); $xml = ''; $options = array( 'formatOptions' => array ( 'xml_seperator' => '', 'element_id' => 'id' ) ); $db2xml->Format->SetOptions($options); if(preg_match('/\/(.*)[\/]/', $path, $matches)) { $table = $matches[1]; } $where = $this->getParameter('where'); if(!empty($table)) { $query = "select * from $table"; if(!empty($where)) { $query .= " where $where"; } $res = $GLOBALS['POOL']->db->query($query); if (PEAR::isError($res) || $res->numRows() == 0) { $xml = "<nothingFound/>"; } else { $xml = $db2xml->getXML($res); } } return $xml; } function contentOnWrite($content) { } }
chregu/fluxcms
inc/bx/streams/db2xml.php
PHP
gpl-2.0
1,061
package to.rtc.rtc2jira.exporter.jira.entities; import java.util.Date; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.codehaus.jackson.map.annotate.JsonView; public class Version extends NamedEntity { String description; boolean archived = false; boolean released = true; Date releaseDate; String project; Integer projectId; @JsonView(IssueView.Filtered.class) @Override public String getKey() { return super.getKey(); } @Override public String getPath() { return "/version"; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isArchived() { return archived; } public void setArchived(boolean archived) { this.archived = archived; } public boolean isReleased() { return released; } public void setReleased(boolean released) { this.released = released; } @XmlJavaTypeAdapter(JiraDateStringAdapter.class) public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } @JsonView(IssueView.Create.class) public String getProject() { return project; } public void setProject(String project) { this.project = project; } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } }
ohumbel/rtc2jira
src/main/java/to/rtc/rtc2jira/exporter/jira/entities/Version.java
Java
gpl-2.0
1,511
/* * @(#)BufferSize.java 1.5 00/05/04 SMI * * Author: Tom Corson * * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * Sun grants you ("Licensee") a non-exclusive, royalty free, license * to use, modify and redistribute this software in source and binary * code form, provided that i) this copyright notice and license appear * on all copies of the software; and ii) Licensee does not utilize the * software in a manner which is disparaging to Sun. * * This software is provided "AS IS," without a warranty of any kind. * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE * SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS * BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, * HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING * OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * This software is not designed or intended for use in on-line control * of aircraft, air traffic, aircraft navigation or aircraft * communications; or in the design, construction, operation or * maintenance of any nuclear facility. Licensee represents and * warrants that it will not use or redistribute the Software for such * purposes. */ import java.awt.Panel; import java.awt.Label; import java.awt.TextField; import java.awt.BorderLayout; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.comm.ParallelPort; /** * Class declaration * * * @author * @version 1.5, 05/04/00 */ public class BufferSize extends Panel implements MouseListener, ActionListener { private int value, defaultValue; private Label label; private TextField data; private ParallelPort port = null; private boolean inputBuffer; /** * Constructor declaration * * * @param size * @param port * @param inputBuffer * * @see */ public BufferSize(int size, ParallelPort port, boolean inputBuffer) { super(); this.setPort(port); this.inputBuffer = inputBuffer; this.setLayout(new BorderLayout()); this.label = new Label("Buffer Size"); this.label.addMouseListener(this); this.add("West", this.label); this.data = new TextField(new Integer(defaultValue).toString(), size); this.data.addActionListener(this); this.add("East", this.data); this.showValue(); this.defaultValue = this.value; } /** * Method declaration * * * @param port * * @see */ public void setPort(ParallelPort port) { this.port = port; } /** * Method declaration * * * @return * * @see */ public int getValue() { if (this.port != null) { /* * Get the buffer size. */ if (inputBuffer) { this.value = port.getInputBufferSize(); } else { this.value = port.getOutputBufferSize(); } return this.value; } else { return (0); } } /** * Method declaration * * * @see */ public void showValue() { this.data.setText(new Integer(this.getValue()).toString()); } /** * Method declaration * * * @param val * * @see */ public void setValue(int val) { if (this.port != null) { /* * Set the new buffer size. */ if (inputBuffer) { port.setInputBufferSize(val); } else { port.setOutputBufferSize(val); } } this.showValue(); } /** * Method declaration * * * @param val * * @see */ public void setDefaultValue(int val) { this.defaultValue = val; } /** * Method declaration * * * @param e * * @see */ public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); try { Integer newValue = new Integer(s); this.setValue(newValue.intValue()); } catch (NumberFormatException ex) { System.out.println("Bad value = " + e.getActionCommand()); this.showValue(); } } /** * Method declaration * * * @param e * * @see */ public void mouseClicked(MouseEvent e) {} /** * Method declaration * * * @param e * * @see */ public void mouseEntered(MouseEvent e) {} /** * Method declaration * * * @param e * * @see */ public void mouseExited(MouseEvent e) {} /** * Method declaration * * * @param e * * @see */ public void mousePressed(MouseEvent e) { this.setValue(this.defaultValue); } /** * Method declaration * * * @param e * * @see */ public void mouseReleased(MouseEvent e) {} }
tstuckey/WirelessCautionLights
comm_api/commapi_linux/examples/ParallelBlackBox/BufferSize.java
Java
gpl-2.0
5,316
# -*- coding: utf-8 -*- from django.db import models class Profiles(models.Model): userid = models.AutoField(primary_key=True) login_name = models.CharField(max_length=255, unique=True) cryptpassword = models.CharField(max_length=128, blank=True) realname = models.CharField(max_length=255) disabledtext = models.TextField() disable_mail = models.IntegerField(default=0) mybugslink = models.IntegerField() extern_id = models.IntegerField(blank=True) class Meta: db_table = "profiles" def get_groups(self): q = UserGroupMap.objects.filter(user__userid=self.userid) q = q.select_related() groups = [assoc.group for assoc in q.all()] return groups class Groups(models.Model): name = models.CharField(unique=True, max_length=255) description = models.TextField() isbuggroup = models.IntegerField() userregexp = models.TextField() isactive = models.IntegerField() class Meta: db_table = "groups" class UserGroupMap(models.Model): user = models.ForeignKey(Profiles, on_delete=models.CASCADE) # user_id # (actually has two primary keys) group = models.ForeignKey(Groups, on_delete=models.CASCADE) # group_id isbless = models.IntegerField(default=0) grant_type = models.IntegerField(default=0) class Meta: db_table = "user_group_map" unique_together = ("user", "group") # # Extra information for users # class UserProfile(models.Model): user = models.OneToOneField( "auth.User", unique=True, related_name="profile", on_delete=models.CASCADE ) phone_number = models.CharField(blank=True, default="", max_length=128) url = models.URLField(blank=True, default="") im = models.CharField(blank=True, default="", max_length=128) im_type_id = models.IntegerField(blank=True, default=1, null=True) address = models.TextField(blank=True, default="") notes = models.TextField(blank=True, default="") class Meta: db_table = "tcms_user_profiles" def get_im(self): from .forms import IM_CHOICES if not self.im: return None for c in IM_CHOICES: if self.im_type_id == c[0]: return "[{}] {}".format(c[1], self.im) @classmethod def get_user_profile(cls, user): return cls.objects.get(user=user)
Nitrate/Nitrate
src/tcms/profiles/models.py
Python
gpl-2.0
2,379
/* * MekWars - Copyright (C) 2004 * * Derived from MegaMekNET (http://www.sourceforge.net/projects/megameknet) * * 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. */ package server.campaign.commands; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.Vector; import server.campaign.CampaignMain; import server.campaign.SPlayer; import server.campaign.votes.Vote; public class RemoveVoteCommand implements Command { int accessLevel = 0; String syntax = ""; public int getExecutionLevel(){return accessLevel;} public void setExecutionLevel(int i) {accessLevel = i;} public String getSyntax() { return syntax;} public void process(StringTokenizer command,String Username) { if (accessLevel != 0) { int userLevel = CampaignMain.cm.getServer().getUserLevel(Username); if(userLevel < getExecutionLevel()) { CampaignMain.cm.toUser("AM:Insufficient access level for command. Level: " + userLevel + ". Required: " + accessLevel + ".",Username,true); return; } } SPlayer castingPlayer = CampaignMain.cm.getPlayer(Username); String recipientName = "";//blank string try { recipientName = new String(command.nextToken()).toString(); }//end try catch (NumberFormatException ex) { CampaignMain.cm.toUser("AM:RemoveVote command failed. Check your input. It should be something like this: /c removevote#name",Username,true); return; }//end catch //break out if a player is trying to vote for himself if (Username.equals(recipientName)) { CampaignMain.cm.toUser("AM:You may not vote for youself.",Username,true); return; } //break out if voting isnt enabled on the server boolean canVote = new Boolean(CampaignMain.cm.getConfig("VotingEnabled")).booleanValue(); if (!canVote) { CampaignMain.cm.toUser("AM:Voting is disabled on this server.",Username,true); return; } //get all votes cast by the player issuing the command Vector<Vote> castersVotes = CampaignMain.cm.getVoteManager().getAllVotesBy(castingPlayer); //break out if the player has no outstanding votes to remove if (castersVotes.isEmpty()) { CampaignMain.cm.toUser("AM:You have not cast any votes. Removal is impossible.",Username,true); return; } //get the SPlayer who is receiving for the next couple of checks SPlayer recipientPlayer = CampaignMain.cm.getPlayer(recipientName); //break out if the recieving player isnt known if (recipientPlayer == null) { CampaignMain.cm.toUser("AM:You can't remove a vote for a player who doesn't exist.",Username,true); return; } //break out if player has no votes cast for recipient Enumeration<Vote> e = castersVotes.elements(); boolean hasVoteForRecipient = false; Vote v = null; while (e.hasMoreElements() && !hasVoteForRecipient) { v = e.nextElement(); if (v.getRecipient().equals(recipientName)) { hasVoteForRecipient = true; } }//end while(more elements) /* * The last vote drawn from the enumeration has the proper recipient, if * hasVoteForRecipient is true, because the loop ends before a replacement * element is drawn. If true, attempt to remove the vote. If false, break the * bad news to the player. */ if (!hasVoteForRecipient) { CampaignMain.cm.toUser("AM:You have not voted for this player.",Username,true); return; } //else if boolean voteRemoved = CampaignMain.cm.getVoteManager().removeVote(v); if (!voteRemoved) { CampaignMain.cm.toUser("AM:There was an error removing the vote. Please contact your " + "server admin or file a bug report.", Username, true); return; } //else CampaignMain.cm.toUser("AM:Your vote for " + recipientName + " has been removed.",Username,true); } }
mekwars-legends/mekwars-upstream
src/server/campaign/commands/RemoveVoteCommand.java
Java
gpl-2.0
4,319
/*************************************************************************** qgsspatialitesourceselect.cpp Dialog to select SpatiaLite layer(s) and add it to the map canvas ------------------- begin : Dec 2008 copyright : (C) 2008 by Sandro Furieri email : a.furieri@lqt.it ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "qgsspatialitesourceselect.h" #include "qgsspatialiteconnection.h" #include "qgslogger.h" #include "qgsapplication.h" #include "qgscontexthelp.h" #include "qgsquerybuilder.h" #include "qgsdatasourceuri.h" #include "qgsvectorlayer.h" #include <QInputDialog> #include <QMessageBox> #include <QSettings> #include <QTextStream> #include <QTableWidgetItem> #include <QHeaderView> #include <QStringList> #include <QPushButton> #ifdef _MSC_VER #define strcasecmp(a,b) stricmp(a,b) #endif QgsSpatiaLiteSourceSelect::QgsSpatiaLiteSourceSelect( QWidget * parent, Qt::WindowFlags fl, bool embedded ): QDialog( parent, fl ) { setupUi( this ); QSettings settings; restoreGeometry( settings.value( "/Windows/SpatiaLiteSourceSelect/geometry" ).toByteArray() ); mHoldDialogOpen->setChecked( settings.value( "/Windows/SpatiaLiteSourceSelect/HoldDialogOpen", false ).toBool() ); setWindowTitle( tr( "Add SpatiaLite Table(s)" ) ); connectionsGroupBox->setTitle( tr( "Databases" ) ); btnEdit->hide(); // hide the edit button btnSave->hide(); btnLoad->hide(); mStatsButton = new QPushButton( tr( "&Update Statistics" ) ); connect( mStatsButton, SIGNAL( clicked() ), this, SLOT( updateStatistics() ) ); mStatsButton->setEnabled( false ); mAddButton = new QPushButton( tr( "&Add" ) ); connect( mAddButton, SIGNAL( clicked() ), this, SLOT( addClicked() ) ); mAddButton->setEnabled( false ); mBuildQueryButton = new QPushButton( tr( "&Set Filter" ) ); connect( mBuildQueryButton, SIGNAL( clicked() ), this, SLOT( buildQuery() ) ); mBuildQueryButton->setEnabled( false ); if ( embedded ) { buttonBox->button( QDialogButtonBox::Close )->hide(); } else { buttonBox->addButton( mAddButton, QDialogButtonBox::ActionRole ); buttonBox->addButton( mBuildQueryButton, QDialogButtonBox::ActionRole ); buttonBox->addButton( mStatsButton, QDialogButtonBox::ActionRole ); } populateConnectionList(); mSearchModeComboBox->addItem( tr( "Wildcard" ) ); mSearchModeComboBox->addItem( tr( "RegExp" ) ); mSearchColumnComboBox->addItem( tr( "All" ) ); mSearchColumnComboBox->addItem( tr( "Table" ) ); mSearchColumnComboBox->addItem( tr( "Type" ) ); mSearchColumnComboBox->addItem( tr( "Geometry column" ) ); mSearchColumnComboBox->addItem( tr( "Sql" ) ); mProxyModel.setParent( this ); mProxyModel.setFilterKeyColumn( -1 ); mProxyModel.setFilterCaseSensitivity( Qt::CaseInsensitive ); mProxyModel.setDynamicSortFilter( true ); mProxyModel.setSourceModel( &mTableModel ); mTablesTreeView->setModel( &mProxyModel ); mTablesTreeView->setSortingEnabled( true ); connect( mTablesTreeView->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ), this, SLOT( treeWidgetSelectionChanged( const QItemSelection&, const QItemSelection& ) ) ); //for Qt < 4.3.2, passing -1 to include all model columns //in search does not seem to work mSearchColumnComboBox->setCurrentIndex( 1 ); //hide the search options by default //they will be shown when the user ticks //the search options group box mSearchLabel->setVisible( false ); mSearchColumnComboBox->setVisible( false ); mSearchColumnsLabel->setVisible( false ); mSearchModeComboBox->setVisible( false ); mSearchModeLabel->setVisible( false ); mSearchTableEdit->setVisible( false ); cbxAllowGeometrylessTables->setDisabled( true ); } QgsSpatiaLiteSourceSelect::~QgsSpatiaLiteSourceSelect() { QSettings settings; settings.setValue( "/Windows/SpatiaLiteSourceSelect/geometry", saveGeometry() ); settings.setValue( "/Windows/SpatiaLiteSourceSelect/HoldDialogOpen", mHoldDialogOpen->isChecked() ); } // Slot for performing action when the Add button is clicked void QgsSpatiaLiteSourceSelect::addClicked() { addTables(); } /** End Autoconnected SLOTS **/ // Remember which database is selected void QgsSpatiaLiteSourceSelect::on_cmbConnections_activated( int ) { dbChanged(); } void QgsSpatiaLiteSourceSelect::buildQuery() { setSql( mTablesTreeView->currentIndex() ); } void QgsSpatiaLiteSourceSelect::updateStatistics() { QString subKey = cmbConnections->currentText(); int idx = subKey.indexOf( '@' ); if ( idx > 0 ) subKey.truncate( idx ); QString msg = tr( "Are you sure you want to update the internal statistics for DB: %1?\n\n" "This could take a long time (depending on the DB size),\n" "but implies better performance thereafter." ).arg( subKey ); QMessageBox::StandardButton result = QMessageBox::information( this, tr( "Confirm Update Statistics" ), msg, QMessageBox::Ok | QMessageBox::Cancel ); if ( result != QMessageBox::Ok ) return; // trying to connect to SpatiaLite DB QgsSpatiaLiteConnection conn( subKey ); if ( conn.updateStatistics() ) { QMessageBox::information( this, tr( "Update Statistics" ), tr( "Internal statistics successfully updated for: %1" ).arg( subKey ) ); } else { QMessageBox::critical( this, tr( "Update Statistics" ), tr( "Error while updating internal statistics for: %1" ).arg( subKey ) ); } } void QgsSpatiaLiteSourceSelect::on_cbxAllowGeometrylessTables_stateChanged( int ) { on_btnConnect_clicked(); } void QgsSpatiaLiteSourceSelect::on_mTablesTreeView_clicked( const QModelIndex &index ) { mBuildQueryButton->setEnabled( index.parent().isValid() ); } void QgsSpatiaLiteSourceSelect::on_mTablesTreeView_doubleClicked( const QModelIndex &index ) { setSql( index ); } void QgsSpatiaLiteSourceSelect::on_mSearchGroupBox_toggled( bool checked ) { if ( mSearchTableEdit->text().isEmpty() ) return; on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : "" ); } void QgsSpatiaLiteSourceSelect::on_mSearchTableEdit_textChanged( const QString & text ) { if ( mSearchModeComboBox->currentText() == tr( "Wildcard" ) ) { mProxyModel._setFilterWildcard( text ); } else if ( mSearchModeComboBox->currentText() == tr( "RegExp" ) ) { mProxyModel._setFilterRegExp( text ); } } void QgsSpatiaLiteSourceSelect::on_mSearchColumnComboBox_currentIndexChanged( const QString & text ) { if ( text == tr( "All" ) ) { mProxyModel.setFilterKeyColumn( -1 ); } else if ( text == tr( "Table" ) ) { mProxyModel.setFilterKeyColumn( 0 ); } else if ( text == tr( "Type" ) ) { mProxyModel.setFilterKeyColumn( 1 ); } else if ( text == tr( "Geometry column" ) ) { mProxyModel.setFilterKeyColumn( 2 ); } else if ( text == tr( "Sql" ) ) { mProxyModel.setFilterKeyColumn( 3 ); } } void QgsSpatiaLiteSourceSelect::on_mSearchModeComboBox_currentIndexChanged( const QString & text ) { Q_UNUSED( text ); on_mSearchTableEdit_textChanged( mSearchTableEdit->text() ); } void QgsSpatiaLiteSourceSelect::setLayerType( const QString& table, const QString& column, const QString& type ) { mTableModel.setGeometryTypesForTable( table, column, type ); mTablesTreeView->sortByColumn( 0, Qt::AscendingOrder ); } void QgsSpatiaLiteSourceSelect::populateConnectionList() { cmbConnections->clear(); Q_FOREACH ( const QString& name, QgsSpatiaLiteConnection::connectionList() ) { // retrieving the SQLite DB name and full path QString text = name + tr( "@" ) + QgsSpatiaLiteConnection::connectionPath( name ); cmbConnections->addItem( text ); } setConnectionListPosition(); btnConnect->setDisabled( cmbConnections->count() == 0 ); btnDelete->setDisabled( cmbConnections->count() == 0 ); cmbConnections->setDisabled( cmbConnections->count() == 0 ); } void QgsSpatiaLiteSourceSelect::on_btnNew_clicked() { if ( ! newConnection( this ) ) return; populateConnectionList(); emit connectionsChanged(); } bool QgsSpatiaLiteSourceSelect::newConnection( QWidget* parent ) { // Retrieve last used project dir from persistent settings QSettings settings; QString lastUsedDir = settings.value( "/UI/lastSpatiaLiteDir", QDir::homePath() ).toString(); QString myFile = QFileDialog::getOpenFileName( parent, tr( "Choose a SpatiaLite/SQLite DB to open" ), lastUsedDir, tr( "SpatiaLite DB" ) + " (*.sqlite *.db *.sqlite3 *.db3 *.s3db);;" + tr( "All files" ) + " (*)" ); if ( myFile.isEmpty() ) return false; QFileInfo myFI( myFile ); QString myPath = myFI.path(); QString myName = myFI.fileName(); QString savedName = myFI.fileName(); QString baseKey = "/SpatiaLite/connections/"; // TODO: keep the test //handle = openSpatiaLiteDb( myFI.canonicalFilePath() ); //if ( !handle ) // return false; // OK, this one is a valid SpatiaLite DB //closeSpatiaLiteDb( handle ); // if there is already a connection with this name, ask for a new name while ( ! settings.value( baseKey + savedName + "/sqlitepath", "" ).toString().isEmpty() ) { bool ok; savedName = QInputDialog::getText( nullptr , tr( "Cannot add connection '%1'" ).arg( myName ) , tr( "A connection with the same name already exists,\nplease provide a new name:" ), QLineEdit::Normal, "", &ok ); if ( !ok || savedName.isEmpty() ) { return false; } } // Persist last used SpatiaLite dir settings.setValue( "/UI/lastSpatiaLiteDir", myPath ); // inserting this SQLite DB path settings.setValue( baseKey + "selected", savedName ); settings.setValue( baseKey + savedName + "/sqlitepath", myFI.canonicalFilePath() ); return true; } QString QgsSpatiaLiteSourceSelect::layerURI( const QModelIndex &index ) { QString tableName = mTableModel.itemFromIndex( index.sibling( index.row(), 0 ) )->text(); QString geomColumnName = mTableModel.itemFromIndex( index.sibling( index.row(), 2 ) )->text(); QString sql = mTableModel.itemFromIndex( index.sibling( index.row(), 3 ) )->text(); if ( geomColumnName.contains( " AS " ) ) { int a = geomColumnName.indexOf( " AS " ); QString typeName = geomColumnName.mid( a + 4 ); //only the type name geomColumnName = geomColumnName.left( a ); //only the geom column name QString geomFilter; if ( typeName == "POINT" ) { geomFilter = QString( "geometrytype(\"%1\") IN ('POINT','MULTIPOINT')" ).arg( geomColumnName ); } else if ( typeName == "LINESTRING" ) { geomFilter = QString( "geometrytype(\"%1\") IN ('LINESTRING','MULTILINESTRING')" ).arg( geomColumnName ); } else if ( typeName == "POLYGON" ) { geomFilter = QString( "geometrytype(\"%1\") IN ('POLYGON','MULTIPOLYGON')" ).arg( geomColumnName ); } if ( !geomFilter.isEmpty() && !sql.contains( geomFilter ) ) { if ( !sql.isEmpty() ) { sql += " AND "; } sql += geomFilter; } } QgsDataSourceURI uri( connectionInfo() ); uri.setDataSource( "", tableName, geomColumnName, sql, "" ); return uri.uri(); } // Slot for deleting an existing connection void QgsSpatiaLiteSourceSelect::on_btnDelete_clicked() { QString subKey = cmbConnections->currentText(); int idx = subKey.indexOf( '@' ); if ( idx > 0 ) subKey.truncate( idx ); QString msg = tr( "Are you sure you want to remove the %1 connection and all associated settings?" ).arg( subKey ); QMessageBox::StandardButton result = QMessageBox::information( this, tr( "Confirm Delete" ), msg, QMessageBox::Ok | QMessageBox::Cancel ); if ( result != QMessageBox::Ok ) return; QgsSpatiaLiteConnection::deleteConnection( subKey ); populateConnectionList(); emit connectionsChanged(); } void QgsSpatiaLiteSourceSelect::addTables() { m_selectedTables.clear(); typedef QMap < int, bool >schemaInfo; QMap < QString, schemaInfo > dbInfo; QItemSelection selection = mTablesTreeView->selectionModel()->selection(); QModelIndexList selectedIndices = selection.indexes(); QStandardItem *currentItem = nullptr; QModelIndexList::const_iterator selected_it = selectedIndices.constBegin(); for ( ; selected_it != selectedIndices.constEnd(); ++selected_it ) { if ( !selected_it->parent().isValid() ) { //top level items only contain the schema names continue; } currentItem = mTableModel.itemFromIndex( mProxyModel.mapToSource( *selected_it ) ); if ( !currentItem ) { continue; } QString currentSchemaName = currentItem->parent()->text(); int currentRow = currentItem->row(); if ( !dbInfo[currentSchemaName].contains( currentRow ) ) { dbInfo[currentSchemaName][currentRow] = true; m_selectedTables << layerURI( mProxyModel.mapToSource( *selected_it ) ); } } if ( m_selectedTables.empty() ) { QMessageBox::information( this, tr( "Select Table" ), tr( "You must select a table in order to add a Layer." ) ); } else { emit addDatabaseLayers( m_selectedTables, "spatialite" ); if ( !mHoldDialogOpen->isChecked() ) { accept(); } } } void QgsSpatiaLiteSourceSelect::on_btnConnect_clicked() { cbxAllowGeometrylessTables->setEnabled( false ); QString subKey = cmbConnections->currentText(); int idx = subKey.indexOf( '@' ); if ( idx > 0 ) subKey.truncate( idx ); // trying to connect to SpatiaLite DB QgsSpatiaLiteConnection conn( subKey ); mSqlitePath = conn.path(); QApplication::setOverrideCursor( Qt::WaitCursor ); QgsSpatiaLiteConnection::Error err; err = conn.fetchTables( cbxAllowGeometrylessTables->isChecked() ); QApplication::restoreOverrideCursor(); if ( err != QgsSpatiaLiteConnection::NoError ) { QString errCause = conn.errorMessage(); switch ( err ) { case QgsSpatiaLiteConnection::NotExists: QMessageBox::critical( this, tr( "SpatiaLite DB Open Error" ), tr( "Database does not exist: %1" ).arg( mSqlitePath ) ); break; case QgsSpatiaLiteConnection::FailedToOpen: QMessageBox::critical( this, tr( "SpatiaLite DB Open Error" ), tr( "Failure while connecting to: %1\n\n%2" ).arg( mSqlitePath, errCause ) ); break; case QgsSpatiaLiteConnection::FailedToGetTables: QMessageBox::critical( this, tr( "SpatiaLite getTableInfo Error" ), tr( "Failure exploring tables from: %1\n\n%2" ).arg( mSqlitePath, errCause ) ); break; default: QMessageBox::critical( this, tr( "SpatiaLite Error" ), tr( "Unexpected error when working with: %1\n\n%2" ).arg( mSqlitePath, errCause ) ); } mSqlitePath = QString(); return; } QModelIndex rootItemIndex = mTableModel.indexFromItem( mTableModel.invisibleRootItem() ); mTableModel.removeRows( 0, mTableModel.rowCount( rootItemIndex ), rootItemIndex ); // populate the table list // get the list of suitable tables and columns and populate the UI mTableModel.setSqliteDb( subKey ); QList<QgsSpatiaLiteConnection::TableEntry> tables = conn.tables(); Q_FOREACH ( const QgsSpatiaLiteConnection::TableEntry& table, tables ) { mTableModel.addTableEntry( table.type, table.tableName, table.column, "" ); } if ( cmbConnections->count() > 0 ) { mStatsButton->setEnabled( true ); } mTablesTreeView->sortByColumn( 0, Qt::AscendingOrder ); //expand all the toplevel items int numTopLevelItems = mTableModel.invisibleRootItem()->rowCount(); for ( int i = 0; i < numTopLevelItems; ++i ) { mTablesTreeView->expand( mProxyModel.mapFromSource( mTableModel.indexFromItem( mTableModel.invisibleRootItem()->child( i ) ) ) ); } mTablesTreeView->resizeColumnToContents( 0 ); mTablesTreeView->resizeColumnToContents( 1 ); cbxAllowGeometrylessTables->setEnabled( true ); } QStringList QgsSpatiaLiteSourceSelect::selectedTables() { return m_selectedTables; } QString QgsSpatiaLiteSourceSelect::connectionInfo() { return QString( "dbname='%1'" ).arg( QString( mSqlitePath ).replace( '\'', "\\'" ) ); } void QgsSpatiaLiteSourceSelect::setSql( const QModelIndex &index ) { QModelIndex idx = mProxyModel.mapToSource( index ); QString tableName = mTableModel.itemFromIndex( idx.sibling( idx.row(), 0 ) )->text(); QgsVectorLayer *vlayer = new QgsVectorLayer( layerURI( idx ), tableName, "spatialite" ); if ( !vlayer->isValid() ) { delete vlayer; return; } // create a query builder object QgsQueryBuilder *gb = new QgsQueryBuilder( vlayer, this ); if ( gb->exec() ) { mTableModel.setSql( mProxyModel.mapToSource( index ), gb->sql() ); } delete gb; delete vlayer; } QString QgsSpatiaLiteSourceSelect::fullDescription( const QString& table, const QString& column, const QString& type ) { QString full_desc = ""; full_desc += table + "\" (" + column + ") " + type; return full_desc; } void QgsSpatiaLiteSourceSelect::dbChanged() { // Remember which database was selected. QSettings settings; settings.setValue( "/SpatiaLite/connections/selected", cmbConnections->currentText() ); } void QgsSpatiaLiteSourceSelect::setConnectionListPosition() { QSettings settings; // If possible, set the item currently displayed database QString toSelect = settings.value( "/SpatiaLite/connections/selected" ).toString(); toSelect += '@' + settings.value( "/SpatiaLite/connections/" + toSelect + "/sqlitepath" ).toString(); cmbConnections->setCurrentIndex( cmbConnections->findText( toSelect ) ); if ( cmbConnections->currentIndex() < 0 ) { if ( toSelect.isNull() ) cmbConnections->setCurrentIndex( 0 ); else cmbConnections->setCurrentIndex( cmbConnections->count() - 1 ); } } void QgsSpatiaLiteSourceSelect::setSearchExpression( const QString & regexp ) { Q_UNUSED( regexp ); } void QgsSpatiaLiteSourceSelect::treeWidgetSelectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) { Q_UNUSED( deselected ) mAddButton->setEnabled( !selected.isEmpty() ); }
AsgerPetersen/QGIS
src/providers/spatialite/qgsspatialitesourceselect.cpp
C++
gpl-2.0
19,027
@extends('emails.layout') @section('header') {{HTML::linkRoute('admin-index', 'Admin Dashboard')}} @stop @section('title') Request Baru @stop @section('description') Halo admin {{{Config::get('setting.site_name')}}}, <br> Request permintaan informasi dari {{{$name}}}:<br> <br> Untuk melihat detail request silahkan klik link berikut:<br> <h3>{{HTML::link($link, 'Detail request')}}</h3> <br><br> Dikirim oleh<br> Sistem {{{Config::get('setting.site_name')}}} @stop
airputih/kip
app/views/emails/request.blade.php
PHP
gpl-2.0
475
/* * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4923484 8146293 * @summary test ASN.1 encoding generation/parsing for the OAEPParameters * implementation in SunJCE provider. * @author Valerie Peng */ import java.math.BigInteger; import java.util.*; import java.security.*; import java.security.spec.MGF1ParameterSpec; import javax.crypto.*; import javax.crypto.spec.OAEPParameterSpec; import javax.crypto.spec.PSource; public class TestOAEPParameterSpec { private static Provider cp; private static boolean runTest(String mdName, MGF1ParameterSpec mgfSpec, byte[] p) throws Exception { OAEPParameterSpec spec = new OAEPParameterSpec(mdName, "MGF1", mgfSpec, new PSource.PSpecified(p)); cp = Security.getProvider("SunJCE"); System.out.println("Testing provider " + cp.getName() + "..."); AlgorithmParameters ap = AlgorithmParameters.getInstance("OAEP", cp); ap.init(spec); byte[] encoding = ap.getEncoded(); AlgorithmParameters ap2 = AlgorithmParameters.getInstance("OAEP", cp); ap2.init(encoding); OAEPParameterSpec spec2 = (OAEPParameterSpec) ap2.getParameterSpec (OAEPParameterSpec.class); return compareSpec(spec, spec2); } private static boolean compareMD(OAEPParameterSpec s1, OAEPParameterSpec s2) { boolean result = false; String alg1 = s1.getDigestAlgorithm().toUpperCase().trim(); String alg2 = s2.getDigestAlgorithm().toUpperCase().trim(); alg1 = alg1.replaceAll("\\-", ""); alg2 = alg2.replaceAll("\\-", ""); if (alg1.equals("SHA") || alg1.equals("SHA1")) { result = (alg2.equals("SHA") || alg2.equals("SHA1")); } else { result = (alg1.equals(alg2)); } return result; } private static boolean compareMGF(OAEPParameterSpec s1, OAEPParameterSpec s2) { String alg1 = s1.getMGFAlgorithm(); String alg2 = s2.getMGFAlgorithm(); if (alg1.equals(alg2)) { MGF1ParameterSpec mp1 = (MGF1ParameterSpec)s1.getMGFParameters(); MGF1ParameterSpec mp2 = (MGF1ParameterSpec)s2.getMGFParameters(); alg1 = mp1.getDigestAlgorithm(); alg2 = mp2.getDigestAlgorithm(); if (alg1.equals(alg2)) { return true; } else { System.out.println("MGF's MD algos: " + alg1 + " vs " + alg2); return false; } } else { System.out.println("MGF algos: " + alg1 + " vs " + alg2); return false; } } private static boolean comparePSource(OAEPParameterSpec s1, OAEPParameterSpec s2) { PSource src1 = s1.getPSource(); PSource src2 = s2.getPSource(); String alg1 = src1.getAlgorithm(); String alg2 = src2.getAlgorithm(); if (alg1.equals(alg2)) { // assumes they are PSource.PSpecified return Arrays.equals(((PSource.PSpecified) src1).getValue(), ((PSource.PSpecified) src2).getValue()); } else { System.out.println("PSource algos: " + alg1 + " vs " + alg2); return false; } } private static boolean compareSpec(OAEPParameterSpec s1, OAEPParameterSpec s2) { return (compareMD(s1, s2) && compareMGF(s1, s2) && comparePSource(s1, s2)); } public static void main(String[] argv) throws Exception { boolean status = true; byte[] p = { (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04 }; status &= runTest("SHA-224", MGF1ParameterSpec.SHA224, p); status &= runTest("SHA-256", MGF1ParameterSpec.SHA256, p); status &= runTest("SHA-384", MGF1ParameterSpec.SHA384, p); status &= runTest("SHA-512", MGF1ParameterSpec.SHA512, p); status &= runTest("SHA-512/224", MGF1ParameterSpec.SHA512_224, p); status &= runTest("SHA-512/256", MGF1ParameterSpec.SHA512_256, p); status &= runTest("SHA", MGF1ParameterSpec.SHA1, new byte[0]); status &= runTest("SHA-1", MGF1ParameterSpec.SHA1, new byte[0]); status &= runTest("SHA1", MGF1ParameterSpec.SHA1, new byte[0]); if (status) { System.out.println("Test Passed"); } else { throw new Exception("One or More Test Failed"); } } }
JetBrains/jdk8u_jdk
test/com/sun/crypto/provider/Cipher/RSA/TestOAEPParameterSpec.java
Java
gpl-2.0
5,439
<?php /** * Browse action support trait * * PHP version 7 * * Copyright (C) The National Library of Finland 2018. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * 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 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 * * @category VuFind * @package AJAX * @author Ere Maijala <ere.maijala@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ namespace Finna\AjaxHandler; /** * Browse action support trait * * @category VuFind * @package AJAX * @author Ere Maijala <ere.maijala@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ trait BrowseActionTrait { /** * Return browse action from the request. * * @param \Zend\Http\Request $request Request * * @return null|string Browse action or null if request is not a browse action */ protected function getBrowseAction($request) { $referer = $request->getServer()->get('HTTP_REFERER'); $match = null; $regex = '/^http[s]?:.*\/Browse\/(Database|Journal)[\/.*]?/'; if (preg_match($regex, $referer, $match)) { return $match[1]; } return null; } }
samuli/NDL-VuFind2
module/Finna/src/Finna/AjaxHandler/BrowseActionTrait.php
PHP
gpl-2.0
1,874
# If you start collecting a wave and then regret it, you can use this # to roll back the data collection. I would recommend duplicating the database # first and letting this program loose on a copy, as you won't be able to # get back any of the data you don't explicitly tell it to keep. import sqlite3 import itertools import add_data as ad def rollback(db_path,waves_to_keep=[],waves_to_lose=[]): '''waves_to_keep and waves_to_lose should be lists of names of wave tables in the database currently being cleaned''' conn=sqlite3.connect(db_path) curs=conn.cursor() ''' for wave in waves_to_lose: curs.execute('DROP TABLE {}'.format(wave)) users_to_keep=[] for wave in waves_to_keep: curs.execute('SELECT id FROM {}'.format(wave)) users_to_keep.extend(curs.fetchall()) curs.execute('ALTER TABLE users RENAME TO old_users') ad.create_table(curs,'users') curs.execute('ALTER TABLE x_follows_y RENAME TO old_x_follows_y') ad.create_table(curs,'x_follows_y') follow_data=set([]) for n, user in enumerate(users_to_keep): curs.execute('SELECT follower,followed FROM old_x_follows_y ' 'WHERE follower=?',user) follow_data.update(curs.fetchall()) curs.execute('SELECT follower,followed FROM old_x_follows_y ' 'WHERE followed=?',user) follow_data.update(curs.fetchall()) if n % 250 == 0: print "{} users' follow data read.".format(n) curs.executemany('INSERT INTO x_follows_y VALUES (?,?)', follow_data) conn.commit() print 'Cleaned x_follows_y table filled.' ''' curs.execute('SELECT follower,followed FROM old_x_follows_y') follow_data=curs.fetchall() print 'Got follow data: {} follows'.format(len(follow_data)) users_to_keep = set(itertools.chain.from_iterable(follow_data)) print 'Got users from follow data: {} of them'.format(len(users_to_keep)) print list(users_to_keep)[:10] n=0 curs.execute('SELECT * FROM old_users') for i,user_data in enumerate(curs.fetchall()): if user_data[0] in users_to_keep: curs.execute('INSERT INTO users VALUES (' '?,?,?,?,?,?,?,?,?,?,' '?,?,?,?,?,?,?,?,?,?)',user_data) n+=1 if i % 1000 == 0: print '{}th user details checked.'.format(i) if n % 1000 == 0: print '{}th user\'s details copied.'.format(n) print 'Gone through them all now' conn.commit() print 'Cleaned users table filled.'
ValuingElectronicMusic/network-analysis
remove_waves.py
Python
gpl-2.0
2,612
<?php /* BufeteAplicacionBundle:Documento:index.html.twig */ class __TwigTemplate_6cacef96adfcc32d4e0dd4163ee51b1694ed3e96e083117399aab131e4fd4a6e extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 try { $this->parent = $this->env->loadTemplate("BufeteAplicacionBundle::Default/admin.html.twig"); } catch (Twig_Error_Loader $e) { $e->setTemplateFile($this->getTemplateName()); $e->setTemplateLine(1); throw $e; } $this->blocks = array( 'page' => array($this, 'block_page'), ); } protected function doGetParent(array $context) { return "BufeteAplicacionBundle::Default/admin.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 2 public function block_page($context, array $blocks = array()) { // line 3 echo " <div id=\"micaso\" class=\"fullsize\" style=\" background-color: #F0F0D8;height: 540px;\"> <h1>Documento list</h1> <table class=\"records_list\"> <thead> <tr> <th>Id</th> <th>Nombre</th> <th>Descripcion</th> <th>Documento</th> <th>Actions</th> </tr> </thead> <tbody> "; // line 17 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable((isset($context["entities"]) ? $context["entities"] : null)); foreach ($context['_seq'] as $context["_key"] => $context["entity"]) { // line 18 echo " <tr> <td><a href=\""; // line 19 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("documento_show", array("id" => $this->getAttribute($context["entity"], "id", array()))), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute($context["entity"], "id", array()), "html", null, true); echo "</a></td> <td>"; // line 20 echo twig_escape_filter($this->env, $this->getAttribute($context["entity"], "nombre", array()), "html", null, true); echo "</td> <td>"; // line 21 echo twig_escape_filter($this->env, $this->getAttribute($context["entity"], "descripcion", array()), "html", null, true); echo "</td> <td>"; // line 22 echo twig_escape_filter($this->env, $this->getAttribute($context["entity"], "documento", array()), "html", null, true); echo "</td> <td> <ul> <li> <a href=\""; // line 26 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("documento_show", array("id" => $this->getAttribute($context["entity"], "id", array()))), "html", null, true); echo "\">show</a> </li> <li> <a href=\""; // line 29 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("documento_edit", array("id" => $this->getAttribute($context["entity"], "id", array()))), "html", null, true); echo "\">edit</a> </li> </ul> </td> </tr> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['entity'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 35 echo " </tbody> </table> <ul> <li> <a href=\""; // line 40 echo $this->env->getExtension('routing')->getPath("documento_new"); echo "\"> Create a new entry </a> </li> </ul> </div> "; } public function getTemplateName() { return "BufeteAplicacionBundle:Documento:index.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 108 => 40, 101 => 35, 89 => 29, 83 => 26, 76 => 22, 72 => 21, 68 => 20, 62 => 19, 59 => 18, 55 => 17, 39 => 3, 36 => 2, 11 => 1,); } }
AndresFelipe27/ProyectoIngenieriaSoftware3
SW3/app/cache/prod/twig/6c/ac/ef96adfcc32d4e0dd4163ee51b1694ed3e96e083117399aab131e4fd4a6e.php
PHP
gpl-2.0
4,652
// Copyright 2015 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "DolphinQt2/Resources.h" #include "DolphinQt2/GameList/GameListModel.h" #include "DolphinQt2/GameList/GameListProxyModel.h" static constexpr QSize NORMAL_BANNER_SIZE(96, 32); static constexpr QSize LARGE_BANNER_SIZE(144, 48); // Convert an integer size to a friendly string representation. static QString FormatSize(qint64 size) { QStringList units{ QStringLiteral("KB"), QStringLiteral("MB"), QStringLiteral("GB"), QStringLiteral("TB") }; QStringListIterator i(units); QString unit = QStringLiteral("B"); double num = (double) size; while (num > 1024.0 && i.hasNext()) { unit = i.next(); num /= 1024.0; } return QStringLiteral("%1 %2").arg(QString::number(num, 'f', 1)).arg(unit); } GameListProxyModel::GameListProxyModel(QObject* parent) : QSortFilterProxyModel(parent) { } QVariant GameListProxyModel::data(const QModelIndex& i, int role) const { QModelIndex source_index = mapToSource(i); QVariant source_data = sourceModel()->data(source_index, Qt::DisplayRole); if (role == Qt::DisplayRole) { switch (i.column()) { // Sort by the integer but display the formatted string. case GameListModel::COL_SIZE: return FormatSize(source_data.toULongLong()); // These fall through to the underlying model. case GameListModel::COL_ID: case GameListModel::COL_TITLE: case GameListModel::COL_DESCRIPTION: case GameListModel::COL_MAKER: return source_data; // Show the title in the display role of the icon view. case GameListModel::COL_LARGE_ICON: return data(index(i.row(), GameListModel::COL_TITLE), Qt::DisplayRole); } } else if (role == Qt::DecorationRole) { switch (i.column()) { // Show icons in the decoration roles. This lets us sort by the // underlying ints, but display just the icons without doing any // fixed-width hacks. case GameListModel::COL_PLATFORM: return Resources::GetPlatform(source_data.toInt()); case GameListModel::COL_BANNER: return source_data.value<QPixmap>().scaled( NORMAL_BANNER_SIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation); case GameListModel::COL_COUNTRY: return Resources::GetCountry(source_data.toInt()); case GameListModel::COL_RATING: return Resources::GetRating(source_data.toInt()); // Show a scaled icon in the decoration role of the icon view. case GameListModel::COL_LARGE_ICON: return data(index(i.row(), GameListModel::COL_BANNER), Qt::DecorationRole) .value<QPixmap>().scaled( LARGE_BANNER_SIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation); } } return QVariant(); }
asuradaimao/dolphin
Source/Core/DolphinQt2/GameList/GameListProxyModel.cpp
C++
gpl-2.0
2,678
<?php /** * @file * Bartik's theme implementation to display a single Drupal page. * * The doctype, html, head and body tags are not in this template. Instead they * can be found in the html.tpl.php template normally located in the * modules/system folder. * * Available variables: * * General utility variables: * - $base_path: The base URL path of the Drupal installation. At the very * least, this will always default to /. * - $directory: The directory the template is located in, e.g. modules/system * or themes/bartik. * - $is_front: TRUE if the current page is the front page. * - $logged_in: TRUE if the user is registered and signed in. * - $is_admin: TRUE if the user has permission to access administration pages. * * Site identity: * - $front_page: The URL of the front page. Use this instead of $base_path, * when linking to the front page. This includes the language domain or * prefix. * - $logo: The path to the logo image, as defined in theme configuration. * - $site_name: The name of the site, empty when display has been disabled * in theme settings. * - $site_slogan: The slogan of the site, empty when display has been disabled * in theme settings. * - $hide_site_name: TRUE if the site name has been toggled off on the theme * settings page. If hidden, the "element-invisible" class is added to make * the site name visually hidden, but still accessible. * - $hide_site_slogan: TRUE if the site slogan has been toggled off on the * theme settings page. If hidden, the "element-invisible" class is added to * make the site slogan visually hidden, but still accessible. * * Navigation: * - $main_menu (array): An array containing the Main menu links for the * site, if they have been configured. * - $secondary_menu (array): An array containing the Secondary menu links for * the site, if they have been configured. * - $breadcrumb: The breadcrumb trail for the current page. * * Page content (in order of occurrence in the default page.tpl.php): * - $title_prefix (array): An array containing additional output populated by * modules, intended to be displayed in front of the main title tag that * appears in the template. * - $title: The page title, for use in the actual HTML content. * - $title_suffix (array): An array containing additional output populated by * modules, intended to be displayed after the main title tag that appears in * the template. * - $messages: HTML for status and error messages. Should be displayed * prominently. * - $tabs (array): Tabs linking to any sub-pages beneath the current page * (e.g., the view and edit tabs when displaying a node). * - $action_links (array): Actions local to the page, such as 'Add menu' on the * menu administration interface. * - $feed_icons: A string of all feed icons for the current page. * - $node: The node object, if there is an automatically-loaded node * associated with the page, and the node ID is the second argument * in the page's path (e.g. node/12345 and node/12345/revisions, but not * comment/reply/12345). * * Regions: * - $page['search']: Items for the header region. * - $page['top']: Items for the featured region. * - $page['left']: Items for the highlighted content region. * - $page['center']: Dynamic help text, mostly for admin pages. * - $page['right']: The main content of the current page. * - $page['footer']: Items for the footer region. * * @see template_preprocess() * @see template_preprocess_page() * @see template_process() * @see bartik_process_page() */ ?> <script type="text/javascript"> var uvOptions = {}; (function() { var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true; uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/aKrd0ayIyn6BsSmA8yegCQ.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s); })(); </script> <div id="header"> <div id="header-content"> <div id="header-left"> <a href="<?php print $front_page; ?>"><img src="<?php print $logo; ?>" alt="The Open Curriculum Project" /></a><br/> <span id="one-liner"> <?php if ($site_slogan): ?> <?php print $site_slogan; ?> <?php endif; ?> </span> </div> <div id="header-right"> <?php /*if ($secondary_menu): ?> <?php print theme('links__system_secondary_menu', array( 'links' => $secondary_menu, 'attributes' => array( 'id' => 'secondary-menu-links', 'class' => array('links', 'inline', 'clearfix'), ), 'heading' => array( 'text' => t('Secondary menu'), 'level' => 'h2', 'class' => array('element-invisible'), ), )); ?> <!-- /#secondary-menu --> <?php endif;*/ ?> <?php include('login.inc') ?> <?php print render($page['search']); ?> <?php include('gradeblock.inc') ?> </div> </div> </div> <div id="main"> <?php if ($main_menu): ?> <div id="main-menu" class="navigation"> <?php print theme('links__system_main_menu', array( 'links' => $main_menu, 'attributes' => array( 'id' => 'main-menu-links', 'class' => array('links', 'clearfix'), ), 'heading' => array( 'text' => t('Main menu'), 'level' => 'h2', 'class' => array('element-invisible'), ), )); ?> </div> <!-- /#main-menu --> <?php endif; ?> <div id="left-panel"> <?php include('left_menu.inc'); ?> </div> <div id="right-panel"> <?php print render($title_prefix); ?> <?php if ($title): ?> <h1 class="title" id="page-title"> <?php print $title; ?> </h1> <?php endif; ?> <?php print render($title_suffix); ?> <?php if ($breadcrumb): ?> <div id="breadcrumb"><?php print $breadcrumb; ?></div> <?php endif; ?> <?php if ($tabs): ?><p/> <div class="tabs"> <?php print render($tabs); ?> </div> <?php endif; ?> <?php print render($page['help']); ?> <?php if ($action_links): ?> <ul class="action-links"> <?php print render($action_links); ?> </ul> <?php endif; ?><p/> <?php if ($messages): ?> <div id="messages"><div class="section clearfix"> <?php print $messages; ?> </div></div> <!-- /.section, /#messages --> <?php endif; ?> <?php print render($page['content']); ?> </div> </div> <?php include('footer.inc') ?> <?php if ($page['highlighted']): ?><div id="highlighted"><?php print render($page['highlighted']); ?></div><?php endif; ?> <!-- Content was HERE-->
varunarora/OpenCurriculum
sites/all/themes/opencurriculum/templates/page.tpl.php
PHP
gpl-2.0
6,764
/* * Copyright (C) 2013-2015 Tim Mayberry <mojofunk@gmail.com> * Copyright (C) 2014-2016 Paul Davis <paul@linuxaudiosystems.com> * Copyright (C) 2014-2019 Robin Gareus <robin@gareus.org> * * 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. */ #include <iostream> #include <cstdlib> #include <string> #ifdef PLATFORM_WINDOWS #include <fcntl.h> #endif #include <giomm.h> #include <glibmm/thread.h> #include "pbd/pbd.h" #include "pbd/debug.h" #include "pbd/error.h" #include "pbd/id.h" #include "pbd/enumwriter.h" #include "pbd/fpu.h" #include "pbd/xml++.h" #ifdef PLATFORM_WINDOWS #include <winsock2.h> #include "pbd/windows_timer_utils.h" #include "pbd/windows_mmcss.h" #endif #include "pbd/i18n.h" extern void setup_libpbd_enums (); namespace { static bool libpbd_initialized = false; #ifdef PLATFORM_WINDOWS static void test_timers_from_env () { bool set; std::string options; options = Glib::getenv ("PBD_TEST_TIMERS", set); if (set) { if (!PBD::QPC::check_timer_valid ()) { PBD::error << X_("Windows QPC Timer source not usable") << endmsg; } else { PBD::info << X_("Windows QPC Timer source usable") << endmsg; } } } #endif } // namespace bool PBD::init () { if (libpbd_initialized) { return true; } #ifdef PLATFORM_WINDOWS // Essential!! Make sure that any files used by Ardour // will be created or opened in BINARY mode! _fmode = O_BINARY; WSADATA wsaData; /* Initialize windows socket DLL for PBD::CrossThreadChannel */ if (WSAStartup(MAKEWORD(1,1),&wsaData) != 0) { error << X_("Windows socket initialization failed with error: ") << WSAGetLastError() << endmsg; return false; } QPC::initialize(); test_timers_from_env (); if (!PBD::MMCSS::initialize()) { PBD::info << X_("Unable to initialize MMCSS") << endmsg; } else { PBD::info << X_("MMCSS Initialized") << endmsg; } #endif if (!Glib::thread_supported()) { Glib::thread_init(); } Gio::init (); PBD::ID::init (); setup_libpbd_enums (); libpbd_initialized = true; return true; } void PBD::cleanup () { #ifdef PLATFORM_WINDOWS PBD::MMCSS::deinitialize (); WSACleanup(); #endif EnumWriter::destroy (); FPU::destroy (); }
napcode/ardour
libs/pbd/pbd.cc
C++
gpl-2.0
2,849
/* Copyright (C) 2005 Versant Inc. http://www.db4o.com */ using System; using System.Reflection; namespace Sharpen.Lang { public class IdentityHashCodeProvider { #if !CF public static int IdentityHashCode(object obj) { return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); } #else public static int IdentityHashCode(object obj) { if (obj == null) return 0; return (int) _hashMethod.Invoke(null, new object[] { obj }); } private static MethodInfo _hashMethod = GetIdentityHashCodeMethod(); private static MethodInfo GetIdentityHashCodeMethod() { Assembly assembly = typeof(object).Assembly; try { Type t = assembly.GetType("System.PInvoke.EE"); return t.GetMethod( "Object_GetHashCode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); } catch (Exception e) { } // We may be running the CF app on .NET Framework 1.1 // for profiling, let's give that a chance try { Type t = assembly.GetType( "System.Runtime.CompilerServices.RuntimeHelpers"); return t.GetMethod( "GetHashCode", BindingFlags.Public | BindingFlags.Static); } catch { } return null; } #endif } }
meebey/smuxi-head-mirror
lib/db4o-net/Db4objects.Db4o/native/Sharpen/Lang/IdentityHashCodeProvider.cs
C#
gpl-2.0
1,240
/***************************************************************************** Copyright (c) 1996, 2016, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2008, Google Inc. Copyright (c) 2017, MariaDB Corporation. Portions of this file contain modifications contributed and copyrighted by Google, Inc. Those modifications are gratefully acknowledged and are described briefly in the InnoDB documentation. The contributions by Google are incorporated with their permission, and subject to the conditions contained in the file COPYING.Google. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /********************************************************************//** @file btr/btr0sea.cc The index tree adaptive search Created 2/17/1996 Heikki Tuuri *************************************************************************/ #include "btr0sea.h" #ifdef BTR_CUR_HASH_ADAPT #include "buf0buf.h" #include "page0page.h" #include "page0cur.h" #include "btr0cur.h" #include "btr0pcur.h" #include "btr0btr.h" #include "ha0ha.h" #include "srv0mon.h" #include "sync0sync.h" /** Is search system enabled. Search system is protected by array of latches. */ char btr_search_enabled = true; /** Number of adaptive hash index partition. */ ulong btr_ahi_parts = 8; #ifdef UNIV_SEARCH_PERF_STAT /** Number of successful adaptive hash index lookups */ ulint btr_search_n_succ = 0; /** Number of failed adaptive hash index lookups */ ulint btr_search_n_hash_fail = 0; #endif /* UNIV_SEARCH_PERF_STAT */ /** padding to prevent other memory update hotspots from residing on the same memory cache line as btr_search_latches */ UNIV_INTERN byte btr_sea_pad1[CACHE_LINE_SIZE]; /** The latches protecting the adaptive search system: this latches protects the (1) positions of records on those pages where a hash index has been built. NOTE: It does not protect values of non-ordering fields within a record from being updated in-place! We can use fact (1) to perform unique searches to indexes. We will allocate the latches from dynamic memory to get it to the same DRAM page as other hotspot semaphores */ rw_lock_t** btr_search_latches; /** padding to prevent other memory update hotspots from residing on the same memory cache line */ UNIV_INTERN byte btr_sea_pad2[CACHE_LINE_SIZE]; /** The adaptive hash index */ btr_search_sys_t* btr_search_sys; /** If the number of records on the page divided by this parameter would have been successfully accessed using a hash index, the index is then built on the page, assuming the global limit has been reached */ #define BTR_SEARCH_PAGE_BUILD_LIMIT 16 /** The global limit for consecutive potentially successful hash searches, before hash index building is started */ #define BTR_SEARCH_BUILD_LIMIT 100 /** Determine the number of accessed key fields. @param[in] n_fields number of complete fields @param[in] n_bytes number of bytes in an incomplete last field @return number of complete or incomplete fields */ inline MY_ATTRIBUTE((warn_unused_result)) ulint btr_search_get_n_fields( ulint n_fields, ulint n_bytes) { return(n_fields + (n_bytes > 0 ? 1 : 0)); } /** Determine the number of accessed key fields. @param[in] cursor b-tree cursor @return number of complete or incomplete fields */ inline MY_ATTRIBUTE((warn_unused_result)) ulint btr_search_get_n_fields( const btr_cur_t* cursor) { return(btr_search_get_n_fields(cursor->n_fields, cursor->n_bytes)); } /********************************************************************//** Builds a hash index on a page with the given parameters. If the page already has a hash index with different parameters, the old hash index is removed. If index is non-NULL, this function checks if n_fields and n_bytes are sensible values, and does not build a hash index if not. */ static void btr_search_build_page_hash_index( /*=============================*/ dict_index_t* index, /*!< in: index for which to build, or NULL if not known */ buf_block_t* block, /*!< in: index page, s- or x-latched */ ulint n_fields,/*!< in: hash this many full fields */ ulint n_bytes,/*!< in: hash this many bytes from the next field */ ibool left_side);/*!< in: hash for searches from left side? */ /** This function should be called before reserving any btr search mutex, if the intended operation might add nodes to the search system hash table. Because of the latching order, once we have reserved the btr search system latch, we cannot allocate a free frame from the buffer pool. Checks that there is a free buffer frame allocated for hash table heap in the btr search system. If not, allocates a free frames for the heap. This check makes it probable that, when have reserved the btr search system latch and we need to allocate a new node to the hash table, it will succeed. However, the check will not guarantee success. @param[in] index index handler */ static void btr_search_check_free_space_in_heap(dict_index_t* index) { hash_table_t* table; mem_heap_t* heap; ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_S)); ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_X)); table = btr_get_search_table(index); heap = table->heap; /* Note that we peek the value of heap->free_block without reserving the latch: this is ok, because we will not guarantee that there will be enough free space in the hash table. */ if (heap->free_block == NULL) { buf_block_t* block = buf_block_alloc(NULL); btr_search_x_lock(index); if (btr_search_enabled && heap->free_block == NULL) { heap->free_block = block; } else { buf_block_free(block); } btr_search_x_unlock(index); } } /** Creates and initializes the adaptive search system at a database start. @param[in] hash_size hash table size. */ void btr_search_sys_create(ulint hash_size) { /* Search System is divided into n parts. Each part controls access to distinct set of hash buckets from hash table through its own latch. */ /* Step-1: Allocate latches (1 per part). */ btr_search_latches = reinterpret_cast<rw_lock_t**>( ut_malloc(sizeof(rw_lock_t*) * btr_ahi_parts, mem_key_ahi)); for (ulint i = 0; i < btr_ahi_parts; ++i) { btr_search_latches[i] = reinterpret_cast<rw_lock_t*>( ut_malloc(sizeof(rw_lock_t), mem_key_ahi)); rw_lock_create(btr_search_latch_key, btr_search_latches[i], SYNC_SEARCH_SYS); } /* Step-2: Allocate hash tablees. */ btr_search_sys = reinterpret_cast<btr_search_sys_t*>( ut_malloc(sizeof(btr_search_sys_t), mem_key_ahi)); btr_search_sys->hash_tables = reinterpret_cast<hash_table_t**>( ut_malloc(sizeof(hash_table_t*) * btr_ahi_parts, mem_key_ahi)); for (ulint i = 0; i < btr_ahi_parts; ++i) { btr_search_sys->hash_tables[i] = ib_create((hash_size / btr_ahi_parts), LATCH_ID_HASH_TABLE_MUTEX, 0, MEM_HEAP_FOR_BTR_SEARCH); #if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG btr_search_sys->hash_tables[i]->adaptive = TRUE; #endif /* UNIV_AHI_DEBUG || UNIV_DEBUG */ } } /** Resize hash index hash table. @param[in] hash_size hash index hash table size */ void btr_search_sys_resize(ulint hash_size) { /* Step-1: Lock all search latches in exclusive mode. */ btr_search_x_lock_all(); if (btr_search_enabled) { btr_search_x_unlock_all(); ib::error() << "btr_search_sys_resize failed because" " hash index hash table is not empty."; ut_ad(0); return; } /* Step-2: Recreate hash tables with new size. */ for (ulint i = 0; i < btr_ahi_parts; ++i) { mem_heap_free(btr_search_sys->hash_tables[i]->heap); hash_table_free(btr_search_sys->hash_tables[i]); btr_search_sys->hash_tables[i] = ib_create((hash_size / btr_ahi_parts), LATCH_ID_HASH_TABLE_MUTEX, 0, MEM_HEAP_FOR_BTR_SEARCH); #if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG btr_search_sys->hash_tables[i]->adaptive = TRUE; #endif /* UNIV_AHI_DEBUG || UNIV_DEBUG */ } /* Step-3: Unlock all search latches from exclusive mode. */ btr_search_x_unlock_all(); } /** Frees the adaptive search system at a database shutdown. */ void btr_search_sys_free() { ut_ad(btr_search_sys != NULL && btr_search_latches != NULL); /* Step-1: Release the hash tables. */ for (ulint i = 0; i < btr_ahi_parts; ++i) { mem_heap_free(btr_search_sys->hash_tables[i]->heap); hash_table_free(btr_search_sys->hash_tables[i]); } ut_free(btr_search_sys->hash_tables); ut_free(btr_search_sys); btr_search_sys = NULL; /* Step-2: Release all allocates latches. */ for (ulint i = 0; i < btr_ahi_parts; ++i) { rw_lock_free(btr_search_latches[i]); ut_free(btr_search_latches[i]); } ut_free(btr_search_latches); btr_search_latches = NULL; } /** Set index->ref_count = 0 on all indexes of a table. @param[in,out] table table handler */ static void btr_search_disable_ref_count( dict_table_t* table) { dict_index_t* index; ut_ad(mutex_own(&dict_sys->mutex)); for (index = dict_table_get_first_index(table); index != NULL; index = dict_table_get_next_index(index)) { ut_ad(rw_lock_own(btr_get_search_latch(index), RW_LOCK_X)); index->search_info->ref_count = 0; } } /** Disable the adaptive hash search system and empty the index. @param[in] need_mutex need to acquire dict_sys->mutex */ void btr_search_disable( bool need_mutex) { dict_table_t* table; if (need_mutex) { mutex_enter(&dict_sys->mutex); } ut_ad(mutex_own(&dict_sys->mutex)); btr_search_x_lock_all(); if (!btr_search_enabled) { if (need_mutex) { mutex_exit(&dict_sys->mutex); } btr_search_x_unlock_all(); return; } btr_search_enabled = false; /* Clear the index->search_info->ref_count of every index in the data dictionary cache. */ for (table = UT_LIST_GET_FIRST(dict_sys->table_LRU); table; table = UT_LIST_GET_NEXT(table_LRU, table)) { btr_search_disable_ref_count(table); } for (table = UT_LIST_GET_FIRST(dict_sys->table_non_LRU); table; table = UT_LIST_GET_NEXT(table_LRU, table)) { btr_search_disable_ref_count(table); } if (need_mutex) { mutex_exit(&dict_sys->mutex); } /* Set all block->index = NULL. */ buf_pool_clear_hash_index(); /* Clear the adaptive hash index. */ for (ulint i = 0; i < btr_ahi_parts; ++i) { hash_table_clear(btr_search_sys->hash_tables[i]); mem_heap_empty(btr_search_sys->hash_tables[i]->heap); } btr_search_x_unlock_all(); } /** Enable the adaptive hash search system. */ void btr_search_enable() { buf_pool_mutex_enter_all(); if (srv_buf_pool_old_size != srv_buf_pool_size) { buf_pool_mutex_exit_all(); return; } buf_pool_mutex_exit_all(); btr_search_x_lock_all(); btr_search_enabled = true; btr_search_x_unlock_all(); } /** Returns the value of ref_count. The value is protected by latch. @param[in] info search info @param[in] index index identifier @return ref_count value. */ ulint btr_search_info_get_ref_count( btr_search_t* info, dict_index_t* index) { ulint ret = 0; if (!btr_search_enabled) { return(ret); } ut_ad(info); ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_S)); ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_X)); btr_search_s_lock(index); ret = info->ref_count; btr_search_s_unlock(index); return(ret); } /** Updates the search info of an index about hash successes. NOTE that info is NOT protected by any semaphore, to save CPU time! Do not assume its fields are consistent. @param[in,out] info search info @param[in] cursor cursor which was just positioned */ static void btr_search_info_update_hash( btr_search_t* info, btr_cur_t* cursor) { dict_index_t* index = cursor->index; ulint n_unique; int cmp; ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_S)); ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_X)); if (dict_index_is_ibuf(index)) { /* So many deletes are performed on an insert buffer tree that we do not consider a hash index useful on it: */ return; } n_unique = dict_index_get_n_unique_in_tree(index); if (info->n_hash_potential == 0) { goto set_new_recomm; } /* Test if the search would have succeeded using the recommended hash prefix */ if (info->n_fields >= n_unique && cursor->up_match >= n_unique) { increment_potential: info->n_hash_potential++; return; } cmp = ut_pair_cmp(info->n_fields, info->n_bytes, cursor->low_match, cursor->low_bytes); if (info->left_side ? cmp <= 0 : cmp > 0) { goto set_new_recomm; } cmp = ut_pair_cmp(info->n_fields, info->n_bytes, cursor->up_match, cursor->up_bytes); if (info->left_side ? cmp <= 0 : cmp > 0) { goto increment_potential; } set_new_recomm: /* We have to set a new recommendation; skip the hash analysis for a while to avoid unnecessary CPU time usage when there is no chance for success */ info->hash_analysis = 0; cmp = ut_pair_cmp(cursor->up_match, cursor->up_bytes, cursor->low_match, cursor->low_bytes); if (cmp == 0) { info->n_hash_potential = 0; /* For extra safety, we set some sensible values here */ info->n_fields = 1; info->n_bytes = 0; info->left_side = TRUE; } else if (cmp > 0) { info->n_hash_potential = 1; if (cursor->up_match >= n_unique) { info->n_fields = n_unique; info->n_bytes = 0; } else if (cursor->low_match < cursor->up_match) { info->n_fields = cursor->low_match + 1; info->n_bytes = 0; } else { info->n_fields = cursor->low_match; info->n_bytes = cursor->low_bytes + 1; } info->left_side = TRUE; } else { info->n_hash_potential = 1; if (cursor->low_match >= n_unique) { info->n_fields = n_unique; info->n_bytes = 0; } else if (cursor->low_match > cursor->up_match) { info->n_fields = cursor->up_match + 1; info->n_bytes = 0; } else { info->n_fields = cursor->up_match; info->n_bytes = cursor->up_bytes + 1; } info->left_side = FALSE; } } /** Update the block search info on hash successes. NOTE that info and block->n_hash_helps, n_fields, n_bytes, left_side are NOT protected by any semaphore, to save CPU time! Do not assume the fields are consistent. @return TRUE if building a (new) hash index on the block is recommended @param[in,out] info search info @param[in,out] block buffer block @param[in] cursor cursor */ static ibool btr_search_update_block_hash_info( btr_search_t* info, buf_block_t* block, const btr_cur_t* cursor) { ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_S)); ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_X)); ut_ad(rw_lock_own(&block->lock, RW_LOCK_S) || rw_lock_own(&block->lock, RW_LOCK_X)); info->last_hash_succ = FALSE; ut_a(buf_block_state_valid(block)); ut_ad(info->magic_n == BTR_SEARCH_MAGIC_N); if ((block->n_hash_helps > 0) && (info->n_hash_potential > 0) && (block->n_fields == info->n_fields) && (block->n_bytes == info->n_bytes) && (block->left_side == info->left_side)) { if ((block->index) && (block->curr_n_fields == info->n_fields) && (block->curr_n_bytes == info->n_bytes) && (block->curr_left_side == info->left_side)) { /* The search would presumably have succeeded using the hash index */ info->last_hash_succ = TRUE; } block->n_hash_helps++; } else { block->n_hash_helps = 1; block->n_fields = info->n_fields; block->n_bytes = info->n_bytes; block->left_side = info->left_side; } if ((block->n_hash_helps > page_get_n_recs(block->frame) / BTR_SEARCH_PAGE_BUILD_LIMIT) && (info->n_hash_potential >= BTR_SEARCH_BUILD_LIMIT)) { if ((!block->index) || (block->n_hash_helps > 2 * page_get_n_recs(block->frame)) || (block->n_fields != block->curr_n_fields) || (block->n_bytes != block->curr_n_bytes) || (block->left_side != block->curr_left_side)) { /* Build a new hash index on the page */ return(TRUE); } } return(FALSE); } /** Updates a hash node reference when it has been unsuccessfully used in a search which could have succeeded with the used hash parameters. This can happen because when building a hash index for a page, we do not check what happens at page boundaries, and therefore there can be misleading hash nodes. Also, collisions in the fold value can lead to misleading references. This function lazily fixes these imperfections in the hash index. @param[in] info search info @param[in] block buffer block where cursor positioned @param[in] cursor cursor */ static void btr_search_update_hash_ref( const btr_search_t* info, buf_block_t* block, const btr_cur_t* cursor) { dict_index_t* index; ulint fold; rec_t* rec; ut_ad(cursor->flag == BTR_CUR_HASH_FAIL); ut_ad(rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_X)); ut_ad(rw_lock_own(&(block->lock), RW_LOCK_S) || rw_lock_own(&(block->lock), RW_LOCK_X)); ut_ad(page_align(btr_cur_get_rec(cursor)) == buf_block_get_frame(block)); assert_block_ahi_valid(block); index = block->index; if (!index) { return; } ut_ad(block->page.id.space() == index->space); ut_a(index == cursor->index); ut_a(!dict_index_is_ibuf(index)); if ((info->n_hash_potential > 0) && (block->curr_n_fields == info->n_fields) && (block->curr_n_bytes == info->n_bytes) && (block->curr_left_side == info->left_side)) { mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; rec_offs_init(offsets_); rec = btr_cur_get_rec(cursor); if (!page_rec_is_user_rec(rec)) { return; } fold = rec_fold(rec, rec_get_offsets(rec, index, offsets_, ULINT_UNDEFINED, &heap), block->curr_n_fields, block->curr_n_bytes, index->id); if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } ut_ad(rw_lock_own(btr_get_search_latch(index), RW_LOCK_X)); ha_insert_for_fold(btr_get_search_table(index), fold, block, rec); MONITOR_INC(MONITOR_ADAPTIVE_HASH_ROW_ADDED); } } /** Updates the search info. @param[in,out] info search info @param[in] cursor cursor which was just positioned */ void btr_search_info_update_slow( btr_search_t* info, btr_cur_t* cursor) { buf_block_t* block; ibool build_index; ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_S)); ut_ad(!rw_lock_own(btr_get_search_latch(cursor->index), RW_LOCK_X)); block = btr_cur_get_block(cursor); /* NOTE that the following two function calls do NOT protect info or block->n_fields etc. with any semaphore, to save CPU time! We cannot assume the fields are consistent when we return from those functions! */ btr_search_info_update_hash(info, cursor); build_index = btr_search_update_block_hash_info(info, block, cursor); if (build_index || (cursor->flag == BTR_CUR_HASH_FAIL)) { btr_search_check_free_space_in_heap(cursor->index); } if (cursor->flag == BTR_CUR_HASH_FAIL) { /* Update the hash node reference, if appropriate */ #ifdef UNIV_SEARCH_PERF_STAT btr_search_n_hash_fail++; #endif /* UNIV_SEARCH_PERF_STAT */ btr_search_x_lock(cursor->index); btr_search_update_hash_ref(info, block, cursor); btr_search_x_unlock(cursor->index); } if (build_index) { /* Note that since we did not protect block->n_fields etc. with any semaphore, the values can be inconsistent. We have to check inside the function call that they make sense. */ btr_search_build_page_hash_index(cursor->index, block, block->n_fields, block->n_bytes, block->left_side); } } /** Checks if a guessed position for a tree cursor is right. Note that if mode is PAGE_CUR_LE, which is used in inserts, and the function returns TRUE, then cursor->up_match and cursor->low_match both have sensible values. @param[in,out] cursor guess cursor position @param[in] can_only_compare_to_cursor_rec if we do not have a latch on the page of cursor, but a latch corresponding search system, then ONLY the columns of the record UNDER the cursor are protected, not the next or previous record in the chain: we cannot look at the next or previous record to check our guess! @param[in] tuple data tuple @param[in] mode PAGE_CUR_L, PAGE_CUR_LE, PAGE_CUR_G, PAGE_CUR_GE @param[in] mtr mini transaction @return TRUE if success */ static ibool btr_search_check_guess( btr_cur_t* cursor, ibool can_only_compare_to_cursor_rec, const dtuple_t* tuple, ulint mode, mtr_t* mtr) { rec_t* rec; ulint n_unique; ulint match; int cmp; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; ibool success = FALSE; rec_offs_init(offsets_); n_unique = dict_index_get_n_unique_in_tree(cursor->index); rec = btr_cur_get_rec(cursor); ut_ad(page_rec_is_user_rec(rec)); match = 0; offsets = rec_get_offsets(rec, cursor->index, offsets, n_unique, &heap); cmp = cmp_dtuple_rec_with_match(tuple, rec, offsets, &match); if (mode == PAGE_CUR_GE) { if (cmp > 0) { goto exit_func; } cursor->up_match = match; if (match >= n_unique) { success = TRUE; goto exit_func; } } else if (mode == PAGE_CUR_LE) { if (cmp < 0) { goto exit_func; } cursor->low_match = match; } else if (mode == PAGE_CUR_G) { if (cmp >= 0) { goto exit_func; } } else if (mode == PAGE_CUR_L) { if (cmp <= 0) { goto exit_func; } } if (can_only_compare_to_cursor_rec) { /* Since we could not determine if our guess is right just by looking at the record under the cursor, return FALSE */ goto exit_func; } match = 0; if ((mode == PAGE_CUR_G) || (mode == PAGE_CUR_GE)) { rec_t* prev_rec; ut_ad(!page_rec_is_infimum(rec)); prev_rec = page_rec_get_prev(rec); if (page_rec_is_infimum(prev_rec)) { success = btr_page_get_prev(page_align(prev_rec), mtr) == FIL_NULL; goto exit_func; } offsets = rec_get_offsets(prev_rec, cursor->index, offsets, n_unique, &heap); cmp = cmp_dtuple_rec_with_match( tuple, prev_rec, offsets, &match); if (mode == PAGE_CUR_GE) { success = cmp > 0; } else { success = cmp >= 0; } goto exit_func; } else { rec_t* next_rec; ut_ad(!page_rec_is_supremum(rec)); next_rec = page_rec_get_next(rec); if (page_rec_is_supremum(next_rec)) { if (btr_page_get_next(page_align(next_rec), mtr) == FIL_NULL) { cursor->up_match = 0; success = TRUE; } goto exit_func; } offsets = rec_get_offsets(next_rec, cursor->index, offsets, n_unique, &heap); cmp = cmp_dtuple_rec_with_match( tuple, next_rec, offsets, &match); if (mode == PAGE_CUR_LE) { success = cmp < 0; cursor->up_match = match; } else { success = cmp <= 0; } } exit_func: if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } return(success); } static void btr_search_failure(btr_search_t* info, btr_cur_t* cursor) { cursor->flag = BTR_CUR_HASH_FAIL; #ifdef UNIV_SEARCH_PERF_STAT ++info->n_hash_fail; if (info->n_hash_succ > 0) { --info->n_hash_succ; } #endif /* UNIV_SEARCH_PERF_STAT */ info->last_hash_succ = FALSE; } /** Tries to guess the right search position based on the hash search info of the index. Note that if mode is PAGE_CUR_LE, which is used in inserts, and the function returns TRUE, then cursor->up_match and cursor->low_match both have sensible values. @param[in,out] index index @param[in,out] info index search info @param[in] tuple logical record @param[in] mode PAGE_CUR_L, .... @param[in] latch_mode BTR_SEARCH_LEAF, ...; NOTE that only if has_search_latch is 0, we will have a latch set on the cursor page, otherwise we assume the caller uses his search latch to protect the record! @param[out] cursor tree cursor @param[in] has_search_latch latch mode the caller currently has on search system: RW_S/X_LATCH or 0 @param[in] mtr mini transaction @return TRUE if succeeded */ ibool btr_search_guess_on_hash( dict_index_t* index, btr_search_t* info, const dtuple_t* tuple, ulint mode, ulint latch_mode, btr_cur_t* cursor, ulint has_search_latch, mtr_t* mtr) { const rec_t* rec; ulint fold; index_id_t index_id; #ifdef notdefined btr_cur_t cursor2; btr_pcur_t pcur; #endif if (!btr_search_enabled) { return(FALSE); } ut_ad(index && info && tuple && cursor && mtr); ut_ad(!dict_index_is_ibuf(index)); ut_ad((latch_mode == BTR_SEARCH_LEAF) || (latch_mode == BTR_MODIFY_LEAF)); /* Not supported for spatial index */ ut_ad(!dict_index_is_spatial(index)); /* Note that, for efficiency, the struct info may not be protected by any latch here! */ if (info->n_hash_potential == 0) { return(FALSE); } cursor->n_fields = info->n_fields; cursor->n_bytes = info->n_bytes; if (dtuple_get_n_fields(tuple) < btr_search_get_n_fields(cursor)) { return(FALSE); } index_id = index->id; #ifdef UNIV_SEARCH_PERF_STAT info->n_hash_succ++; #endif fold = dtuple_fold(tuple, cursor->n_fields, cursor->n_bytes, index_id); cursor->fold = fold; cursor->flag = BTR_CUR_HASH; if (!has_search_latch) { btr_search_s_lock(index); if (!btr_search_enabled) { btr_search_s_unlock(index); btr_search_failure(info, cursor); return(FALSE); } } ut_ad(rw_lock_get_writer(btr_get_search_latch(index)) != RW_LOCK_X); ut_ad(rw_lock_get_reader_count(btr_get_search_latch(index)) > 0); rec = (rec_t*) ha_search_and_get_data( btr_get_search_table(index), fold); if (rec == NULL) { if (!has_search_latch) { btr_search_s_unlock(index); } btr_search_failure(info, cursor); return(FALSE); } buf_block_t* block = buf_block_from_ahi(rec); if (!has_search_latch) { if (!buf_page_get_known_nowait( latch_mode, block, BUF_MAKE_YOUNG, __FILE__, __LINE__, mtr)) { if (!has_search_latch) { btr_search_s_unlock(index); } btr_search_failure(info, cursor); return(FALSE); } btr_search_s_unlock(index); buf_block_dbg_add_level(block, SYNC_TREE_NODE_FROM_HASH); } if (buf_block_get_state(block) != BUF_BLOCK_FILE_PAGE) { ut_ad(buf_block_get_state(block) == BUF_BLOCK_REMOVE_HASH); if (!has_search_latch) { btr_leaf_page_release(block, latch_mode, mtr); } btr_search_failure(info, cursor); return(FALSE); } ut_ad(page_rec_is_user_rec(rec)); btr_cur_position(index, (rec_t*) rec, block, cursor); /* Check the validity of the guess within the page */ /* If we only have the latch on search system, not on the page, it only protects the columns of the record the cursor is positioned on. We cannot look at the next of the previous record to determine if our guess for the cursor position is right. */ if (index_id != btr_page_get_index_id(block->frame) || !btr_search_check_guess(cursor, has_search_latch, tuple, mode, mtr)) { if (!has_search_latch) { btr_leaf_page_release(block, latch_mode, mtr); } btr_search_failure(info, cursor); return(FALSE); } if (info->n_hash_potential < BTR_SEARCH_BUILD_LIMIT + 5) { info->n_hash_potential++; } #ifdef notdefined /* These lines of code can be used in a debug version to check the correctness of the searched cursor position: */ info->last_hash_succ = FALSE; /* Currently, does not work if the following fails: */ ut_ad(!has_search_latch); btr_leaf_page_release(block, latch_mode, mtr); btr_cur_search_to_nth_level( index, 0, tuple, mode, latch_mode, &cursor2, 0, mtr); if (mode == PAGE_CUR_GE && page_rec_is_supremum(btr_cur_get_rec(&cursor2))) { /* If mode is PAGE_CUR_GE, then the binary search in the index tree may actually take us to the supremum of the previous page */ info->last_hash_succ = FALSE; btr_pcur_open_on_user_rec( index, tuple, mode, latch_mode, &pcur, mtr); ut_ad(btr_pcur_get_rec(&pcur) == btr_cur_get_rec(cursor)); } else { ut_ad(btr_cur_get_rec(&cursor2) == btr_cur_get_rec(cursor)); } /* NOTE that it is theoretically possible that the above assertions fail if the page of the cursor gets removed from the buffer pool meanwhile! Thus it might not be a bug. */ #endif info->last_hash_succ = TRUE; #ifdef UNIV_SEARCH_PERF_STAT btr_search_n_succ++; #endif if (!has_search_latch && buf_page_peek_if_too_old(&block->page)) { buf_page_make_young(&block->page); } /* Increment the page get statistics though we did not really fix the page: for user info only */ { buf_pool_t* buf_pool = buf_pool_from_bpage(&block->page); ++buf_pool->stat.n_page_gets; } return(TRUE); } /** Drop any adaptive hash index entries that point to an index page. @param[in,out] block block containing index page, s- or x-latched, or an index page for which we know that block->buf_fix_count == 0 or it is an index page which has already been removed from the buf_pool->page_hash i.e.: it is in state BUF_BLOCK_REMOVE_HASH */ void btr_search_drop_page_hash_index(buf_block_t* block) { ulint n_fields; ulint n_bytes; const page_t* page; const rec_t* rec; ulint fold; ulint prev_fold; ulint n_cached; ulint n_recs; ulint* folds; ulint i; mem_heap_t* heap; const dict_index_t* index; ulint* offsets; rw_lock_t* latch; btr_search_t* info; retry: /* Do a dirty check on block->index, return if the block is not in the adaptive hash index. */ index = block->index; /* This debug check uses a dirty read that could theoretically cause false positives while buf_pool_clear_hash_index() is executing. */ assert_block_ahi_valid(block); if (index == NULL) { return; } ut_ad(block->page.buf_fix_count == 0 || buf_block_get_state(block) == BUF_BLOCK_REMOVE_HASH || rw_lock_own(&block->lock, RW_LOCK_S) || rw_lock_own(&block->lock, RW_LOCK_X)); /* We must not dereference index here, because it could be freed if (index->table->n_ref_count == 0 && !mutex_own(&dict_sys->mutex)). Determine the ahi_slot based on the block contents. */ const index_id_t index_id = btr_page_get_index_id(block->frame); const ulint ahi_slot = ut_fold_ulint_pair(static_cast<ulint>(index_id), static_cast<ulint>(block->page.id.space())) % btr_ahi_parts; latch = btr_search_latches[ahi_slot]; ut_ad(!btr_search_own_any(RW_LOCK_S)); ut_ad(!btr_search_own_any(RW_LOCK_X)); rw_lock_s_lock(latch); assert_block_ahi_valid(block); if (block->index == NULL) { rw_lock_s_unlock(latch); return; } /* The index associated with a block must remain the same, because we are holding block->lock or the block is not accessible by other threads (BUF_BLOCK_REMOVE_HASH), or the index is not accessible to other threads (buf_fix_count == 0 when DROP TABLE or similar is executing buf_LRU_drop_page_hash_for_tablespace()). */ ut_a(index == block->index); #ifdef MYSQL_INDEX_DISABLE_AHI ut_ad(!index->disable_ahi); #endif ut_ad(btr_search_enabled); ut_ad(block->page.id.space() == index->space); ut_a(index_id == index->id); ut_a(!dict_index_is_ibuf(index)); #ifdef UNIV_DEBUG switch (dict_index_get_online_status(index)) { case ONLINE_INDEX_CREATION: /* The index is being created (bulk loaded). */ case ONLINE_INDEX_COMPLETE: /* The index has been published. */ case ONLINE_INDEX_ABORTED: /* Either the index creation was aborted due to an error observed by InnoDB (in which case there should not be any adaptive hash index entries), or it was completed and then flagged aborted in rollback_inplace_alter_table(). */ break; case ONLINE_INDEX_ABORTED_DROPPED: /* The index should have been dropped from the tablespace already, and the adaptive hash index entries should have been dropped as well. */ ut_error; } #endif /* UNIV_DEBUG */ n_fields = block->curr_n_fields; n_bytes = block->curr_n_bytes; /* NOTE: The AHI fields of block must not be accessed after releasing search latch, as the index page might only be s-latched! */ rw_lock_s_unlock(latch); ut_a(n_fields > 0 || n_bytes > 0); page = block->frame; n_recs = page_get_n_recs(page); /* Calculate and cache fold values into an array for fast deletion from the hash index */ folds = (ulint*) ut_malloc_nokey(n_recs * sizeof(ulint)); n_cached = 0; rec = page_get_infimum_rec(page); rec = page_rec_get_next_low(rec, page_is_comp(page)); prev_fold = 0; heap = NULL; offsets = NULL; while (!page_rec_is_supremum(rec)) { offsets = rec_get_offsets( rec, index, offsets, btr_search_get_n_fields(n_fields, n_bytes), &heap); fold = rec_fold(rec, offsets, n_fields, n_bytes, index_id); if (fold == prev_fold && prev_fold != 0) { goto next_rec; } /* Remove all hash nodes pointing to this page from the hash chain */ folds[n_cached] = fold; n_cached++; next_rec: rec = page_rec_get_next_low(rec, page_rec_is_comp(rec)); prev_fold = fold; } if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } rw_lock_x_lock(latch); if (UNIV_UNLIKELY(!block->index)) { /* Someone else has meanwhile dropped the hash index */ goto cleanup; } ut_a(block->index == index); if (block->curr_n_fields != n_fields || block->curr_n_bytes != n_bytes) { /* Someone else has meanwhile built a new hash index on the page, with different parameters */ rw_lock_x_unlock(latch); ut_free(folds); goto retry; } for (i = 0; i < n_cached; i++) { ha_remove_all_nodes_to_page( btr_search_sys->hash_tables[ahi_slot], folds[i], page); } info = btr_search_get_info(block->index); ut_a(info->ref_count > 0); info->ref_count--; block->index = NULL; MONITOR_INC(MONITOR_ADAPTIVE_HASH_PAGE_REMOVED); MONITOR_INC_VALUE(MONITOR_ADAPTIVE_HASH_ROW_REMOVED, n_cached); cleanup: assert_block_ahi_valid(block); rw_lock_x_unlock(latch); ut_free(folds); } /** Drop any adaptive hash index entries that may point to an index page that may be in the buffer pool, when a page is evicted from the buffer pool or freed in a file segment. @param[in] page_id page id @param[in] page_size page size */ void btr_search_drop_page_hash_when_freed( const page_id_t& page_id, const page_size_t& page_size) { buf_block_t* block; mtr_t mtr; dberr_t err = DB_SUCCESS; ut_d(export_vars.innodb_ahi_drop_lookups++); mtr_start(&mtr); /* If the caller has a latch on the page, then the caller must have a x-latch on the page and it must have already dropped the hash index for the page. Because of the x-latch that we are possibly holding, we cannot s-latch the page, but must (recursively) x-latch it, even though we are only reading. */ block = buf_page_get_gen(page_id, page_size, RW_X_LATCH, NULL, BUF_PEEK_IF_IN_POOL, __FILE__, __LINE__, &mtr, &err); if (block) { /* If AHI is still valid, page can't be in free state. AHI is dropped when page is freed. */ ut_ad(!block->page.file_page_was_freed); buf_block_dbg_add_level(block, SYNC_TREE_NODE_FROM_HASH); dict_index_t* index = block->index; if (index != NULL) { /* In all our callers, the table handle should be open, or we should be in the process of dropping the table (preventing eviction). */ ut_ad(index->table->n_ref_count > 0 || mutex_own(&dict_sys->mutex)); btr_search_drop_page_hash_index(block); } } mtr_commit(&mtr); } /** Build a hash index on a page with the given parameters. If the page already has a hash index with different parameters, the old hash index is removed. If index is non-NULL, this function checks if n_fields and n_bytes are sensible, and does not build a hash index if not. @param[in,out] index index for which to build. @param[in,out] block index page, s-/x- latched. @param[in] n_fields hash this many full fields @param[in] n_bytes hash this many bytes of the next field @param[in] left_side hash for searches from left side */ static void btr_search_build_page_hash_index( dict_index_t* index, buf_block_t* block, ulint n_fields, ulint n_bytes, ibool left_side) { hash_table_t* table; page_t* page; rec_t* rec; rec_t* next_rec; ulint fold; ulint next_fold; ulint n_cached; ulint n_recs; ulint* folds; rec_t** recs; ulint i; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; #ifdef MYSQL_INDEX_DISABLE_AHI if (index->disable_ahi) return; #endif if (!btr_search_enabled) { return; } rec_offs_init(offsets_); ut_ad(index); ut_ad(block->page.id.space() == index->space); ut_a(!dict_index_is_ibuf(index)); ut_ad(!rw_lock_own(btr_get_search_latch(index), RW_LOCK_X)); ut_ad(rw_lock_own(&(block->lock), RW_LOCK_S) || rw_lock_own(&(block->lock), RW_LOCK_X)); btr_search_s_lock(index); table = btr_get_search_table(index); page = buf_block_get_frame(block); if (block->index && ((block->curr_n_fields != n_fields) || (block->curr_n_bytes != n_bytes) || (block->curr_left_side != left_side))) { btr_search_s_unlock(index); btr_search_drop_page_hash_index(block); } else { btr_search_s_unlock(index); } /* Check that the values for hash index build are sensible */ if (n_fields == 0 && n_bytes == 0) { return; } if (dict_index_get_n_unique_in_tree(index) < btr_search_get_n_fields(n_fields, n_bytes)) { return; } n_recs = page_get_n_recs(page); if (n_recs == 0) { return; } /* Calculate and cache fold values and corresponding records into an array for fast insertion to the hash index */ folds = (ulint*) ut_malloc_nokey(n_recs * sizeof(ulint)); recs = (rec_t**) ut_malloc_nokey(n_recs * sizeof(rec_t*)); n_cached = 0; ut_a(index->id == btr_page_get_index_id(page)); rec = page_rec_get_next(page_get_infimum_rec(page)); offsets = rec_get_offsets( rec, index, offsets, btr_search_get_n_fields(n_fields, n_bytes), &heap); ut_ad(page_rec_is_supremum(rec) || n_fields + (n_bytes > 0) == rec_offs_n_fields(offsets)); fold = rec_fold(rec, offsets, n_fields, n_bytes, index->id); if (left_side) { folds[n_cached] = fold; recs[n_cached] = rec; n_cached++; } for (;;) { next_rec = page_rec_get_next(rec); if (page_rec_is_supremum(next_rec)) { if (!left_side) { folds[n_cached] = fold; recs[n_cached] = rec; n_cached++; } break; } offsets = rec_get_offsets( next_rec, index, offsets, btr_search_get_n_fields(n_fields, n_bytes), &heap); next_fold = rec_fold(next_rec, offsets, n_fields, n_bytes, index->id); if (fold != next_fold) { /* Insert an entry into the hash index */ if (left_side) { folds[n_cached] = next_fold; recs[n_cached] = next_rec; n_cached++; } else { folds[n_cached] = fold; recs[n_cached] = rec; n_cached++; } } rec = next_rec; fold = next_fold; } btr_search_check_free_space_in_heap(index); btr_search_x_lock(index); if (!btr_search_enabled) { goto exit_func; } if (block->index && ((block->curr_n_fields != n_fields) || (block->curr_n_bytes != n_bytes) || (block->curr_left_side != left_side))) { goto exit_func; } /* This counter is decremented every time we drop page hash index entries and is incremented here. Since we can rebuild hash index for a page that is already hashed, we have to take care not to increment the counter in that case. */ if (!block->index) { assert_block_ahi_empty(block); index->search_info->ref_count++; } block->n_hash_helps = 0; block->curr_n_fields = unsigned(n_fields); block->curr_n_bytes = unsigned(n_bytes); block->curr_left_side = unsigned(left_side); block->index = index; for (i = 0; i < n_cached; i++) { ha_insert_for_fold(table, folds[i], block, recs[i]); } MONITOR_INC(MONITOR_ADAPTIVE_HASH_PAGE_ADDED); MONITOR_INC_VALUE(MONITOR_ADAPTIVE_HASH_ROW_ADDED, n_cached); exit_func: assert_block_ahi_valid(block); btr_search_x_unlock(index); ut_free(folds); ut_free(recs); if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } } /** Moves or deletes hash entries for moved records. If new_page is already hashed, then the hash index for page, if any, is dropped. If new_page is not hashed, and page is hashed, then a new hash index is built to new_page with the same parameters as page (this often happens when a page is split). @param[in,out] new_block records are copied to this page. @param[in,out] block index page from which record are copied, and the copied records will be deleted from this page. @param[in,out] index record descriptor */ void btr_search_move_or_delete_hash_entries( buf_block_t* new_block, buf_block_t* block, dict_index_t* index) { #ifdef MYSQL_INDEX_DISABLE_AHI if (index->disable_ahi) return; #endif if (!btr_search_enabled) { return; } ut_ad(rw_lock_own(&(block->lock), RW_LOCK_X)); ut_ad(rw_lock_own(&(new_block->lock), RW_LOCK_X)); btr_search_s_lock(index); ut_a(!new_block->index || new_block->index == index); ut_a(!block->index || block->index == index); ut_a(!(new_block->index || block->index) || !dict_index_is_ibuf(index)); assert_block_ahi_valid(block); assert_block_ahi_valid(new_block); if (new_block->index) { btr_search_s_unlock(index); btr_search_drop_page_hash_index(block); return; } if (block->index) { ulint n_fields = block->curr_n_fields; ulint n_bytes = block->curr_n_bytes; ibool left_side = block->curr_left_side; new_block->n_fields = block->curr_n_fields; new_block->n_bytes = block->curr_n_bytes; new_block->left_side = left_side; btr_search_s_unlock(index); ut_a(n_fields > 0 || n_bytes > 0); btr_search_build_page_hash_index( index, new_block, n_fields, n_bytes, left_side); ut_ad(n_fields == block->curr_n_fields); ut_ad(n_bytes == block->curr_n_bytes); ut_ad(left_side == block->curr_left_side); return; } btr_search_s_unlock(index); } /** Updates the page hash index when a single record is deleted from a page. @param[in] cursor cursor which was positioned on the record to delete using btr_cur_search_, the record is not yet deleted.*/ void btr_search_update_hash_on_delete(btr_cur_t* cursor) { hash_table_t* table; buf_block_t* block; const rec_t* rec; ulint fold; dict_index_t* index; ulint offsets_[REC_OFFS_NORMAL_SIZE]; mem_heap_t* heap = NULL; rec_offs_init(offsets_); #ifdef MYSQL_INDEX_DISABLE_AHI if (cursor->index->disable_ahi) return; #endif if (!btr_search_enabled) { return; } block = btr_cur_get_block(cursor); ut_ad(rw_lock_own(&(block->lock), RW_LOCK_X)); assert_block_ahi_valid(block); index = block->index; if (!index) { return; } ut_ad(block->page.id.space() == index->space); ut_a(index == cursor->index); ut_a(block->curr_n_fields > 0 || block->curr_n_bytes > 0); ut_a(!dict_index_is_ibuf(index)); table = btr_get_search_table(index); rec = btr_cur_get_rec(cursor); fold = rec_fold(rec, rec_get_offsets(rec, index, offsets_, ULINT_UNDEFINED, &heap), block->curr_n_fields, block->curr_n_bytes, index->id); if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } btr_search_x_lock(index); assert_block_ahi_valid(block); if (block->index) { ut_a(block->index == index); if (ha_search_and_delete_if_found(table, fold, rec)) { MONITOR_INC(MONITOR_ADAPTIVE_HASH_ROW_REMOVED); } else { MONITOR_INC( MONITOR_ADAPTIVE_HASH_ROW_REMOVE_NOT_FOUND); } assert_block_ahi_valid(block); } btr_search_x_unlock(index); } /** Updates the page hash index when a single record is inserted on a page. @param[in] cursor cursor which was positioned to the place to insert using btr_cur_search_, and the new record has been inserted next to the cursor. */ void btr_search_update_hash_node_on_insert(btr_cur_t* cursor) { hash_table_t* table; buf_block_t* block; dict_index_t* index; rec_t* rec; #ifdef MYSQL_INDEX_DISABLE_AHI if (cursor->index->disable_ahi) return; #endif if (!btr_search_enabled) { return; } rec = btr_cur_get_rec(cursor); block = btr_cur_get_block(cursor); ut_ad(rw_lock_own(&(block->lock), RW_LOCK_X)); index = block->index; if (!index) { return; } ut_a(cursor->index == index); ut_a(!dict_index_is_ibuf(index)); btr_search_x_lock(index); if (!block->index) { goto func_exit; } ut_a(block->index == index); if ((cursor->flag == BTR_CUR_HASH) && (cursor->n_fields == block->curr_n_fields) && (cursor->n_bytes == block->curr_n_bytes) && !block->curr_left_side) { table = btr_get_search_table(index); if (ha_search_and_update_if_found( table, cursor->fold, rec, block, page_rec_get_next(rec))) { MONITOR_INC(MONITOR_ADAPTIVE_HASH_ROW_UPDATED); } func_exit: assert_block_ahi_valid(block); btr_search_x_unlock(index); } else { btr_search_x_unlock(index); btr_search_update_hash_on_insert(cursor); } } /** Updates the page hash index when a single record is inserted on a page. @param[in,out] cursor cursor which was positioned to the place to insert using btr_cur_search_..., and the new record has been inserted next to the cursor */ void btr_search_update_hash_on_insert(btr_cur_t* cursor) { hash_table_t* table; buf_block_t* block; dict_index_t* index; const rec_t* rec; const rec_t* ins_rec; const rec_t* next_rec; ulint fold; ulint ins_fold; ulint next_fold = 0; /* remove warning (??? bug ???) */ ulint n_fields; ulint n_bytes; ibool left_side; ibool locked = FALSE; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; rec_offs_init(offsets_); #ifdef MYSQL_INDEX_DISABLE_AHI if (cursor->index->disable_ahi) return; #endif if (!btr_search_enabled) { return; } block = btr_cur_get_block(cursor); ut_ad(rw_lock_own(&(block->lock), RW_LOCK_X)); assert_block_ahi_valid(block); index = block->index; if (!index) { return; } ut_ad(block->page.id.space() == index->space); btr_search_check_free_space_in_heap(index); table = btr_get_search_table(index); rec = btr_cur_get_rec(cursor); #ifdef MYSQL_INDEX_DISABLE_AHI ut_a(!index->disable_ahi); #endif ut_a(index == cursor->index); ut_a(!dict_index_is_ibuf(index)); n_fields = block->curr_n_fields; n_bytes = block->curr_n_bytes; left_side = block->curr_left_side; ins_rec = page_rec_get_next_const(rec); next_rec = page_rec_get_next_const(ins_rec); offsets = rec_get_offsets(ins_rec, index, offsets, ULINT_UNDEFINED, &heap); ins_fold = rec_fold(ins_rec, offsets, n_fields, n_bytes, index->id); if (!page_rec_is_supremum(next_rec)) { offsets = rec_get_offsets( next_rec, index, offsets, btr_search_get_n_fields(n_fields, n_bytes), &heap); next_fold = rec_fold(next_rec, offsets, n_fields, n_bytes, index->id); } if (!page_rec_is_infimum(rec)) { offsets = rec_get_offsets( rec, index, offsets, btr_search_get_n_fields(n_fields, n_bytes), &heap); fold = rec_fold(rec, offsets, n_fields, n_bytes, index->id); } else { if (left_side) { btr_search_x_lock(index); locked = TRUE; if (!btr_search_enabled) { goto function_exit; } ha_insert_for_fold(table, ins_fold, block, ins_rec); } goto check_next_rec; } if (fold != ins_fold) { if (!locked) { btr_search_x_lock(index); locked = TRUE; if (!btr_search_enabled) { goto function_exit; } } if (!left_side) { ha_insert_for_fold(table, fold, block, rec); } else { ha_insert_for_fold(table, ins_fold, block, ins_rec); } } check_next_rec: if (page_rec_is_supremum(next_rec)) { if (!left_side) { if (!locked) { btr_search_x_lock(index); locked = TRUE; if (!btr_search_enabled) { goto function_exit; } } ha_insert_for_fold(table, ins_fold, block, ins_rec); } goto function_exit; } if (ins_fold != next_fold) { if (!locked) { btr_search_x_lock(index); locked = TRUE; if (!btr_search_enabled) { goto function_exit; } } if (!left_side) { ha_insert_for_fold(table, ins_fold, block, ins_rec); } else { ha_insert_for_fold(table, next_fold, block, next_rec); } } function_exit: if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } if (locked) { btr_search_x_unlock(index); } } #if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG /** Validates the search system for given hash table. @param[in] hash_table_id hash table to validate @return TRUE if ok */ static ibool btr_search_hash_table_validate(ulint hash_table_id) { ha_node_t* node; ibool ok = TRUE; ulint i; ulint cell_count; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; if (!btr_search_enabled) { return(TRUE); } /* How many cells to check before temporarily releasing search latches. */ ulint chunk_size = 10000; rec_offs_init(offsets_); btr_search_x_lock_all(); buf_pool_mutex_enter_all(); cell_count = hash_get_n_cells( btr_search_sys->hash_tables[hash_table_id]); for (i = 0; i < cell_count; i++) { /* We release search latches every once in a while to give other queries a chance to run. */ if ((i != 0) && ((i % chunk_size) == 0)) { buf_pool_mutex_exit_all(); btr_search_x_unlock_all(); os_thread_yield(); btr_search_x_lock_all(); buf_pool_mutex_enter_all(); ulint curr_cell_count = hash_get_n_cells( btr_search_sys->hash_tables[hash_table_id]); if (cell_count != curr_cell_count) { cell_count = curr_cell_count; if (i >= cell_count) { break; } } } node = (ha_node_t*) hash_get_nth_cell( btr_search_sys->hash_tables[hash_table_id], i)->node; for (; node != NULL; node = node->next) { const buf_block_t* block = buf_block_from_ahi((byte*) node->data); const buf_block_t* hash_block; buf_pool_t* buf_pool; index_id_t page_index_id; buf_pool = buf_pool_from_bpage((buf_page_t*) block); if (UNIV_LIKELY(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE)) { /* The space and offset are only valid for file blocks. It is possible that the block is being freed (BUF_BLOCK_REMOVE_HASH, see the assertion and the comment below) */ hash_block = buf_block_hash_get( buf_pool, block->page.id); } else { hash_block = NULL; } if (hash_block) { ut_a(hash_block == block); } else { /* When a block is being freed, buf_LRU_search_and_free_block() first removes the block from buf_pool->page_hash by calling buf_LRU_block_remove_hashed_page(). After that, it invokes btr_search_drop_page_hash_index() to remove the block from btr_search_sys->hash_tables[i]. */ ut_a(buf_block_get_state(block) == BUF_BLOCK_REMOVE_HASH); } ut_a(!dict_index_is_ibuf(block->index)); ut_ad(block->page.id.space() == block->index->space); page_index_id = btr_page_get_index_id(block->frame); offsets = rec_get_offsets( node->data, block->index, offsets, btr_search_get_n_fields(block->curr_n_fields, block->curr_n_bytes), &heap); const ulint fold = rec_fold( node->data, offsets, block->curr_n_fields, block->curr_n_bytes, page_index_id); if (node->fold != fold) { const page_t* page = block->frame; ok = FALSE; ib::error() << "Error in an adaptive hash" << " index pointer to page " << page_id_t(page_get_space_id(page), page_get_page_no(page)) << ", ptr mem address " << reinterpret_cast<const void*>( node->data) << ", index id " << page_index_id << ", node fold " << node->fold << ", rec fold " << fold; fputs("InnoDB: Record ", stderr); rec_print_new(stderr, node->data, offsets); fprintf(stderr, "\nInnoDB: on that page." " Page mem address %p, is hashed %p," " n fields %lu\n" "InnoDB: side %lu\n", (void*) page, (void*) block->index, (ulong) block->curr_n_fields, (ulong) block->curr_left_side); ut_ad(0); } } } for (i = 0; i < cell_count; i += chunk_size) { /* We release search latches every once in a while to give other queries a chance to run. */ if (i != 0) { buf_pool_mutex_exit_all(); btr_search_x_unlock_all(); os_thread_yield(); btr_search_x_lock_all(); buf_pool_mutex_enter_all(); ulint curr_cell_count = hash_get_n_cells( btr_search_sys->hash_tables[hash_table_id]); if (cell_count != curr_cell_count) { cell_count = curr_cell_count; if (i >= cell_count) { break; } } } ulint end_index = ut_min(i + chunk_size - 1, cell_count - 1); if (!ha_validate(btr_search_sys->hash_tables[hash_table_id], i, end_index)) { ok = FALSE; } } buf_pool_mutex_exit_all(); btr_search_x_unlock_all(); if (UNIV_LIKELY_NULL(heap)) { mem_heap_free(heap); } return(ok); } /** Validate the search system. @return true if ok. */ bool btr_search_validate() { for (ulint i = 0; i < btr_ahi_parts; ++i) { if (!btr_search_hash_table_validate(i)) { return(false); } } return(true); } #endif /* defined UNIV_AHI_DEBUG || defined UNIV_DEBUG */ #endif /* BTR_CUR_HASH_ADAPT */
chidelmun/server
storage/innobase/btr/btr0sea.cc
C++
gpl-2.0
53,277
/*FreeMind - A Program for creating and viewing Mindmaps *Copyright (C) 2000-2006 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others. * *See COPYING for Details * *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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * Created on 08.05.2005 * */ package freemind.common; /** * Utility Class for displaying local object names in GUI components. * * @author Dimitri Polivaev * 18.01.2007 */ public class NamedObject{ private String name; private Object object; private NamedObject(){ } public NamedObject(Object object, String name) { this.object = object; this.name = name; } static public NamedObject literal(String literal){ NamedObject result = new NamedObject(); result.object = literal; result.name = literal; return result; } public boolean equals(Object o){ if (o instanceof NamedObject){ NamedObject ts = (NamedObject)o; return object.equals(ts.object); } return object.equals(o); } public String toString(){ return name; } public Object getObject(){ return object; } }
TheProjecter/sharedmind
freemind/common/NamedObject.java
Java
gpl-2.0
1,843
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('QuickBooking', '0010_auto_20150704_1942'), ] operations = [ migrations.AlterField( model_name='seat', name='seat_type', field=models.CharField(max_length=10, primary_key=True), ), ]
noorelden/QuickBooking
QuickBooking/migrations/0011_auto_20150704_2001.py
Python
gpl-2.0
426
/* * libjingle * Copyright 2004--2011 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "talk/app/webrtc/peerconnectionfactory.h" #include "talk/app/webrtc/audiotrack.h" #include "talk/app/webrtc/localaudiosource.h" #include "talk/app/webrtc/mediastream.h" #include "talk/app/webrtc/mediastreamproxy.h" #include "talk/app/webrtc/mediastreamtrackproxy.h" #include "talk/app/webrtc/peerconnection.h" #include "talk/app/webrtc/peerconnectionfactoryproxy.h" #include "talk/app/webrtc/peerconnectionproxy.h" #include "talk/app/webrtc/portallocatorfactory.h" #include "talk/app/webrtc/videosource.h" #include "talk/app/webrtc/videosourceproxy.h" #include "talk/app/webrtc/videotrack.h" #include "talk/media/webrtc/webrtcmediaengine.h" #include "talk/media/webrtc/webrtcvideodecoderfactory.h" #include "talk/media/webrtc/webrtcvideoencoderfactory.h" #include "webrtc/base/bind.h" #include "webrtc/modules/audio_device/include/audio_device.h" namespace webrtc { namespace { // Passes down the calls to |store_|. See usage in CreatePeerConnection. class DtlsIdentityStoreWrapper : public DtlsIdentityStoreInterface { public: DtlsIdentityStoreWrapper( const rtc::scoped_refptr<RefCountedDtlsIdentityStore>& store) : store_(store) { RTC_DCHECK(store_); } void RequestIdentity( rtc::KeyType key_type, const rtc::scoped_refptr<webrtc::DtlsIdentityRequestObserver>& observer) override { store_->RequestIdentity(key_type, observer); } private: rtc::scoped_refptr<RefCountedDtlsIdentityStore> store_; }; } // anonymous namespace rtc::scoped_refptr<PeerConnectionFactoryInterface> CreatePeerConnectionFactory() { rtc::scoped_refptr<PeerConnectionFactory> pc_factory( new rtc::RefCountedObject<PeerConnectionFactory>()); // Call Initialize synchronously but make sure its executed on // |signaling_thread|. MethodCall0<PeerConnectionFactory, bool> call( pc_factory.get(), &PeerConnectionFactory::Initialize); bool result = call.Marshal(pc_factory->signaling_thread()); if (!result) { return NULL; } return PeerConnectionFactoryProxy::Create(pc_factory->signaling_thread(), pc_factory); } rtc::scoped_refptr<PeerConnectionFactoryInterface> CreatePeerConnectionFactory( rtc::Thread* worker_thread, rtc::Thread* signaling_thread, AudioDeviceModule* default_adm, cricket::WebRtcVideoEncoderFactory* encoder_factory, cricket::WebRtcVideoDecoderFactory* decoder_factory) { rtc::scoped_refptr<PeerConnectionFactory> pc_factory( new rtc::RefCountedObject<PeerConnectionFactory>(worker_thread, signaling_thread, default_adm, encoder_factory, decoder_factory)); // Call Initialize synchronously but make sure its executed on // |signaling_thread|. MethodCall0<PeerConnectionFactory, bool> call( pc_factory.get(), &PeerConnectionFactory::Initialize); bool result = call.Marshal(signaling_thread); if (!result) { return NULL; } return PeerConnectionFactoryProxy::Create(signaling_thread, pc_factory); } PeerConnectionFactory::PeerConnectionFactory() : owns_ptrs_(true), wraps_current_thread_(false), signaling_thread_(rtc::ThreadManager::Instance()->CurrentThread()), worker_thread_(new rtc::Thread) { if (!signaling_thread_) { signaling_thread_ = rtc::ThreadManager::Instance()->WrapCurrentThread(); wraps_current_thread_ = true; } worker_thread_->Start(); } PeerConnectionFactory::PeerConnectionFactory( rtc::Thread* worker_thread, rtc::Thread* signaling_thread, AudioDeviceModule* default_adm, cricket::WebRtcVideoEncoderFactory* video_encoder_factory, cricket::WebRtcVideoDecoderFactory* video_decoder_factory) : owns_ptrs_(false), wraps_current_thread_(false), signaling_thread_(signaling_thread), worker_thread_(worker_thread), default_adm_(default_adm), video_encoder_factory_(video_encoder_factory), video_decoder_factory_(video_decoder_factory) { ASSERT(worker_thread != NULL); ASSERT(signaling_thread != NULL); // TODO: Currently there is no way creating an external adm in // libjingle source tree. So we can 't currently assert if this is NULL. // ASSERT(default_adm != NULL); } PeerConnectionFactory::~PeerConnectionFactory() { RTC_DCHECK(signaling_thread_->IsCurrent()); channel_manager_.reset(nullptr); default_allocator_factory_ = nullptr; // Make sure |worker_thread_| and |signaling_thread_| outlive // |dtls_identity_store_|. dtls_identity_store_ = nullptr; if (owns_ptrs_) { if (wraps_current_thread_) rtc::ThreadManager::Instance()->UnwrapCurrentThread(); delete worker_thread_; } } bool PeerConnectionFactory::Initialize() { RTC_DCHECK(signaling_thread_->IsCurrent()); rtc::InitRandom(rtc::Time()); default_allocator_factory_ = PortAllocatorFactory::Create(worker_thread_); if (!default_allocator_factory_) return false; // TODO: Need to make sure only one VoE is created inside // WebRtcMediaEngine. cricket::MediaEngineInterface* media_engine = worker_thread_->Invoke<cricket::MediaEngineInterface*>(rtc::Bind( &PeerConnectionFactory::CreateMediaEngine_w, this)); channel_manager_.reset( new cricket::ChannelManager(media_engine, worker_thread_)); channel_manager_->SetVideoRtxEnabled(true); if (!channel_manager_->Init()) { return false; } dtls_identity_store_ = new RefCountedDtlsIdentityStore( signaling_thread_, worker_thread_); return true; } rtc::scoped_refptr<AudioSourceInterface> PeerConnectionFactory::CreateAudioSource( const MediaConstraintsInterface* constraints) { RTC_DCHECK(signaling_thread_->IsCurrent()); rtc::scoped_refptr<LocalAudioSource> source( LocalAudioSource::Create(options_, constraints)); return source; } rtc::scoped_refptr<VideoSourceInterface> PeerConnectionFactory::CreateVideoSource( cricket::VideoCapturer* capturer, const MediaConstraintsInterface* constraints) { RTC_DCHECK(signaling_thread_->IsCurrent()); rtc::scoped_refptr<VideoSource> source( VideoSource::Create(channel_manager_.get(), capturer, constraints)); return VideoSourceProxy::Create(signaling_thread_, source); } bool PeerConnectionFactory::StartAecDump(rtc::PlatformFile file) { RTC_DCHECK(signaling_thread_->IsCurrent()); return channel_manager_->StartAecDump(file); } void PeerConnectionFactory::StopAecDump() { RTC_DCHECK(signaling_thread_->IsCurrent()); channel_manager_->StopAecDump(); } bool PeerConnectionFactory::StartRtcEventLog(rtc::PlatformFile file) { RTC_DCHECK(signaling_thread_->IsCurrent()); return channel_manager_->StartRtcEventLog(file); } void PeerConnectionFactory::StopRtcEventLog() { RTC_DCHECK(signaling_thread_->IsCurrent()); channel_manager_->StopRtcEventLog(); } rtc::scoped_refptr<PeerConnectionInterface> PeerConnectionFactory::CreatePeerConnection( const PeerConnectionInterface::RTCConfiguration& configuration, const MediaConstraintsInterface* constraints, PortAllocatorFactoryInterface* allocator_factory, rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store, PeerConnectionObserver* observer) { RTC_DCHECK(signaling_thread_->IsCurrent()); RTC_DCHECK(allocator_factory || default_allocator_factory_); if (!dtls_identity_store.get()) { // Because |pc|->Initialize takes ownership of the store we need a new // wrapper object that can be deleted without deleting the underlying // |dtls_identity_store_|, protecting it from being deleted multiple times. dtls_identity_store.reset( new DtlsIdentityStoreWrapper(dtls_identity_store_)); } PortAllocatorFactoryInterface* chosen_allocator_factory = allocator_factory ? allocator_factory : default_allocator_factory_.get(); chosen_allocator_factory->SetNetworkIgnoreMask(options_.network_ignore_mask); rtc::scoped_refptr<PeerConnection> pc( new rtc::RefCountedObject<PeerConnection>(this)); if (!pc->Initialize( configuration, constraints, chosen_allocator_factory, dtls_identity_store.Pass(), observer)) { return NULL; } return PeerConnectionProxy::Create(signaling_thread(), pc); } rtc::scoped_refptr<MediaStreamInterface> PeerConnectionFactory::CreateLocalMediaStream(const std::string& label) { RTC_DCHECK(signaling_thread_->IsCurrent()); return MediaStreamProxy::Create(signaling_thread_, MediaStream::Create(label)); } rtc::scoped_refptr<VideoTrackInterface> PeerConnectionFactory::CreateVideoTrack( const std::string& id, VideoSourceInterface* source) { RTC_DCHECK(signaling_thread_->IsCurrent()); rtc::scoped_refptr<VideoTrackInterface> track( VideoTrack::Create(id, source)); return VideoTrackProxy::Create(signaling_thread_, track); } rtc::scoped_refptr<AudioTrackInterface> PeerConnectionFactory::CreateAudioTrack(const std::string& id, AudioSourceInterface* source) { RTC_DCHECK(signaling_thread_->IsCurrent()); rtc::scoped_refptr<AudioTrackInterface> track( AudioTrack::Create(id, source)); return AudioTrackProxy::Create(signaling_thread_, track); } webrtc::MediaControllerInterface* PeerConnectionFactory::CreateMediaController() const { RTC_DCHECK(signaling_thread_->IsCurrent()); return MediaControllerInterface::Create(worker_thread_, channel_manager_.get()); } rtc::Thread* PeerConnectionFactory::signaling_thread() { // This method can be called on a different thread when the factory is // created in CreatePeerConnectionFactory(). return signaling_thread_; } rtc::Thread* PeerConnectionFactory::worker_thread() { RTC_DCHECK(signaling_thread_->IsCurrent()); return worker_thread_; } cricket::MediaEngineInterface* PeerConnectionFactory::CreateMediaEngine_w() { ASSERT(worker_thread_ == rtc::Thread::Current()); return cricket::WebRtcMediaEngineFactory::Create( default_adm_.get(), video_encoder_factory_.get(), video_decoder_factory_.get()); } } // namespace webrtc
raj-bhatia/grooveip-ios-public
submodules/mswebrtc/webrtc/talk/app/webrtc/peerconnectionfactory.cc
C++
gpl-2.0
11,762
using UnityEngine; using System.Collections; public class RUISOculusFollow : MonoBehaviour { RUISCoordinateSystem coordinateSystem; void Start() { coordinateSystem = MonoBehaviour.FindObjectOfType(typeof(RUISCoordinateSystem)) as RUISCoordinateSystem; } void Update () { if(RUISOVRManager.ovrHmd != null) { Vector3 tempSample = Vector3.zero; Ovr.Posef headpose = RUISOVRManager.ovrHmd.GetTrackingState().HeadPose.ThePose; float px = headpose.Position.x; float py = headpose.Position.y; float pz = -headpose.Position.z; // This needs to be negated TODO: might change with future OVR version tempSample = new Vector3(px, py, pz); tempSample = coordinateSystem.ConvertRawOculusDK2Location(tempSample); Vector3 convertedLocation = coordinateSystem.ConvertLocation(tempSample, RUISDevice.Oculus_DK2); this.transform.localPosition = convertedLocation; if(OVRManager.capiHmd != null) { try { this.transform.localRotation = OVRManager.capiHmd.GetTrackingState().HeadPose.ThePose.Orientation.ToQuaternion(); } catch(System.Exception e) { Debug.LogError(e.Message); } } } } }
znjRoLS/RUISHarryPotter
HarryPoter/RUISunity/Assets/RUIS/Scripts/Input/Calibration/RUISOculusFollow.cs
C#
gpl-2.0
1,178
var lvl1 = (function () { var xPartition = 320; var preload = function () { // tilemap this.xPartition = xPartition; game.load.tilemap('map', 'assets/map.json', null, Phaser.Tilemap.TILED_JSON); game.load.image('floor', 'assets/floor.png'); game.load.image('tileset', 'assets/tileset.png'); game.load.image('wall', 'assets/wall.png'); // furniture game.load.spritesheet('door', 'assets/door.png', 48, 80); game.load.spritesheet('phone', 'assets/phone.png', 32, 48); game.load.spritesheet('atm', 'assets/atm.png', 48, 80); // ppj game.load.spritesheet('cracker', 'assets/cracker.png', 48, 96); game.load.spritesheet('sysadmin', 'assets/sysadmin.png', 48, 96); game.load.spritesheet('secre0', 'assets/ingenuous.png', 48, 96); game.load.spritesheet('secre1', 'assets/ingenuous2.png', 48, 96); game.load.image('pear', 'assets/pear.png'); // removing blury images game.stage.smoothed = false; }; var create = function () { // Background color. game.stage.backgroundColor = '#eee'; // Physics. game.physics.startSystem(Phaser.Physics.ARCADE); // Sprites creation this.tilemap = map(this, xPartition); this.cracker = cracker(this); this.cursor = cursor(); // this is a horrible patch: do not remove it, unless // you wanna fix cracker's overlapDoor conflict this.cracker.cursor = this.cursor; // creating doors this.doors = this.tilemap.parseDoors(); // creating phones this.phones = parsePhones(this, this.tilemap, this.tilemap.phone); // creating sysadmins this.sysadmins = parseSysadmins(this, this.tilemap, this.tilemap.sysadmin, this.phones); // creating atms this.atms = parseAtms(this, this.tilemap, this.tilemap.atm); // scoreboard this.scoreboard = scoreboard(this.phones); // creating secres this.secres = parseSecres(this, this.tilemap, this.tilemap.secre, this.phones, this.scoreboard); this.spawner = new spawner(this); // bringing to top things (below this line) this.cracker.bringToTop(); this.sysadmins.forEach( function (sysadmin) { sysadmin.bringToTop(); }); this.secres.forEach( function (secre) { secre.bringToTop(); }); }; var update = function () { this.spawner.update(); // sysadmin fixes the atm's game.physics.arcade.overlap(this.atms, this.sysadmins, function (atm, sysadmin) { atm.animations.play('ok'); }); this.secres.lookPhone(); }; // check the cracker.js file! the overlapDoor function ;) return { create : create, preload : preload, update : update }; })(); var game = new Phaser.Game(800, 640, Phaser.AUTO, 'game'); game.state.add('lvl1', lvl1); game.state.start('lvl1'); // Global variables window.firstAtmCracked = false; window.firstPhishing = false;
mehhhh/TheLammerGame
game.js
JavaScript
gpl-2.0
3,254
/*---------------------------------------------------------------------------*\ ## #### ###### | ## ## ## | Copyright: ICE Stroemungsfoschungs GmbH ## ## #### | ## ## ## | http://www.ice-sf.at ## #### ###### | ------------------------------------------------------------------------------- ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2008 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is based on OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Class Description Define types for searchableSurfaces that changed SourceFiles Contributors/Copyright: 2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at> SWAK Revision: $Id$ \*---------------------------------------------------------------------------*/ #ifndef SwakSurfaceTypesMacroHeader_H #define SwakSurfaceTypesMacroHeader_H #include "swak.H" #ifdef FOAM_VOLUMETYPE_IS_TYPE #define INSIDE volumeType::INSIDE #define OUTSIDE volumeType::OUTSIDE #define UNKNOWN volumeType::UNKNOWN #define MIXED volumeType::MIXED #endif #if FOAM_VERSION4SWAK > VERSION_NR2(2,2) && !defined(FOAM_DEV) #define FOAM_SEARCHABLE_SURF_NEEDS_BOUNDING_SPHERES #endif #endif // ************************************************************************* //
aliozel/swak4Foam
Libraries/simpleSearchableSurfaces/include/swakSurfaceTypes.H
C++
gpl-2.0
2,158
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2011 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // {{{ requires require_once CLASS_EX_REALDIR . 'page_extends/LC_Page_Ex.php'; /** * 会員登録完了のページクラス. * * @package Page * @author LOCKON CO.,LTD. * @version $Id:LC_Page_Regist_Complete.php 15532 2007-08-31 14:39:46Z nanasess $ */ class LC_Page_Regist_Complete extends LC_Page_Ex { // }}} // {{{ functions /** * Page を初期化する. * * @return void */ function init() { parent::init(); $this->tpl_title = '会員登録(完了ページ)'; $this->tpl_conv_page = AFF_ENTRY_COMPLETE; } /** * Page のプロセス. * * @return void */ function process() { parent::process(); $this->action(); $this->sendResponse(); } /** * Page のAction. * * @return void */ function action() { } /** * デストラクタ. * * @return void */ function destroy() { parent::destroy(); } } ?>
sin3fu3/inkjet-conveni
data/class/pages/regist/LC_Page_Regist_Complete.php
PHP
gpl-2.0
1,863
<?php class Auth extends Eloquent{ protected $table = 'auth'; }
mhndev/shopping
app/models/Auth.php
PHP
gpl-2.0
70
/* QueryJ Copyright (C) 2002-today Jose San Leandro Armendariz chous@acm-sl.org This library 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 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 General Public License for more details. You should have received a copy of the GNU 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 Thanks to ACM S.L. for distributing this library under the GPL license. Contact info: jose.sanleandro@acm-sl.com ****************************************************************************** * * Filename: DataAccessManagerTemplateGenerator.java * * Author: Jose San Leandro Armendariz * * Description: Is able to generate DataAccessManager implementations * according to database metadata. * */ package org.acmsl.queryj.templates.dao; /* * Importing some project-specific classes. */ import org.acmsl.queryj.api.AbstractTemplateGenerator; import org.acmsl.queryj.api.PerRepositoryTemplateGenerator; /* * Importing checkthread.org annotations. */ import org.checkthread.annotations.ThreadSafe; /** * Is able to generate DataAccessManager implementations according * to database metadata. * @author <a href="mailto:chous@acm-sl.org">Jose San Leandro Armendariz</a> */ @ThreadSafe public class DataAccessManagerTemplateGenerator extends AbstractTemplateGenerator<DataAccessManagerTemplate> implements PerRepositoryTemplateGenerator<DataAccessManagerTemplate> { /** * Creates a new {@link DataAccessContextLocalTemplateGenerator} with given settings. * @param caching whether to enable caching. * @param threadCount the number of threads to use. */ public DataAccessManagerTemplateGenerator(final boolean caching, final int threadCount) { super(caching, threadCount); } }
rydnr/queryj-rt
queryj-templates-deprecated/src/main/java/org/acmsl/queryj/templates/dao/DataAccessManagerTemplateGenerator.java
Java
gpl-2.0
2,309
// K-3D // Copyright (c) 1995-2009, Timothy M. Shead // // Contact: tshead@k-3d.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <k3dsdk/log_control.h> #include <k3dsdk/xml.h> #include <k3dsdk/xpath.h> using namespace k3d::xml; #include <iostream> #include <stdexcept> #include <sstream> #define test_expression(expression) \ { \ if(!(expression)) \ { \ std::ostringstream buffer; \ buffer << "Expression failed at line " << __LINE__ << ": " << #expression; \ throw std::runtime_error(buffer.str()); \ } \ } int main(int argc, char* argv[]) { k3d::log_color_level(true); k3d::log_show_level(true); k3d::log_minimum_level(k3d::K3D_LOG_LEVEL_DEBUG); try { element document("k3d", element("nodes", element("node", attribute("class", "foo") ), element("node", attribute("factory", "bar"), element("properties", element("property", attribute("user_property", ""), attribute("type", "double") ) ) ) ), element("dependencies" ) ); xpath::result_set results; results = xpath::match(document, ""); test_expression(results.size() == 0); results = xpath::match(document, "/"); test_expression(results.size() == 0); results = xpath::match(document, "/foo"); test_expression(results.size() == 0); results = xpath::match(document, "/k3d"); test_expression(results.size() == 1); test_expression(results[0]->name == "k3d"); results = xpath::match(document, "/k3d/*"); test_expression(results.size() == 2); test_expression(results[0]->name == "nodes"); test_expression(results[1]->name == "dependencies"); results = xpath::match(document, "/k3d/nodes"); test_expression(results.size() == 1); test_expression(results[0]->name == "nodes"); results = xpath::match(document, "/k3d/nodes/node"); test_expression(results.size() == 2); test_expression(results[0]->name == "node"); test_expression(results[1]->name == "node"); results = xpath::match(document, "/k3d/nodes/node[@class]"); test_expression(results.size() == 1); test_expression(find_attribute(*results[0], "class")); test_expression(!find_attribute(*results[0], "factory")); results = xpath::match(document, "/k3d/nodes/node/properties/property[@user_property][@type='double']"); test_expression(results.size() == 1); results = xpath::match(document, "nodes"); test_expression(results.size() == 1); test_expression(results[0]->name == "nodes"); results = xpath::match(document, "nodes/node"); test_expression(results.size() == 2); test_expression(results[0]->name == "node"); test_expression(results[1]->name == "node"); } catch(std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
barche/k3d
tests/sdk/xml_xpath.cpp
C++
gpl-2.0
3,438
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.performance; import com.rapidminer.example.Attribute; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.operator.OperatorException; import com.rapidminer.tools.math.Averagable; /** * Returns the average value of the prediction. This criterion can be used to * detect whether a learning scheme predicts nonsense, e.g. always make the same * error. This criterion is not suitable for evaluating the performance and * should never be used as main criterion. The {@link #getFitness()} method * always returns 0. * * @author Ingo Mierswa * @version $Id: PredictionAverage.java,v 2.18 2006/03/21 15:35:51 ingomierswa * Exp $ */ public class PredictionAverage extends MeasuredPerformance { private static final long serialVersionUID = -5316112625406102611L; private double sum; private double squaredSum; private double count; private Attribute labelAttribute; private Attribute weightAttribute; public PredictionAverage() { } public PredictionAverage(PredictionAverage pa) { super(pa); this.sum = pa.sum; this.squaredSum = pa.squaredSum; this.count = pa.count; this.labelAttribute = (Attribute)pa.labelAttribute.clone(); if (pa.weightAttribute != null) this.weightAttribute = (Attribute)pa.weightAttribute.clone(); } public double getExampleCount() { return count; } public void countExample(Example example) { double weight = 1.0d; if (weightAttribute != null) weight = example.getValue(weightAttribute); count += weight; double v = example.getLabel(); if (!Double.isNaN(v)) { sum += v * weight; squaredSum += v * v * weight * weight; } } public double getMikroAverage() { return sum / count; } public double getMikroVariance() { double avg = getMikroAverage(); return (squaredSum / count) - avg * avg; } public void startCounting(ExampleSet set, boolean useExampleWeights) throws OperatorException { super.startCounting(set, useExampleWeights); count = 0; sum = 0.0; this.labelAttribute = set.getAttributes().getLabel(); if (useExampleWeights) this.weightAttribute = set.getAttributes().getWeight(); } public String getName() { return "prediction_average"; } /** Returns 0. */ public double getFitness() { return 0.0; } public void buildSingleAverage(Averagable performance) { PredictionAverage other = (PredictionAverage) performance; this.sum += other.sum; this.squaredSum += other.squaredSum; this.count += other.count; } public String getDescription() { return "This is not a real performance measure, but merely the average of the predicted labels."; } }
ntj/ComplexRapidMiner
src/com/rapidminer/operator/performance/PredictionAverage.java
Java
gpl-2.0
3,662
<?php /** * @package Joomla.Site * @subpackage Layout * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Create a shortcut for params. $params = $displayData->params; $canEdit = $displayData->params->get('access-edit'); JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html'); ?> <?php if ($params->get('show_title') || $displayData->state == 0 || ($params->get('show_author') && !empty($displayData->author ))) : ?> <div class="page-header"> <?php if ($params->get('show_title')) : ?> <h2 > <?php if ($params->get('link_titles') && $params->get('access-view')) : ?> <a href="<?php echo JRoute::_(ContentHelperRoute::getArticleRoute($displayData->slug, $displayData->catid)); ?>" > <?php echo $this->escape($displayData->title); ?></a> <?php else : ?> <?php echo $this->escape($displayData->title); ?> <?php endif; ?> </h2> <?php endif; ?> <?php if ($displayData->state == 0) : ?> <span class="label label-warning"><?php echo JText::_('JUNPUBLISHED'); ?></span> <?php endif; ?> <?php if (strtotime($displayData->publish_up) > strtotime(JFactory::getDate())) : ?> <span class="label label-warning"><?php echo JText::_('JNOTPUBLISHEDYET'); ?></span> <?php endif; ?> <?php if ((strtotime($displayData->publish_down) < strtotime(JFactory::getDate())) && $displayData->publish_down != '0000-00-00 00:00:00') : ?> <span class="label label-warning"><?php echo JText::_('JEXPIRED'); ?></span> <?php endif; ?> </div> <?php endif; ?>
site4com/j-gov-3-it
layouts/joomla/content/blog_style_default_item_title.php
PHP
gpl-2.0
1,670
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using HUX.Buttons; using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; namespace HUX { public class HUXEditorUtils { public readonly static Color DefaultColor = new Color(1f, 1f, 1f); public readonly static Color DisabledColor = new Color(0.6f, 0.6f, 0.6f); public readonly static Color BorderedColor = new Color(0.8f, 0.8f, 0.8f); public readonly static Color WarningColor = new Color(1f, 0.85f, 0.6f); public readonly static Color ErrorColor = new Color(1f, 0.55f, 0.5f); public readonly static Color SuccessColor = new Color(0.8f, 1f, 0.75f); public readonly static Color ObjectColor = new Color(0.85f, 0.9f, 1f); public readonly static Color HelpBoxColor = new Color(0.22f, 0.23f, 0.24f, 0.45f); public readonly static Color SectionColor = new Color(0.42f, 0.43f, 0.47f, 0.25f); public readonly static Color DarkColor = new Color(0.1f, 0.1f, 0.1f); public readonly static Color ObjectColorEmpty = new Color(0.75f, 0.8f, 0.9f); /// <summary> /// Draws a field for scriptable object profiles /// If base class T is abstract, includes a button for creating a profile of each type that inherits from base class T /// Otherwise just includes button for creating a profile of type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="profile"></param> /// <returns></returns> public static T DrawProfileField<T>(T profile) where T : ButtonProfile { Color prevColor = GUI.color; GUI.color = Color.Lerp(Color.white, Color.gray, 0.5f); EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.Lerp(Color.white, Color.gray, 0.25f); EditorGUILayout.LabelField("Select a " + typeof(T).Name + " or create a new profile", EditorStyles.miniBoldLabel); T newProfile = profile; EditorGUILayout.BeginHorizontal(); newProfile = (T)EditorGUILayout.ObjectField(profile, typeof(T), false); // is this an abstract class? if (typeof(T).IsAbstract) { EditorGUILayout.BeginVertical(); List<Type> types = GetDerivedTypes(typeof(T), Assembly.GetAssembly(typeof(T))); foreach (Type profileType in types) { if (GUILayout.Button("Create " + profileType.Name)) { profile = CreateProfile<T>(profileType); } } EditorGUILayout.EndVertical(); } else { if (GUILayout.Button("Create Profile")) { profile = CreateProfile<T>(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); if (profile == null) { ErrorMessage("You must choose a button profile.", null); } GUI.color = prevColor; return newProfile; } public static T CreateProfile<T>(Type profileType) where T : ButtonProfile { T asset = (T)ScriptableObject.CreateInstance(profileType); if (asset != null) { AssetDatabase.CreateAsset(asset, "Assets/New" + profileType.Name + ".asset"); AssetDatabase.SaveAssets(); } else { Debug.LogError("Couldn't create profile of type " + profileType.Name); } return asset; } public static T CreateProfile<T>() where T : ButtonProfile { T asset = ScriptableObject.CreateInstance<T>(); AssetDatabase.CreateAsset(asset, "Assets/New" + typeof(T).Name + ".asset"); AssetDatabase.SaveAssets(); return asset; } public static void DrawFilterTagField(SerializedObject serializedObject, string propertyName) { SerializedProperty p = serializedObject.FindProperty(propertyName); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(p); if (EditorGUI.EndChangeCheck()) serializedObject.ApplyModifiedProperties(); } public static void DrawProfileInspector(ButtonProfile profile, Component targetComponent) { ProfileInspector profileEditor = (ProfileInspector)Editor.CreateEditor(profile); profileEditor.targetComponent = targetComponent; profileEditor.OnInspectorGUI(); } public static T DropDownComponentField<T>(string label, T obj, Transform transform, bool showComponentName = false) where T : UnityEngine.Component { T[] optionObjects = transform.GetComponentsInChildren<T>(true); int selectedIndex = 0; string[] options = new string[optionObjects.Length + 1]; options[0] = "(None)"; for (int i = 0; i < optionObjects.Length; i++) { if (showComponentName) { options[i + 1] = optionObjects[i].GetType().Name + " (" + optionObjects[i].name + ")"; } else { options[i + 1] = optionObjects[i].name; } if (obj == optionObjects[i]) { selectedIndex = i + 1; } } EditorGUILayout.BeginHorizontal(); int newIndex = EditorGUILayout.Popup(label, selectedIndex, options); if (newIndex == 0) { // Zero means '(None)' obj = null; } else { obj = optionObjects[newIndex - 1]; } //draw the object field so people can click it obj = (T)EditorGUILayout.ObjectField(obj, typeof(T), true); EditorGUILayout.EndHorizontal(); return obj; } /// <summary> /// Draws enum values as a set of toggle fields /// </summary> /// <typeparam name="T"></typeparam> /// <param name="label"></param> /// <param name="enumObj"></param> /// <returns></returns> public static int EnumCheckboxField<T>(string label, T enumObj) where T : struct, IConvertible { if (!typeof(T).IsEnum) { throw new ArgumentException("T must be an enum."); } return EnumCheckboxField<T>(label, enumObj, string.Empty, (T)Activator.CreateInstance(typeof(T))); } public static T SceneObjectField<T>(string label, T sceneObject) where T : Component { EditorGUILayout.BeginHorizontal(); if (string.IsNullOrEmpty(label)) { sceneObject = (T)EditorGUILayout.ObjectField(sceneObject, typeof(T), true); } else { sceneObject = (T)EditorGUILayout.ObjectField(label, sceneObject, typeof(T), true); } if (sceneObject != null && sceneObject.gameObject.scene.name == null) { // Don't allow objects that aren't in the scene! sceneObject = null; } T[] objectsInScene = GameObject.FindObjectsOfType<T>(); int selectedIndex = 0; string[] displayedOptions = new string[objectsInScene.Length + 1]; displayedOptions[0] = "(None)"; for (int i = 0; i < objectsInScene.Length; i++) { displayedOptions[i + 1] = objectsInScene[i].name; if (objectsInScene[i] == sceneObject) { selectedIndex = i + 1; } } selectedIndex = EditorGUILayout.Popup(selectedIndex, displayedOptions); if (selectedIndex == 0) { sceneObject = null; } else { sceneObject = objectsInScene[selectedIndex - 1]; } EditorGUILayout.EndHorizontal(); return sceneObject; } /// <summary> /// Draws enum values as a set of toggle fields /// Also draws a button the user can click to set to a 'default' value /// </summary> /// <typeparam name="T"></typeparam> /// <param name="label"></param> /// <param name="enumObj"></param> /// <param name="defaultName"></param> /// <param name="defaultVal"></param> /// <returns></returns> public static int EnumCheckboxField<T>(string label, T enumObj, string defaultName, T defaultVal, bool ignoreNone = true, bool ignoreAll = true) where T : struct, IConvertible { if (!typeof(T).IsEnum) { throw new ArgumentException("T must be an enum."); } // Convert enum value to an int64 so we can treat it as a flag set int enumFlags = Convert.ToInt32(enumObj); EditorGUILayout.BeginVertical(EditorStyles.helpBox); if (!string.IsNullOrEmpty(label)) { EditorGUILayout.LabelField(label, EditorStyles.miniLabel); DrawDivider(); } System.Array enumVals = Enum.GetValues(typeof(T)); int lastvalue = Convert.ToInt32((T)enumVals.GetValue(enumVals.GetLength(0) - 1)); foreach (T enumVal in enumVals) { int flagVal = Convert.ToInt32(enumVal); if (ignoreNone && flagVal == 0 && enumVal.ToString().ToLower() == "none") { continue; } if (ignoreAll && flagVal == lastvalue && enumVal.ToString().ToLower() == "all") { continue; } bool selected = (flagVal & enumFlags) != 0; selected = EditorGUILayout.Toggle(enumVal.ToString(), selected); // If it's selected add it to the enumObj, otherwise remove it if (selected) { enumFlags |= flagVal; } else { enumFlags &= ~flagVal; } } if (!string.IsNullOrEmpty(defaultName)) { if (GUILayout.Button(defaultName, EditorStyles.miniButton)) { enumFlags = Convert.ToInt32(defaultVal); } } EditorGUILayout.EndVertical(); return enumFlags; } public static int EnumCheckboxField<T>(string label, T enumObj, string defaultName, T defaultVal, T valOnZero, bool ignoreNone = true, bool ignoreAll = true) where T : struct, IConvertible { if (!typeof(T).IsEnum) { throw new ArgumentException("T must be an enum."); } // Convert enum value to an int64 so we can treat it as a flag set int enumFlags = Convert.ToInt32(enumObj); EditorGUILayout.BeginVertical(EditorStyles.helpBox); EditorGUILayout.LabelField(label, EditorStyles.miniLabel); DrawDivider(); System.Array enumVals = Enum.GetValues(typeof(T)); int lastvalue = Convert.ToInt32((T)enumVals.GetValue(enumVals.GetLength(0) - 1)); foreach (T enumVal in enumVals) { int flagVal = Convert.ToInt32(enumVal); if (ignoreNone && flagVal == 0 && enumVal.ToString().ToLower() == "none") { continue; } if (ignoreAll && flagVal == lastvalue && enumVal.ToString().ToLower() == "all") { continue; } bool selected = (flagVal & enumFlags) != 0; selected = EditorGUILayout.Toggle(enumVal.ToString(), selected); // If it's selected add it to the enumObj, otherwise remove it if (selected) { enumFlags |= flagVal; } else { enumFlags &= ~flagVal; } } if (!string.IsNullOrEmpty(defaultName)) { if (GUILayout.Button(defaultName, EditorStyles.miniButton)) { enumFlags = Convert.ToInt32(defaultVal); } } EditorGUILayout.EndVertical(); if (enumFlags == 0) { enumFlags = Convert.ToInt32(valOnZero); } return enumFlags; } public static string MaterialPropertyName(string property, Material mat, ShaderUtil.ShaderPropertyType type, bool allowNone = true, string defaultProperty = "_Color", string labelName = null) { Color tColor = GUI.color; // Create a list of available color and value properties List<string> props = new List<string>(); int selectedPropIndex = 0; if (allowNone) { props.Add("(None)"); } if (mat != null) { int propertyCount = ShaderUtil.GetPropertyCount(mat.shader); string propName = string.Empty; for (int i = 0; i < propertyCount; i++) { if (ShaderUtil.GetPropertyType(mat.shader, i) == type) { propName = ShaderUtil.GetPropertyName(mat.shader, i); if (propName == property) { // We've found our current property selectedPropIndex = props.Count; } props.Add(propName); } } GUI.color = string.IsNullOrEmpty(property) ? HUXEditorUtils.DisabledColor : HUXEditorUtils.DefaultColor; if (string.IsNullOrEmpty (labelName)) { labelName = type.ToString(); } int newPropIndex = EditorGUILayout.Popup(labelName, selectedPropIndex, props.ToArray()); if (allowNone) { property = (newPropIndex > 0 ? props[newPropIndex] : string.Empty); } else { if (props.Count > 0) { property = props[newPropIndex]; } else { property = defaultProperty; } } GUI.color = HUXEditorUtils.DefaultColor; return property; } else { WarningMessage("Can't get material " + type.ToString() + " properties because material is null."); GUI.color = HUXEditorUtils.DefaultColor; return string.Empty; } } public static void Header (string header) { GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel); headerStyle.fontSize = 18; EditorGUILayout.LabelField(header, headerStyle, GUILayout.MinHeight(24)); } public static void WarningMessage(string warning, string buttonMessage = null, Action buttonAction = null) { Color tColor = GUI.color; HUXEditorUtils.BeginSectionBox("Warning", HUXEditorUtils.WarningColor); EditorGUILayout.LabelField(warning, EditorStyles.wordWrappedLabel); if (!string.IsNullOrEmpty(buttonMessage) && buttonAction != null) { if (GUILayout.Button(buttonMessage)) { buttonAction.Invoke(); } } HUXEditorUtils.EndSectionBox(); GUI.color = tColor; } public static void ErrorMessage(string error, Action action = null, string fixMessage = null) { Color tColor = GUI.color; HUXEditorUtils.BeginSectionBox("Error", HUXEditorUtils.ErrorColor); EditorGUILayout.LabelField(error, EditorStyles.wordWrappedLabel); if (action != null && GUILayout.Button((fixMessage != null) ? fixMessage : "Fix now")) { action.Invoke(); } HUXEditorUtils.EndSectionBox(); GUI.color = tColor; } public static void BeginProfileBox() { GUI.color = HUXEditorUtils.WarningColor; EditorGUILayout.BeginVertical(EditorStyles.helpBox); DrawSubtleMiniLabel("Profile" + ":"); DrawSubtleMiniLabel("(Warning: this section edits the button profile. These changes will affect all buttons that use this profile.)"); } public static void EndProfileBox() { EndSectionBox(); } public static void BeginSectionBox(string label) { GUI.color = DefaultColor; /*GUIStyle boxStyle = new GUIStyle(EditorStyles.helpBox); boxStyle.normal.background = SectionBackground;*/ EditorGUILayout.BeginVertical(EditorStyles.helpBox); DrawSubtleMiniLabel(label + ":"); } public static void HelpBox(bool show, string text) { if (show) { GUI.color = ObjectColor; GUIStyle helpBoxStyle = new GUIStyle(EditorStyles.helpBox); helpBoxStyle.wordWrap = true; helpBoxStyle.fontSize = 9; helpBoxStyle.normal.background = HelpBoxBackground; EditorGUILayout.LabelField(text, helpBoxStyle); } GUI.color = DefaultColor; } public static bool BeginSectionBox(string label, ref bool foldout) { GUI.color = DefaultColor; /*GUIStyle boxStyle = new GUIStyle(EditorStyles.helpBox); boxStyle.normal.background = SectionBackground;*/ EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.Lerp(DefaultColor, Color.grey, 0.5f); ; //GUI.contentColor = DarkColor; GUIStyle foldoutStyle = new GUIStyle(EditorStyles.foldout); foldoutStyle.fontStyle = FontStyle.Normal; foldoutStyle.fontSize = 9; foldoutStyle.fontStyle = FontStyle.Normal; foldout = EditorGUILayout.Foldout(foldout, label + (foldout ? ":" : ""), true, foldoutStyle); GUI.color = DefaultColor; //GUI.contentColor = Color.white; return foldout; } public static void BeginSectionBox(string label, Color color) { GUI.color = color; /*GUIStyle boxStyle = new GUIStyle(EditorStyles.helpBox); boxStyle.normal.background = SectionBackground;*/ EditorGUILayout.BeginVertical(EditorStyles.helpBox); /*GUIStyle foldoutStyle = new GUIStyle(EditorStyles.wordWrappedLabel); foldoutStyle.fontStyle = FontStyle.Normal; foldoutStyle.fontSize = 12; foldoutStyle.fontStyle = FontStyle.Bold; EditorGUILayout.LabelField(label + ":", foldoutStyle);*/ DrawSubtleMiniLabel(label + ":"); } public static void EndSectionBox() { EditorGUILayout.EndVertical(); } public static void BeginSubSectionBox(string label, Color sectionColor) { GUI.color = sectionColor; GUIStyle boxStyle = new GUIStyle(EditorStyles.helpBox); boxStyle.normal.background = SectionBackground; EditorGUILayout.BeginVertical(boxStyle); EditorGUILayout.LabelField(label + ":", EditorStyles.boldLabel); } public static void BeginSubSectionBox(string label) { GUI.color = DefaultColor; GUIStyle boxStyle = new GUIStyle(EditorStyles.helpBox); boxStyle.normal.background = SectionBackground; EditorGUILayout.BeginVertical(boxStyle); EditorGUILayout.LabelField(label + ":", EditorStyles.boldLabel); } public static void EndSubSectionBox() { EditorGUILayout.EndVertical(); } public static void DrawSubtleMiniLabel(string label) { Color tColor = GUI.color; GUI.color = Color.Lerp(tColor, Color.grey, 0.5f); EditorGUILayout.LabelField(label, EditorStyles.wordWrappedMiniLabel); GUI.color = tColor; } public static void DrawDivider() { GUIStyle styleHR = new GUIStyle(GUI.skin.box); styleHR.stretchWidth = true; styleHR.fixedHeight = 2; GUILayout.Box("", styleHR); } public static void SaveChanges(UnityEngine.Object target) { if (Application.isPlaying) return; if (GUI.changed) { EditorUtility.SetDirty(target); UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene()); } } public static void SaveChanges(UnityEngine.Object target1, UnityEngine.Object target2) { if (Application.isPlaying) return; if (GUI.changed) { EditorUtility.SetDirty(target1); EditorUtility.SetDirty(target2); UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene()); } } public static string[] getMethodOptions(GameObject comp, List<System.Type> ignoreTypes = null) { List<string> methods = new List<string>(); if (comp != null) { Component[] allComponents = comp.GetComponents<Component>(); List<System.Type> doneTypes = new List<System.Type>(); for (int index = 0; index < allComponents.Length; index++) { System.Type compType = allComponents[index].GetType(); if (!doneTypes.Contains(compType) && (ignoreTypes == null || !ignoreTypes.Contains(compType))) { MethodInfo[] allMemebers = compType.GetMethods(); for (int memberIndex = 0; memberIndex < allMemebers.Length; memberIndex++) { if (allMemebers[memberIndex].IsPublic && allMemebers[memberIndex].GetParameters().Length == 0 && !methods.Contains(allMemebers[memberIndex].Name) && allMemebers[memberIndex].ReturnType == typeof(void)) { methods.Add(allMemebers[memberIndex].Name); } } doneTypes.Add(compType); } } } return methods.ToArray(); } /// <summary> /// Adds a prefab to the scene. /// </summary> /// <param name="prefabPath"></param> /// <param name="ignoreAlreadyInScene">If false the prefab will not be added if it exists in the hierarchy.</param> /// <returns>A refernce to the newly created prefab instance or one that exists in the scene if ignoreAlreadyInScene is false.</returns> public static GameObject AddToScene(string prefabPath, bool ignoreAlreadyInScene = true) { GameObject prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject; GameObject instance = null; if (prefab != null) { instance = FindFirstPrefabInstance(prefab); if (instance == null || ignoreAlreadyInScene) { instance = PrefabUtility.InstantiatePrefab(prefab) as GameObject; } else { Debug.LogWarning("Instance already exits in the scene: " + prefabPath); } } else { Debug.LogError("Could not load prefab: " + prefabPath); } return instance; } /// <summary> /// Finds the first instance of a preface in the Hierarchy. /// </summary> /// <param name="prefab"></param> /// <returns>First instance of the prefab or null if one is not found.</returns> public static GameObject FindFirstPrefabInstance(GameObject prefab) { GameObject result = null; GameObject[] allObjects = (GameObject[])GameObject.FindObjectsOfType(typeof(GameObject)); foreach (GameObject obj in allObjects) { PrefabType type = PrefabUtility.GetPrefabType(obj); if (type == PrefabType.PrefabInstance) { UnityEngine.Object GO_prefab = PrefabUtility.GetPrefabParent(obj); if (prefab == GO_prefab) { result = obj; break; } } } return result; } public static void CorrectAmbientLightingInScene() { RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat; RenderSettings.ambientIntensity = 1.0f; // Normalize and set ambient light to default. Vector4 c = new Vector4(51.0f, 51.0f, 51.0f, 255.0f); c.Normalize(); RenderSettings.ambientLight = new Color(c.x, c.y, c.z, c.w); RenderSettings.reflectionBounces = 1; RenderSettings.reflectionIntensity = 1.0f; RenderSettings.skybox = null; RenderSettings.fog = false; } private static List<Type> GetDerivedTypes(Type baseType, Assembly assembly) { Type[] types = assembly.GetTypes(); List<Type> derivedTypes = new List<Type>(); for (int i = 0, count = types.Length; i < count; i++) { Type type = types[i]; if (IsSubclassOf(type, baseType)) { derivedTypes.Add(type); } } return derivedTypes; } private static bool IsSubclassOf(Type type, Type baseType) { if (type == null || baseType == null || type == baseType) return false; if (baseType.IsGenericType == false) { if (type.IsGenericType == false) return type.IsSubclassOf(baseType); } else { baseType = baseType.GetGenericTypeDefinition(); } type = type.BaseType; Type objectType = typeof(object); while (type != objectType && type != null) { Type curentType = type.IsGenericType ? type.GetGenericTypeDefinition() : type; if (curentType == baseType) return true; type = type.BaseType; } return false; } private static Texture2D SectionBackground { get { if (sectionBackground == null) { sectionBackground = new Texture2D(2, 2); var pix = new Color[2 * 2]; for (int i = 0; i < pix.Length; i++) { pix[i] = SectionColor; } sectionBackground.SetPixels(pix); sectionBackground.Apply(); } return sectionBackground; } } private static Texture2D HelpBoxBackground { get { if (helpBoxBackground == null) { helpBoxBackground = new Texture2D(2, 2); var pix = new Color[2 * 2]; for (int i = 0; i < pix.Length; i++) { pix[i] = HelpBoxColor; } helpBoxBackground.SetPixels(pix); helpBoxBackground.Apply(); } return helpBoxBackground; } } private static Texture2D helpBoxBackground = null; private static Texture2D sectionBackground = null; } }
elbruno/Blog
20170807 Holo MRDesignLab Move Resize Holograms/Assets/HUX/Editor/Utility/HUXEditorUtils.cs
C#
gpl-2.0
29,118
/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "DFGExitProfile.h" #if ENABLE(DFG_JIT) #include <wtf/PassOwnPtr.h> namespace JSC { namespace DFG { ExitProfile::ExitProfile() { } ExitProfile::~ExitProfile() { } bool ExitProfile::add(const ConcurrentJITLocker&, const FrequentExitSite& site) { ASSERT(site.jitType() != ExitFromAnything); // If we've never seen any frequent exits then create the list and put this site // into it. if (!m_frequentExitSites) { m_frequentExitSites = adoptPtr(new Vector<FrequentExitSite>()); m_frequentExitSites->append(site); return true; } // Don't add it if it's already there. This is O(n), but that's OK, because we // know that the total number of places where code exits tends to not be large, // and this code is only used when recompilation is triggered. for (unsigned i = 0; i < m_frequentExitSites->size(); ++i) { if (m_frequentExitSites->at(i) == site) return false; } m_frequentExitSites->append(site); return true; } Vector<FrequentExitSite> ExitProfile::exitSitesFor(unsigned bytecodeIndex) { Vector<FrequentExitSite> result; if (!m_frequentExitSites) return result; for (unsigned i = 0; i < m_frequentExitSites->size(); ++i) { if (m_frequentExitSites->at(i).bytecodeOffset() == bytecodeIndex) result.append(m_frequentExitSites->at(i)); } return result; } bool ExitProfile::hasExitSite(const ConcurrentJITLocker&, const FrequentExitSite& site) const { if (!m_frequentExitSites) return false; for (unsigned i = m_frequentExitSites->size(); i--;) { if (site.subsumes(m_frequentExitSites->at(i))) return true; } return false; } QueryableExitProfile::QueryableExitProfile() { } QueryableExitProfile::~QueryableExitProfile() { } void QueryableExitProfile::initialize(const ConcurrentJITLocker&, const ExitProfile& profile) { if (!profile.m_frequentExitSites) return; for (unsigned i = 0; i < profile.m_frequentExitSites->size(); ++i) m_frequentExitSites.add(profile.m_frequentExitSites->at(i)); } } } // namespace JSC::DFG #endif
loveyoupeng/rt
modules/web/src/main/native/Source/JavaScriptCore/bytecode/DFGExitProfile.cpp
C++
gpl-2.0
3,542
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.eform.actions; import java.io.File; import java.util.ArrayList; import javax.activation.MimetypesFileTypeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DownloadAction; import org.oscarehr.util.MiscUtils; import oscar.OscarProperties; /** * eform_image * @author jay *and Paul */ public class DisplayImageAction extends DownloadAction{ /** Creates a new instance of DisplayImageAction */ public DisplayImageAction() { } protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("imagefile"); //if (fileName.indexOf('/') != -1) return null; //prevents navigating away from the page. String home_dir = OscarProperties.getInstance().getProperty("eform_image"); response.setHeader("Content-disposition","inline; filename=" + fileName); File file = null; try{ File directory = new File(home_dir); if(!directory.exists()){ throw new Exception("Directory: "+home_dir+ " does not exist"); } file = new File(directory,fileName); //String canonicalPath = file.getParentFile().getCanonicalPath(); //absolute path of the retrieved file if (!directory.equals(file.getParentFile())) { MiscUtils.getLogger().debug("SECURITY WARNING: Illegal file path detected, client attempted to navigate away from the file directory"); throw new Exception("Could not open file " + fileName + ". Check the file path"); } }catch(Exception e){ MiscUtils.getLogger().error("Error", e); throw new Exception("Could not open file "+home_dir+fileName +" does "+home_dir+ " exist ?",e); } //gets content type from image extension String contentType = new MimetypesFileTypeMap().getContentType(file); /** * For encoding file types not included in the mimetypes file * You need to look at mimetypes file to check if the file type you are using is included * */ try{ if(extension(file.getName()).equalsIgnoreCase("png")){ // for PNG contentType = "image/png"; }else if(extension(file.getName()).equalsIgnoreCase("jpeg")|| extension(file.getName()).equalsIgnoreCase("jpe")|| extension(file.getName()).equalsIgnoreCase("jpg")){ //for JPEG,JPG,JPE contentType = "image/jpeg"; }else if(extension(file.getName()).equalsIgnoreCase("bmp")){ // for BMP contentType = "image/bmp"; }else if(extension(file.getName()).equalsIgnoreCase("cod")){ // for COD contentType = "image/cis-cod"; }else if(extension(file.getName()).equalsIgnoreCase("ief")){ // for IEF contentType = "image/ief"; }else if(extension(file.getName()).equalsIgnoreCase("jfif")){ // for JFIF contentType = "image/pipeg"; }else if(extension(file.getName()).equalsIgnoreCase("svg")){ // for SVG contentType = "image/svg+xml"; }else if(extension(file.getName()).equalsIgnoreCase("tiff")|| extension(file.getName()).equalsIgnoreCase("tif")){ // for TIFF or TIF contentType = "image/tiff"; }else if(extension(file.getName()).equalsIgnoreCase("pbm")){ // for PBM contentType = "image/x-portable-bitmap"; }else if(extension(file.getName()).equalsIgnoreCase("pnm")){ // for PNM contentType = "image/x-portable-anymap"; }else if(extension(file.getName()).equalsIgnoreCase("pgm")){ // for PGM contentType = "image/x-portable-greymap"; }else if(extension(file.getName()).equalsIgnoreCase("ppm")){ // for PPM contentType = "image/x-portable-pixmap"; }else if(extension(file.getName()).equalsIgnoreCase("xbm")){ // for XBM contentType = "image/x-xbitmap"; }else if(extension(file.getName()).equalsIgnoreCase("xpm")){ // for XPM contentType = "image/x-xpixmap"; }else if(extension(file.getName()).equalsIgnoreCase("xwd")){ // for XWD contentType = "image/x-xwindowdump"; }else if(extension(file.getName()).equalsIgnoreCase("rgb")){ // for RGB contentType = "image/x-rgb"; }else if(extension(file.getName()).equalsIgnoreCase("ico")){ // for ICO contentType = "image/x-icon"; }else if(extension(file.getName()).equalsIgnoreCase("cmx")){ // for CMX contentType = "image/x-cmx"; }else if(extension(file.getName()).equalsIgnoreCase("ras")){ // for RAS contentType = "image/x-cmu-raster"; }else if(extension(file.getName()).equalsIgnoreCase("gif")){ // for GIF contentType = "image/gif"; }else if(extension(file.getName()).equalsIgnoreCase("js")){ // for GIF contentType = "text/javascript"; }else if(extension(file.getName()).equalsIgnoreCase("css")){ // for GIF contentType = "text/css"; }else if(extension(file.getName()).equalsIgnoreCase("rtl") || extension(file.getName()).equalsIgnoreCase("html") || extension(file.getName()).equalsIgnoreCase("htm")){ // for HTML contentType = "text/html"; }else{ throw new Exception("please check the file type or update mimetypes.default file to include the "+"."+extension(file.getName())); } }catch(Exception e){MiscUtils.getLogger().error("Error", e); throw new Exception("Could not open file "+file.getName()+" wrong file extension, ",e); } return new FileStreamInfo(contentType, file); } /** * * @String <filename e.g example.jpeg> * This method used to get file extension from a given filename * @return String <file extension> * */ public String extension(String f) { int dot = f.lastIndexOf("."); return f.substring(dot + 1); } public static File getImageFile(String imageFileName) throws Exception { String home_dir = OscarProperties.getInstance().getProperty("eform_image"); File file = null; try{ File directory = new File(home_dir); if(!directory.exists()){ throw new Exception("Directory: "+home_dir+ " does not exist"); } file = new File(directory,imageFileName); //String canonicalPath = file.getParentFile().getCanonicalPath(); //absolute path of the retrieved file if (!directory.equals(file.getParentFile())) { MiscUtils.getLogger().debug("SECURITY WARNING: Illegal file path detected, client attempted to navigate away from the file directory"); throw new Exception("Could not open file " + imageFileName + ". Check the file path"); } return file; }catch(Exception e){ MiscUtils.getLogger().error("Error", e); throw new Exception("Could not open file "+home_dir+imageFileName +" does "+home_dir+ " exist ?",e); } } /** * * Process only files under dir * This method used to list images for eform generator * */ public String[] visitAllFiles(File dir) { String[] children=null; if (dir.isDirectory()) { children = dir.list(); for (int i=0; i<children.length; i++) { visitAllFiles(new File(dir, children[i])); } } return children; } public static String[] getRichTextLetterTemplates(File dir) { ArrayList<String> results = getFiles(dir, ".*(rtl)$", null); return results.toArray(new String[0]); } public static ArrayList<String> getFiles(File dir, String ext, ArrayList<String> files) { if (files == null) { files = new ArrayList<String>(); } if (dir.isDirectory()) { for (String fileName : dir.list()) { if (fileName.toLowerCase().matches(ext)) { files.add(fileName); } } } return files; } }
vvanherk/oscar_emr
src/main/java/oscar/eform/actions/DisplayImageAction.java
Java
gpl-2.0
9,846
<?php /** * Sample implementation of the Custom Header feature * http://codex.wordpress.org/Custom_Headers * * You can add an optional custom header image to header.php like so ... <?php $header_image = get_header_image(); if ( ! empty( $header_image ) ) { ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"> <img src="<?php header_image(); ?>" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /> </a> <?php } // if ( ! empty( $header_image ) ) ?> * * @package wpjobboard_theme */ /** * Setup the WordPress core custom header feature. * * Use add_theme_support to register support for WordPress 3.4+ * as well as provide backward compatibility for previous versions. * Use feature detection of wp_get_theme() which was introduced * in WordPress 3.4. * * @todo Rework this function to remove WordPress 3.4 support when WordPress 3.6 is released. * * @uses wpjobboard_theme_header_style() * @uses wpjobboard_theme_admin_header_style() * @uses wpjobboard_theme_admin_header_image() * * @package wpjobboard_theme */ function wpjobboard_theme_custom_header_setup() { $args = array( 'default-image' => '', 'default-text-color' => '000', 'width' => 1000, 'height' => 250, 'flex-height' => true, 'wp-head-callback' => 'wpjobboard_theme_header_style', 'admin-head-callback' => 'wpjobboard_theme_admin_header_style', 'admin-preview-callback' => 'wpjobboard_theme_admin_header_image', ); $args = apply_filters('wpjobboard_theme_custom_header_args', $args); if (function_exists('wp_get_theme')) { add_theme_support('custom-header', $args); } else { // Compat: Versions of WordPress prior to 3.4. define('HEADER_TEXTCOLOR', $args['default-text-color']); define('HEADER_IMAGE', $args['default-image']); define('HEADER_IMAGE_WIDTH', $args['width']); define('HEADER_IMAGE_HEIGHT', $args['height']); add_custom_image_header($args['wp-head-callback'], $args['admin-head-callback'], $args['admin-preview-callback']); } } add_action('after_setup_theme', 'wpjobboard_theme_custom_header_setup'); /** * Shiv for get_custom_header(). * * get_custom_header() was introduced to WordPress * in version 3.4. To provide backward compatibility * with previous versions, we will define our own version * of this function. * * @todo Remove this function when WordPress 3.6 is released. * @return stdClass All properties represent attributes of the curent header image. * * @package wpjobboard_theme */ if (!function_exists('get_custom_header')) { function get_custom_header() { return (object) array( 'url' => get_header_image(), 'thumbnail_url' => get_header_image(), 'width' => HEADER_IMAGE_WIDTH, 'height' => HEADER_IMAGE_HEIGHT, ); } } if (!function_exists('wpjobboard_theme_header_style')) : /** * Styles the header image and text displayed on the blog * * @see wpjobboard_theme_custom_header_setup(). */ function wpjobboard_theme_header_style() { // If no custom options for text are set, let's bail // get_header_textcolor() options: HEADER_TEXTCOLOR is default, hide text (returns 'blank') or any hex value if (HEADER_TEXTCOLOR == get_header_textcolor()) return; // If we get this far, we have custom styles. Let's do this. ?> <style type="text/css"> <?php // Has the text been hidden? if ('blank' == get_header_textcolor()) : ?> .site-title, .site-description { position: absolute !important; clip: rect(1px 1px 1px 1px); /* IE6, IE7 */ clip: rect(1px, 1px, 1px, 1px); } <?php // If the user has set a custom color for the text use that else : ?> .site-title a, .site-description { color: #<?php echo get_header_textcolor(); ?>; } <?php endif; ?> </style> <?php } endif; // wpjobboard_theme_header_style if (!function_exists('wpjobboard_theme_admin_header_style')) : /** * Styles the header image displayed on the Appearance > Header admin panel. * * @see wpjobboard_theme_custom_header_setup(). */ function wpjobboard_theme_admin_header_style() { ?> <style type="text/css"> .appearance_page_custom-header #headimg { border: none; } #headimg h1, #desc { } #headimg h1 { } #headimg h1 a { } #desc { } #headimg img { } </style> <?php } endif; // wpjobboard_theme_admin_header_style if (!function_exists('wpjobboard_theme_admin_header_image')) : /** * Custom header image markup displayed on the Appearance > Header admin panel. * * @see wpjobboard_theme_custom_header_setup(). */ function wpjobboard_theme_admin_header_image() { ?> <div id="headimg"> <?php if ('blank' == get_header_textcolor() || '' == get_header_textcolor()) $style = ' style="display:none;"'; else $style = ' style="color:#' . get_header_textcolor() . ';"'; ?> <h1 class="displaying-header-text"><a id="name"<?php echo $style; ?> onclick="return false;" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a></h1> <div class="displaying-header-text" id="desc"<?php echo $style; ?>><?php bloginfo('description'); ?></div> <?php $header_image = get_header_image(); if (!empty($header_image)) : ?> <img src="<?php echo esc_url($header_image); ?>" alt="" /> <?php endif; ?> </div> <?php } endif; // wpjobboard_theme_admin_header_image
ashchat404/wordpress
wp-content/themes/tsf/inc/custom-header.php
PHP
gpl-2.0
6,290
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Functionality for the navigation tree * * @package PhpMyAdmin-Navigation */ if (! defined('PHPMYADMIN')) { exit; } require_once 'libraries/navigation/Nodes/Node_DatabaseChild.class.php'; /** * Represents a view node in the navigation tree * * @package PhpMyAdmin-Navigation */ class Node_View extends Node_DatabaseChild { /** * Initialises the class * * @param string $name An identifier for the new node * @param int $type Type of node, may be one of CONTAINER or OBJECT * @param bool $is_group Whether this object has been created * while grouping nodes * * @return Node_View */ public function __construct($name, $type = Node::OBJECT, $is_group = false) { parent::__construct($name, $type, $is_group); $this->icon = PMA_Util::getImage('b_props.png', __('View')); $this->links = array( 'text' => 'sql.php?server=' . $GLOBALS['server'] . '&amp;db=%2$s&amp;table=%1$s&amp;pos=0' . '&amp;token=' . $_SESSION[' PMA_token '], 'icon' => 'tbl_structure.php?server=' . $GLOBALS['server'] . '&amp;db=%2$s&amp;table=%1$s' . '&amp;token=' . $_SESSION[' PMA_token '] ); $this->classes = 'view'; } /** * Returns the type of the item represented by the node. * * @return string type of the item */ protected function getItemType() { return 'view'; } }
saisai/phpmyadmin
libraries/navigation/Nodes/Node_View.class.php
PHP
gpl-2.0
1,597
/* * Digital Media Server, for streaming digital media to UPnP AV or DLNA * compatible devices based on PS3 Media Server and Universal Media Server. * Copyright (C) 2016 Digital Media Server developers. * * 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 net.pms.formats.audio; public class MPC extends AudioBase { @Override public Identifier getIdentifier() { return Identifier.MPC; } @Override public String[] getSupportedExtensions() { return new String[] { "mpc", "mp+", "mpp", }; } }
DigitalMediaServer/DigitalMediaServer
src/main/java/net/pms/formats/audio/MPC.java
Java
gpl-2.0
1,121
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ require_once(MAX_PATH.'/lib/OA/Upgrade/Migration.php'); class Migration_542 extends Migration { function Migration_542() { //$this->__construct(); $this->aTaskList_constructive[] = 'beforeAddField__campaigns__as_reject_reason'; $this->aTaskList_constructive[] = 'afterAddField__campaigns__as_reject_reason'; $this->aObjectMap['campaigns']['as_reject_reason'] = array('fromTable'=>'campaigns', 'fromField'=>'as_reject_reason'); } function beforeAddField__campaigns__as_reject_reason() { return $this->beforeAddField('campaigns', 'as_reject_reason'); } function afterAddField__campaigns__as_reject_reason() { return $this->afterAddField('campaigns', 'as_reject_reason'); } } ?>
adqio/revive-adserver
etc/changes/migration_tables_core_542.php
PHP
gpl-2.0
1,282
<?php namespace Elgg\I18n; /** * WARNING: API IN FLUX. DO NOT USE DIRECTLY. * * @access private * * @since 1.10.0 */ class Translator { /** * Global Elgg configuration * * @var \stdClass */ private $CONFIG; /** * Initializes new translator */ public function __construct() { global $CONFIG; $this->CONFIG = $CONFIG; $this->defaultPath = dirname(dirname(dirname(dirname(__DIR__)))) . "/languages/"; } /** * Given a message key, returns an appropriately translated full-text string * * @param string $message_key The short message code * @param array $args An array of arguments to pass through vsprintf(). * @param string $language Optionally, the standard language code * (defaults to site/user default, then English) * * @return string Either the translated string, the English string, * or the original language string. */ function translate($message_key, $args = array(), $language = "") { static $CURRENT_LANGUAGE; // old param order is deprecated if (!is_array($args)) { elgg_deprecated_notice( 'As of Elgg 1.8, the 2nd arg to elgg_echo() is an array of string replacements and the 3rd arg is the language.', 1.8 ); $language = $args; $args = array(); } if (!isset($GLOBALS['_ELGG']->translations)) { // this means we probably had an exception before translations were initialized $this->registerTranslations($this->defaultPath); } if (!$CURRENT_LANGUAGE) { $CURRENT_LANGUAGE = $this->getLanguage(); } if (!$language) { $language = $CURRENT_LANGUAGE; } if (!isset($GLOBALS['_ELGG']->translations[$language])) { // The language being requested is not the same as the language of the // logged in user, so we will have to load it separately. (Most likely // we're sending a notification and the recipient is using a different // language than the logged in user.) _elgg_load_translations_for_language($language); } if (isset($GLOBALS['_ELGG']->translations[$language][$message_key])) { $string = $GLOBALS['_ELGG']->translations[$language][$message_key]; } else if (isset($GLOBALS['_ELGG']->translations["en"][$message_key])) { $string = $GLOBALS['_ELGG']->translations["en"][$message_key]; _elgg_services()->logger->notice(sprintf('Missing %s translation for "%s" language key', $language, $message_key)); } else { $string = $message_key; _elgg_services()->logger->notice(sprintf('Missing English translation for "%s" language key', $message_key)); } // only pass through if we have arguments to allow backward compatibility // with manual sprintf() calls. if ($args) { $string = vsprintf($string, $args); } return $string; } /** * Add a translation. * * Translations are arrays in the Zend Translation array format, eg: * * $english = array('message1' => 'message1', 'message2' => 'message2'); * $german = array('message1' => 'Nachricht1','message2' => 'Nachricht2'); * * @param string $country_code Standard country code (eg 'en', 'nl', 'es') * @param array $language_array Formatted array of strings * * @return bool Depending on success */ function addTranslation($country_code, $language_array) { if (!isset($GLOBALS['_ELGG']->translations)) { $GLOBALS['_ELGG']->translations = array(); } $country_code = strtolower($country_code); $country_code = trim($country_code); if (is_array($language_array) && $country_code != "") { if (sizeof($language_array) > 0) { if (!isset($GLOBALS['_ELGG']->translations[$country_code])) { $GLOBALS['_ELGG']->translations[$country_code] = $language_array; } else { $GLOBALS['_ELGG']->translations[$country_code] = $language_array + $GLOBALS['_ELGG']->translations[$country_code]; } } return true; } return false; } /** * Detect the current language being used by the current site or logged in user. * * @return string The language code for the site/user or "en" if not set */ function getCurrentLanguage() { $language = $this->getLanguage(); if (!$language) { $language = 'en'; } return $language; } /** * Gets the current language in use by the system or user. * * @return string The language code (eg "en") or false if not set */ function getLanguage() { $url_lang = _elgg_services()->input->get('hl'); if ($url_lang) { return $url_lang; } $user = _elgg_services()->session->getLoggedInUser(); $language = false; if (($user) && ($user->language)) { $language = $user->language; } if ((!$language) && (isset($this->CONFIG->language)) && ($this->CONFIG->language)) { $language = $this->CONFIG->language; } if ($language) { return $language; } return false; } /** * @access private */ function loadTranslations() { if ($this->CONFIG->system_cache_enabled) { $loaded = true; $languages = array_unique(array('en', $this->getCurrentLanguage())); foreach ($languages as $language) { $data = elgg_load_system_cache("$language.lang"); if ($data) { $this->addTranslation($language, unserialize($data)); } else { $loaded = false; } } if ($loaded) { $GLOBALS['_ELGG']->i18n_loaded_from_cache = true; // this is here to force $GLOBALS['_ELGG']->language_paths[$this->defaultPath] = true; return; } } // load core translations from languages directory $this->registerTranslations($this->defaultPath); } /** * Registers translations in a directory assuming the standard plugin layout. * * @param string $path Without the trailing slash. * * @return bool Success */ function registerPluginTranslations($path) { $languages_path = rtrim($path, "\\/") . "/languages"; // don't need to have translations if (!is_dir($languages_path)) { return true; } return $this->registerTranslations($languages_path); } /** * When given a full path, finds translation files and loads them * * @param string $path Full path * @param bool $load_all If true all languages are loaded, if * false only the current language + en are loaded * * @return bool success */ function registerTranslations($path, $load_all = false) { $path = sanitise_filepath($path); // Make a note of this path just incase we need to register this language later if (!isset($GLOBALS['_ELGG']->language_paths)) { $GLOBALS['_ELGG']->language_paths = array(); } $GLOBALS['_ELGG']->language_paths[$path] = true; // Get the current language based on site defaults and user preference $current_language = $this->getCurrentLanguage(); _elgg_services()->logger->info("Translations loaded from: $path"); // only load these files unless $load_all is true. $load_language_files = array( 'en.php', "$current_language.php" ); $load_language_files = array_unique($load_language_files); $handle = opendir($path); if (!$handle) { _elgg_services()->logger->error("Could not open language path: $path"); return false; } $return = true; while (false !== ($language = readdir($handle))) { // ignore bad files if (substr($language, 0, 1) == '.' || substr($language, -4) !== '.php') { continue; } if (in_array($language, $load_language_files) || $load_all) { $result = include_once($path . $language); if ($result === false) { $return = false; continue; } elseif (is_array($result)) { $this->addTranslation(basename($language, '.php'), $result); } } } return $return; } /** * Reload all translations from all registered paths. * * This is only called by functions which need to know all possible translations. * * @todo Better on demand loading based on language_paths array * * @return void */ function reloadAllTranslations() { static $LANG_RELOAD_ALL_RUN; if ($LANG_RELOAD_ALL_RUN) { return; } if ($GLOBALS['_ELGG']->i18n_loaded_from_cache) { $cache = elgg_get_system_cache(); $cache_dir = $cache->getVariable("cache_path"); $filenames = elgg_get_file_list($cache_dir, array(), array(), array(".lang")); foreach ($filenames as $filename) { // Look for files matching for example 'en.lang', 'cmn.lang' or 'pt_br.lang'. // Note that this regex is just for the system cache. The original language // files are allowed to have uppercase letters (e.g. pt_BR.php). if (preg_match('/(([a-z]{2,3})(_[a-z]{2})?)\.lang$/', $filename, $matches)) { $language = $matches[1]; $data = elgg_load_system_cache("$language.lang"); if ($data) { $this->addTranslation($language, unserialize($data)); } } } } else { foreach ($GLOBALS['_ELGG']->language_paths as $path => $dummy) { $this->registerTranslations($path, true); } } $LANG_RELOAD_ALL_RUN = true; } /** * Return an array of installed translations as an associative * array "two letter code" => "native language name". * * @return array */ function getInstalledTranslations() { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); $installed = array(); $admin_logged_in = _elgg_services()->session->isAdminLoggedIn(); foreach ($GLOBALS['_ELGG']->translations as $k => $v) { $installed[$k] = $this->translate($k, array(), $k); if ($admin_logged_in && ($k != 'en')) { $completeness = $this->getLanguageCompleteness($k); if ($completeness < 100) { $installed[$k] .= " (" . $completeness . "% " . $this->translate('complete') . ")"; } } } return $installed; } /** * Return the level of completeness for a given language code (compared to english) * * @param string $language Language * * @return int */ function getLanguageCompleteness($language) { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); $language = sanitise_string($language); $en = count($GLOBALS['_ELGG']->translations['en']); $missing = $this->getMissingLanguageKeys($language); if ($missing) { $missing = count($missing); } else { $missing = 0; } //$lang = count($GLOBALS['_ELGG']->translations[$language]); $lang = $en - $missing; return round(($lang / $en) * 100, 2); } /** * Return the translation keys missing from a given language, * or those that are identical to the english version. * * @param string $language The language * * @return mixed */ function getMissingLanguageKeys($language) { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); $missing = array(); foreach ($GLOBALS['_ELGG']->translations['en'] as $k => $v) { if ((!isset($GLOBALS['_ELGG']->translations[$language][$k])) || ($GLOBALS['_ELGG']->translations[$language][$k] == $GLOBALS['_ELGG']->translations['en'][$k])) { $missing[] = $k; } } if (count($missing)) { return $missing; } return false; } /** * Check if a give language key exists * * @param string $key The translation key * @param string $language The specific language to check * * @return bool * @since 1.11 */ function languageKeyExists($key, $language = 'en') { if (empty($key)) { return false; } if (($language !== 'en') && !array_key_exists($language, $GLOBALS['_ELGG']->translations)) { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); } if (!array_key_exists($language, $GLOBALS['_ELGG']->translations)) { return false; } return array_key_exists($key, $GLOBALS['_ELGG']->translations[$language]); } /** * Returns an array of language codes. * * @return array */ function getAllLanguageCodes() { return array( "aa", // "Afar" "ab", // "Abkhazian" "af", // "Afrikaans" "am", // "Amharic" "ar", // "Arabic" "as", // "Assamese" "ay", // "Aymara" "az", // "Azerbaijani" "ba", // "Bashkir" "be", // "Byelorussian" "bg", // "Bulgarian" "bh", // "Bihari" "bi", // "Bislama" "bn", // "Bengali; Bangla" "bo", // "Tibetan" "br", // "Breton" "ca", // "Catalan" "cmn", // "Mandarin Chinese" // ISO 639-3 "co", // "Corsican" "cs", // "Czech" "cy", // "Welsh" "da", // "Danish" "de", // "German" "dz", // "Bhutani" "el", // "Greek" "en", // "English" "eo", // "Esperanto" "es", // "Spanish" "et", // "Estonian" "eu", // "Basque" "fa", // "Persian" "fi", // "Finnish" "fj", // "Fiji" "fo", // "Faeroese" "fr", // "French" "fy", // "Frisian" "ga", // "Irish" "gd", // "Scots / Gaelic" "gl", // "Galician" "gn", // "Guarani" "gu", // "Gujarati" "he", // "Hebrew" "ha", // "Hausa" "hi", // "Hindi" "hr", // "Croatian" "hu", // "Hungarian" "hy", // "Armenian" "ia", // "Interlingua" "id", // "Indonesian" "ie", // "Interlingue" "ik", // "Inupiak" "is", // "Icelandic" "it", // "Italian" "iu", // "Inuktitut" "iw", // "Hebrew (obsolete)" "ja", // "Japanese" "ji", // "Yiddish (obsolete)" "jw", // "Javanese" "ka", // "Georgian" "kk", // "Kazakh" "kl", // "Greenlandic" "km", // "Cambodian" "kn", // "Kannada" "ko", // "Korean" "ks", // "Kashmiri" "ku", // "Kurdish" "ky", // "Kirghiz" "la", // "Latin" "ln", // "Lingala" "lo", // "Laothian" "lt", // "Lithuanian" "lv", // "Latvian/Lettish" "mg", // "Malagasy" "mi", // "Maori" "mk", // "Macedonian" "ml", // "Malayalam" "mn", // "Mongolian" "mo", // "Moldavian" "mr", // "Marathi" "ms", // "Malay" "mt", // "Maltese" "my", // "Burmese" "na", // "Nauru" "ne", // "Nepali" "nl", // "Dutch" "no", // "Norwegian" "oc", // "Occitan" "om", // "(Afan) Oromo" "or", // "Oriya" "pa", // "Punjabi" "pl", // "Polish" "ps", // "Pashto / Pushto" "pt", // "Portuguese" "pt_br", // 'Brazilian Portuguese' "qu", // "Quechua" "rm", // "Rhaeto-Romance" "rn", // "Kirundi" "ro", // "Romanian" "ru", // "Russian" "rw", // "Kinyarwanda" "sa", // "Sanskrit" "sd", // "Sindhi" "sg", // "Sangro" "sh", // "Serbo-Croatian" "si", // "Singhalese" "sk", // "Slovak" "sl", // "Slovenian" "sm", // "Samoan" "sn", // "Shona" "so", // "Somali" "sq", // "Albanian" "sr", // "Serbian" "ss", // "Siswati" "st", // "Sesotho" "su", // "Sundanese" "sv", // "Swedish" "sw", // "Swahili" "ta", // "Tamil" "te", // "Tegulu" "tg", // "Tajik" "th", // "Thai" "ti", // "Tigrinya" "tk", // "Turkmen" "tl", // "Tagalog" "tn", // "Setswana" "to", // "Tonga" "tr", // "Turkish" "ts", // "Tsonga" "tt", // "Tatar" "tw", // "Twi" "ug", // "Uigur" "uk", // "Ukrainian" "ur", // "Urdu" "uz", // "Uzbek" "vi", // "Vietnamese" "vo", // "Volapuk" "wo", // "Wolof" "xh", // "Xhosa" "yi", // "Yiddish" "yo", // "Yoruba" "za", // "Zuang" "zh", // "Chinese" "zu", // "Zulu" ); } }
printerpam/Elgg
engine/classes/Elgg/I18n/Translator.php
PHP
gpl-2.0
15,087
<?php /** * This file is part of http://github.com/LukeBeer/BroadworksOCIP * * (c) 2013-2015 Luke Berezynskyj <eat.lemons@gmail.com> */ namespace BroadworksOCIP\api\Rel_17_sp4_1_197_OCISchemaAS\OCISchemaDataTypes; use BroadworksOCIP\Builder\Types\SimpleType; use BroadworksOCIP\Builder\Restrictions\Enumeration; /** * Choices for extended file resource usage. */ class ExtendedFileResourceSelection extends SimpleType { public $elementName = "ExtendedFileResourceSelection"; public function __construct($value) { $this->setElementValue($value); $this->addRestriction(new Enumeration([ 'File', 'URL', 'Default' ])); } }
paericksen/broadworks-ocip
src/BroadworksOCIP/api/Rel_17_sp4_1_197_OCISchemaAS/OCISchemaDataTypes/ExtendedFileResourceSelection.php
PHP
gpl-2.0
703
/** * Copyright (C) 2015 Frank Steiler <frank@steilerdev.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 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, see <http://www.gnu.org/licenses/>. */ package de.steilerdev.whatToStudy.Exception; /** * This class is a application specific exception, always thrown and handled if an application specific error occurs. * In general other exceptions are tried to be wrapped inside this exception, so the program only needs to handle these kind of exceptions. */ public class WhatToStudyException extends Exception { /** * Constructs a new exception with {@code null} as its detail message. The cause is not initialized, and may * subsequently be initialized by a call to {@link #initCause}. */ public WhatToStudyException() { super(); } /** * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently * be initialized by a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} * method. */ public WhatToStudyException(String message) { super(message); } /** * Constructs a new exception with the specified detail message and cause. <p>Note that the detail message * associated with {@code cause} is <i>not</i> automatically incorporated in this exception's detail message. * * @param message the detail message (which is saved for later retrieval by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A * <tt>null</tt> value is permitted, and indicates that the cause is nonexistent or unknown.) * @since 1.4 */ public WhatToStudyException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause and a detail message of <tt>(cause==null ? null : * cause.toString())</tt> (which typically contains the class and detail message of <tt>cause</tt>). This * constructor is useful for exceptions that are little more than wrappers for other throwables (for example, {@link * java.security.PrivilegedActionException}). * * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A <tt>null</tt> * value is permitted, and indicates that the cause is nonexistent or unknown.) * @since 1.4 */ public WhatToStudyException(Throwable cause) { super(cause); } /** * Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and * writable stack trace enabled or disabled. * * @param message the detail message. * @param cause the cause. (A {@code null} value is permitted, and indicates that the cause is * nonexistent or unknown.) * @param enableSuppression whether or not suppression is enabled or disabled * @param writableStackTrace whether or not the stack trace should be writable * @since 1.7 */ protected WhatToStudyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
steilerDev/WhatToStudy
Source/src/de/steilerdev/whatToStudy/Exception/WhatToStudyException.java
Java
gpl-2.0
4,019
<?php /* * @version $Id$ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2015-2016 Teclib'. http://glpi-project.org based on GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI 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. GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ class RuleDictionnaryMonitorModel extends RuleDictionnaryDropdown { /** * Constructor **/ function __construct() { parent::__construct('RuleDictionnaryMonitorModel'); } /** * @see Rule::getCriterias() **/ function getCriterias() { static $criterias = array(); if (count($criterias)) { return $criterias; } $criterias['name']['field'] = 'name'; $criterias['name']['name'] = __('Model'); $criterias['name']['table'] = 'glpi_monitormodels'; $criterias['manufacturer']['field'] = 'name'; $criterias['manufacturer']['name'] = __('Manufacturer'); $criterias['manufacturer']['table'] = 'glpi_manufacturers'; return $criterias; } /** * @see Rule::getActions() **/ function getActions() { $actions = array(); $actions['name']['name'] = __('Model'); $actions['name']['force_actions'] = array('append_regex_result', 'assign','regex_result'); return $actions; } }
TECLIB/glpi
inc/ruledictionnarymonitormodel.class.php
PHP
gpl-2.0
2,216
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Employee Model * Check if user is staff, perform basic moderation actions * @package Models */ class Employee_model extends CI_Model { /** * Allow loggedin user access if session var * * @return bool * */ public function allow_access() { // check sess vars $staff = $this->php_session->get('employee'); if ($staff == 0) { return false; } else { return true; } } /** * Check if user is staff * * @param string $username The user's username * @return bool If the user is staff or not * */ public function is_staff($username) { // query db to check if user is employee $this->db->select('employee') ->from('users') ->where('username', $username); $result = $this->db->get()->row_array(); // return 0 or 1 switch($result['employee']) { case 1: return true; case 0: return false; } } /** * Get all users * * @return array, user's data * */ public function get_users() { // query db to list usernames and stuff $this->db->select('name, username, official, employee, avatar, points, email, id') ->from('users'); return $this->db->get()->result_array(); } /** * Delete user * * @return boolean, status of deletion * */ public function delete($id) { // query db if (is_numeric($id)) { $this->db->select('employee') ->from('users') ->where('id', $id); $arr = $this->db->get()->row_array(); $status = $arr['employee']; if($status == 1) { return false; } else { $this->db->delete('users', array('id'=>$id)); return true; } } } public function delete_f($id) { if (is_numeric($id)) { return $this->db->delete('users', array('id'=>$id)); } else { return false; } } public function delete_post($id) { return $this->db->delete('debates', array('id'=>$id)); } public function official($id) { if (is_numeric($id)) { $this->db->where('id', $id); $st = 1; $this->db->update('users', array('official'=>$st)); } } public function staff($id) { if (is_numeric($id)) { $this->db->where('id', $id); $st = 1; $this->db->update('users', array('employee'=>$st)); } } } ?>
unfinite/Alphasquare
src/application/models/employee_model.php
PHP
gpl-2.0
2,577
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.mahout.cf.taste.hadoop.item; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Reducer; import org.apache.mahout.cf.taste.hadoop.MutableRecommendedItem; import org.apache.mahout.cf.taste.hadoop.RecommendedItemsWritable; import org.apache.mahout.cf.taste.hadoop.TasteHadoopUtils; import org.apache.mahout.cf.taste.hadoop.TopItemsQueue; import org.apache.mahout.cf.taste.impl.common.FastIDSet; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.common.HadoopUtil; import org.apache.mahout.common.iterator.FileLineIterable; import org.apache.mahout.math.RandomAccessSparseVector; import org.apache.mahout.math.VarLongWritable; import org.apache.mahout.math.Vector; import org.apache.mahout.math.Vector.Element; import org.apache.mahout.math.function.Functions; import org.apache.mahout.math.map.OpenIntLongHashMap; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>computes prediction values for each user</p> * * <pre> * u = a user * i = an item not yet rated by u * N = all items similar to i (where similarity is usually computed by pairwisely comparing the item-vectors * of the user-item matrix) * * Prediction(u,i) = sum(all n from N: similarity(i,n) * rating(u,n)) / sum(all n from N: abs(similarity(i,n))) * </pre> */ public final class AggregateAndRecommendReducer extends Reducer<VarLongWritable,PrefAndSimilarityColumnWritable,VarLongWritable,RecommendedItemsWritable> { private static final Logger log = LoggerFactory.getLogger(AggregateAndRecommendReducer.class); static final String ITEMID_INDEX_PATH = "itemIDIndexPath"; static final String NUM_RECOMMENDATIONS = "numRecommendations"; static final int DEFAULT_NUM_RECOMMENDATIONS = 10; static final String ITEMS_FILE = "itemsFile"; private boolean booleanData; private int recommendationsPerUser; private FastIDSet itemsToRecommendFor; private OpenIntLongHashMap indexItemIDMap; private final RecommendedItemsWritable recommendedItems = new RecommendedItemsWritable(); private static final float BOOLEAN_PREF_VALUE = 1.0f; @Override protected void setup(Context context) throws IOException { Configuration conf = context.getConfiguration(); recommendationsPerUser = conf.getInt(NUM_RECOMMENDATIONS, DEFAULT_NUM_RECOMMENDATIONS); booleanData = conf.getBoolean(RecommenderJob.BOOLEAN_DATA, false); indexItemIDMap = TasteHadoopUtils.readIDIndexMap(conf.get(ITEMID_INDEX_PATH), conf); String itemFilePathString = conf.get(ITEMS_FILE); if (itemFilePathString != null) { itemsToRecommendFor = new FastIDSet(); for (String line : new FileLineIterable(HadoopUtil.openStream(new Path(itemFilePathString), conf))) { try { itemsToRecommendFor.add(Long.parseLong(line)); } catch (NumberFormatException nfe) { log.warn("itemsFile line ignored: {}", line); } } } } @Override protected void reduce(VarLongWritable userID, Iterable<PrefAndSimilarityColumnWritable> values, Context context) throws IOException, InterruptedException { if (booleanData) { reduceBooleanData(userID, values, context); } else { reduceNonBooleanData(userID, values, context); } } private void reduceBooleanData(VarLongWritable userID, Iterable<PrefAndSimilarityColumnWritable> values, Context context) throws IOException, InterruptedException { /* having boolean data, each estimated preference can only be 1, * however we can't use this to rank the recommended items, * so we use the sum of similarities for that. */ Iterator<PrefAndSimilarityColumnWritable> columns = values.iterator(); Vector predictions = columns.next().getSimilarityColumn(); while (columns.hasNext()) { predictions.assign(columns.next().getSimilarityColumn(), Functions.PLUS); } writeRecommendedItems(userID, predictions, context); } private void reduceNonBooleanData(VarLongWritable userID, Iterable<PrefAndSimilarityColumnWritable> values, Context context) throws IOException, InterruptedException { /* each entry here is the sum in the numerator of the prediction formula */ Vector numerators = null; /* each entry here is the sum in the denominator of the prediction formula */ Vector denominators = null; /* each entry here is the number of similar items used in the prediction formula */ Vector numberOfSimilarItemsUsed = new RandomAccessSparseVector(Integer.MAX_VALUE, 100); for (PrefAndSimilarityColumnWritable prefAndSimilarityColumn : values) { Vector simColumn = prefAndSimilarityColumn.getSimilarityColumn(); float prefValue = prefAndSimilarityColumn.getPrefValue(); /* count the number of items used for each prediction */ for (Element e : simColumn.nonZeroes()) { int itemIDIndex = e.index(); numberOfSimilarItemsUsed.setQuick(itemIDIndex, numberOfSimilarItemsUsed.getQuick(itemIDIndex) + 1); } if (denominators == null) { denominators = simColumn.clone(); } else { denominators.assign(simColumn, Functions.PLUS_ABS); } if (numerators == null) { numerators = simColumn.clone(); if (prefValue != BOOLEAN_PREF_VALUE) { numerators.assign(Functions.MULT, prefValue); } } else { if (prefValue != BOOLEAN_PREF_VALUE) { simColumn.assign(Functions.MULT, prefValue); } numerators.assign(simColumn, Functions.PLUS); } } if (numerators == null) { return; } Vector recommendationVector = new RandomAccessSparseVector(Integer.MAX_VALUE, 100); for (Element element : numerators.nonZeroes()) { int itemIDIndex = element.index(); /* preference estimations must be based on at least 2 datapoints */ if (numberOfSimilarItemsUsed.getQuick(itemIDIndex) > 1) { /* compute normalized prediction */ double prediction = element.get() / denominators.getQuick(itemIDIndex); recommendationVector.setQuick(itemIDIndex, prediction); } } writeRecommendedItems(userID, recommendationVector, context); } /** * find the top entries in recommendationVector, map them to the real itemIDs and write back the result */ private void writeRecommendedItems(VarLongWritable userID, Vector recommendationVector, Context context) throws IOException, InterruptedException { TopItemsQueue topKItems = new TopItemsQueue(recommendationsPerUser); for (Element element : recommendationVector.nonZeroes()) { int index = element.index(); long itemID; if (indexItemIDMap != null && !indexItemIDMap.isEmpty()) { itemID = indexItemIDMap.get(index); } else { //we don't have any mappings, so just use the original itemID = index; } if (itemsToRecommendFor == null || itemsToRecommendFor.contains(itemID)) { float value = (float) element.get(); if (!Float.isNaN(value)) { MutableRecommendedItem topItem = topKItems.top(); if (value > topItem.getValue()) { topItem.set(itemID, value); topKItems.updateTop(); } } } } List<RecommendedItem> topItems = topKItems.getTopItems(); if (!topItems.isEmpty()) { recommendedItems.set(topItems); context.write(userID, recommendedItems); } } }
bharcode/MachineLearning
CustomMahout/core/src/main/java/org/apache/mahout/cf/taste/hadoop/item/AggregateAndRecommendReducer.java
Java
gpl-2.0
8,512
<?php /** * Page Template * * Loaded automatically by index.php?main_page=order_status.<br /> * Displays information related to a single specific order * * @package templateSystem * @copyright Copyright 2003-2015 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @copyright Portions copyright COWOA authors see https://www.zen-cart.com/downloads.php?do=file&id=1115 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: New in V1.6.0 $ */ ?> <!-- TPL_ORDER_STATUS_DEFAULT.PHP --> <div class="centerColumn" id="accountHistInfo"> <h1 id="orderHistoryHeading"><?php echo HEADING_TITLE; ?></h1> <br /> <?php if (isset($_POST['action']) && $_POST['action'] == "process" && ($errorInvalidID || $errorInvalidEmail || $errorNoMatch)) { ?> <div class="messageStackWarning larger"> <?php if($errorInvalidID) echo ERROR_INVALID_ORDER; if($errorInvalidEmail) echo ERROR_INVALID_EMAIL; if($errorNoMatch) echo ERROR_NO_MATCH; ?> </div> <?php } ?> <?php if (isset($order)) { ?> <table border="0" width="100%" cellspacing="0" cellpadding="0" summary="Itemized listing of previous order, includes number ordered, items and prices"> <h2 id="orderHistoryDetailedOrder"><?php echo SUB_HEADING_TITLE . ORDER_HEADING_DIVIDER . sprintf(HEADING_ORDER_NUMBER, $_POST['order_id']); ?></h2> <div class="forward"><?php echo HEADING_ORDER_DATE . ' ' . zen_date_long($order->info['date_purchased']); ?></div> <br class="clearBoth" /> <tr class="tableHeading"> <th scope="col" id="myAccountQuantity"><?php echo HEADING_QUANTITY; ?></th> <th scope="col" id="myAccountProducts"><?php echo HEADING_PRODUCTS; ?></th> <?php if (sizeof($order->info['tax_groups']) > 1) { ?> <th scope="col" id="myAccountTax"><?php echo HEADING_TAX; ?></th> <?php } ?> <th scope="col" id="myAccountTotal"><?php echo HEADING_TOTAL; ?></th> </tr> <?php for ($i=0, $n=sizeof($order->products); $i<$n; $i++) { ?> <tr> <td class="accountQuantityDisplay"><?php echo $order->products[$i]['qty'] . QUANTITY_SUFFIX; ?></td> <td class="accountProductDisplay"><?php echo $order->products[$i]['name']; if ( (isset($order->products[$i]['attributes'])) && (sizeof($order->products[$i]['attributes']) > 0) ) { echo '<ul class="orderAttribsList">'; for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) { echo '<li>' . $order->products[$i]['attributes'][$j]['option'] . TEXT_OPTION_DIVIDER . nl2br($order->products[$i]['attributes'][$j]['value']) . '</li>'; } echo '</ul>'; } ?> </td> <?php if (sizeof($order->info['tax_groups']) > 1) { ?> <td class="accountTaxDisplay"><?php echo zen_display_tax_value($order->products[$i]['tax']) . '%' ?></td> <?php } ?> <td class="accountTotalDisplay"><?php echo $currencies->format(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ($order->products[$i]['onetime_charges'] != 0 ? '<br />' . $currencies->format(zen_add_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), true, $order->info['currency'], $order->info['currency_value']) : '') ?></td> </tr> <?php } ?> </table> <hr /> <div id="orderTotals"> <?php for ($i=0, $n=sizeof($order->totals); $i<$n; $i++) { ?> <div class="amount larger forward"><?php echo $order->totals[$i]['text'] ?></div> <div class="lineTitle larger forward"><?php echo $order->totals[$i]['title'] ?></div> <br class="clearBoth" /> <?php } ?> </div> <?php /** * Used to display any downloads associated with the cutomers account */ if (DOWNLOAD_ENABLED == 'true') require($template->get_template_dir('tpl_modules_downloads.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_downloads.php'); ?> <?php /** * Used to loop thru and display order status information */ if (sizeof($statusArray)) { ?> <table border="0" width="100%" cellspacing="0" cellpadding="0" id="myAccountOrdersStatus" summary="Table contains the date, order status and any comments regarding the order"> <caption><h2 id="orderHistoryStatus"><?php echo HEADING_ORDER_HISTORY; ?></h2></caption> <tr class="tableHeading"> <th scope="col" id="myAccountStatusDate"><?php echo TABLE_HEADING_STATUS_DATE; ?></th> <th scope="col" id="myAccountStatus"><?php echo TABLE_HEADING_STATUS_ORDER_STATUS; ?></th> <th scope="col" id="myAccountStatusComments"><?php echo TABLE_HEADING_STATUS_COMMENTS; ?></th> </tr> <?php foreach ($statusArray as $statuses) { ?> <tr> <td><?php echo zen_date_short($statuses['date_added']); ?></td> <td><?php echo $statuses['orders_status_name']; ?></td> <td><?php echo (empty($statuses['comments']) ? '&nbsp;' : nl2br(zen_output_string_protected($statuses['comments']))); ?></td> </tr> <?php } ?> </table> <?php } ?> <hr /> <div id="myAccountShipInfo" class="floatingBox back"> <?php if (zen_not_null($order->info['shipping_method'])) { ?> <h4><?php echo HEADING_SHIPPING_METHOD; ?></h4> <div><?php echo $order->info['shipping_method']; ?></div> <?php } else { // temporary just remove these 4 lines ?> <div>WARNING: Missing Shipping Information</div> <?php } ?> </div> <div id="myAccountPaymentInfo" class="floatingBox forward"> <h4><?php echo HEADING_PAYMENT_METHOD; ?></h4> <div><?php echo $order->info['payment_method']; ?></div> </div> <br class="clearBoth" /> <br /> <?php } ?> <?php echo zen_draw_form('order_status', zen_href_link(FILENAME_ORDER_STATUS, '', 'SSL'), 'post') . zen_draw_hidden_field('action', 'process'); ?> <fieldset> <legend><?php echo HEADING_TITLE; ?></legend> <?php echo TEXT_LOOKUP_INSTRUCTIONS; ?> <br /><br /> <label class="inputLabel"><?php echo ENTRY_ORDER_NUMBER; ?></label> <?php echo zen_draw_input_field('order_id', (int)$_GET['order_id'], 'size="10" id="order_id" required autofocus', 'number'); ?> <br /> <br /> <label class="inputLabel"><?php echo ENTRY_EMAIL; ?></label> <?php echo zen_draw_input_field('query_email_address', '', 'size="35" id="query_email_address" required', 'email'); ?> <br /> <div class="buttonRow forward"><?php echo zen_image_submit(BUTTON_IMAGE_CONTINUE, BUTTON_CONTINUE_ALT); ?></div> </fieldset> </form> </div>
drbyte/zc-v1-series
includes/templates/template_default/templates/tpl_order_status_default.php
PHP
gpl-2.0
6,773
/* * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "common.h" #include <UIAutomation.h> #include "GlassApplication.h" #include "ViewContainer.h" #include "GlassView.h" #include "KeyTable.h" #include "Utils.h" #include "GlassDnD.h" #include "GlassInputTextInfo.h" #include "ManipulationEvents.h" #include "BaseWnd.h" #include "com_sun_glass_events_ViewEvent.h" #include "com_sun_glass_events_KeyEvent.h" #include "com_sun_glass_events_MouseEvent.h" #include "com_sun_glass_events_DndEvent.h" #include "com_sun_glass_events_TouchEvent.h" static UINT LangToCodePage(LANGID idLang) { WCHAR strCodePage[8]; // use the LANGID to create a LCID LCID idLocale = MAKELCID(idLang, SORT_DEFAULT); // get the ANSI code page associated with this locale if (::GetLocaleInfo(idLocale, LOCALE_IDEFAULTANSICODEPAGE, strCodePage, sizeof(strCodePage) / sizeof(WCHAR)) > 0) { return _wtoi(strCodePage); } else { return ::GetACP(); } } namespace { bool IsTouchEvent() { // Read this link if you wonder why we need to hard code the mask and signature: // http://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx //"The lower 8 bits returned from GetMessageExtraInfo are variable. // Of those bits, 7 (the lower 7, masked by 0x7F) are used to represent the cursor ID, // zero for the mouse or a variable value for the pen ID. // Additionally, in Windows Vista, the eighth bit, masked by 0x80, is used to // differentiate touch input from pen input (0 = pen, 1 = touch)." UINT SIGNATURE = 0xFF515780; UINT MASK = 0xFFFFFF80; UINT v = (UINT) GetMessageExtraInfo(); return ((v & MASK) == SIGNATURE); } } // namespace ViewContainer::ViewContainer() : m_view(NULL), m_bTrackingMouse(FALSE), m_manipProc(NULL), m_inertiaProc(NULL), m_manipEventSink(NULL), m_gestureSupportCls(NULL), m_lastMouseMovePosition(-1), m_mouseButtonDownCounter(0), m_deadKeyWParam(0) { m_kbLayout = ::GetKeyboardLayout(0); m_idLang = LOWORD(m_kbLayout); m_codePage = LangToCodePage(m_idLang); m_lastTouchInputCount = 0; } jobject ViewContainer::GetView() { return GetGlassView() != NULL ? GetGlassView()->GetView() : NULL; } void ViewContainer::InitDropTarget(HWND hwnd) { if (!hwnd) { return; } m_spDropTarget = std::auto_ptr<IDropTarget>(new GlassDropTarget(this, hwnd)); } void ViewContainer::ReleaseDropTarget() { m_spDropTarget = std::auto_ptr<IDropTarget>(); } void ViewContainer::InitManipProcessor(HWND hwnd) { if (IS_WIN7) { ::RegisterTouchWindow(hwnd, TWF_WANTPALM); HRESULT hr = ::CoCreateInstance(CLSID_ManipulationProcessor, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (VOID**)(&m_manipProc) ); if (SUCCEEDED(hr)) { ::CoCreateInstance(CLSID_InertiaProcessor, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (VOID**)(&m_inertiaProc) ); m_manipEventSink = new ManipulationEventSinkWithInertia(m_manipProc, m_inertiaProc, this, hwnd); } const DWORD_PTR dwHwndTabletProperty = TABLET_DISABLE_PENTAPFEEDBACK | TABLET_DISABLE_PENBARRELFEEDBACK | TABLET_DISABLE_FLICKS; ::SetProp(hwnd, MICROSOFT_TABLETPENSERVICE_PROPERTY, reinterpret_cast<HANDLE>(dwHwndTabletProperty)); if (!m_gestureSupportCls) { JNIEnv *env = GetEnv(); const jclass cls = GlassApplication::ClassForName(env, "com.sun.glass.ui.win.WinGestureSupport"); m_gestureSupportCls = (jclass)env->NewGlobalRef(cls); env->DeleteLocalRef(cls); ASSERT(m_gestureSupportCls); } } } void ViewContainer::ReleaseManipProcessor() { if (IS_WIN7) { if (m_manipProc) { m_manipProc->Release(); m_manipProc = NULL; } if (m_inertiaProc) { m_inertiaProc->Release(); m_inertiaProc = NULL; } if (m_manipEventSink) { m_manipEventSink->Release(); m_manipEventSink = NULL; } } if (m_gestureSupportCls) { JNIEnv *env = GetEnv(); env->DeleteGlobalRef(m_gestureSupportCls); m_gestureSupportCls = 0; } } void ViewContainer::HandleViewInputLangChange(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } m_kbLayout = reinterpret_cast<HKL>(lParam); m_idLang = LOWORD(m_kbLayout); m_codePage = LangToCodePage(m_idLang); m_deadKeyWParam = 0; } void ViewContainer::NotifyViewMoved(HWND hwnd) { if (!hwnd || !GetGlassView()) { return; } JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyView, com_sun_glass_events_ViewEvent_MOVE); CheckAndClearException(env); } void ViewContainer::NotifyViewSize(HWND hwnd) { if (!hwnd || !GetGlassView()) { return; } RECT r; if (::GetClientRect(hwnd, &r)) { JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyResize, r.right-r.left, r.bottom - r.top); CheckAndClearException(env); } } void ViewContainer::HandleViewPaintEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } RECT r; if (!::GetUpdateRect(hwnd, &r, FALSE)) { return; } JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyRepaint, r.left, r.top, r.right-r.left, r.bottom-r.top); CheckAndClearException(env); } LRESULT ViewContainer::HandleViewGetAccessible(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return NULL; } /* WM_GETOBJECT is sent to request different object types, * always test the type to avoid unnecessary work. */ LRESULT lr = NULL; if (static_cast<long>(lParam) == static_cast<long>(UiaRootObjectId)) { /* The client is requesting UI Automation. */ JNIEnv* env = GetEnv(); if (!env) return NULL; jlong pProvider = env->CallLongMethod(GetView(), javaIDs.View.getAccessible); CheckAndClearException(env); /* It is possible WM_GETOBJECT is sent before the toolkit is ready to * create the accessible object (getAccessible returns NULL). * On Windows 7, calling UiaReturnRawElementProvider() with a NULL provider * returns an invalid LRESULT which stops further WM_GETOBJECT to be sent, * effectively disabling accessibility for the window. */ if (pProvider) { lr = UiaReturnRawElementProvider(hwnd, wParam, lParam, reinterpret_cast<IRawElementProviderSimple*>(pProvider)); } } else if (static_cast<long>(lParam) == static_cast<long>(OBJID_CLIENT)) { /* By default JAWS does not send WM_GETOBJECT with UiaRootObjectId till * a focus event is raised by UiaRaiseAutomationEvent(). * In some systems (i.e. touch monitors), OBJID_CLIENT are sent when * no screen reader is active. Test for SPI_GETSCREENREADER and * UiaClientsAreListening() to avoid initializing accessibility * unnecessarily. */ UINT screenReader = 0; ::SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); if (screenReader && UiaClientsAreListening()) { JNIEnv* env = GetEnv(); if (env) { /* Calling getAccessible() initializes accessibility which * eventually raises the focus events required to indicate to * JAWS to use UIA for this window. * * Note: do not return the accessible object for OBJID_CLIENT, * that would create an UIA-MSAA bridge. That problem with the * bridge is that it does not respect * ProviderOptions_UseComThreading. */ env->CallLongMethod(GetView(), javaIDs.View.getAccessible); CheckAndClearException(env); } } } return lr; } void ViewContainer::HandleViewSizeEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (wParam == SIZE_MINIMIZED) { return; } NotifyViewSize(hwnd); } void ViewContainer::HandleViewMenuEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } if ((HWND)wParam != hwnd) { return; } jboolean isKeyboardTrigger = lParam == (LPARAM)-1; if (isKeyboardTrigger) { lParam = ::GetMessagePos (); } POINT pt; int absX = pt.x = GET_X_LPARAM(lParam); int absY = pt.y = GET_Y_LPARAM(lParam); ::ScreenToClient (hwnd, &pt); if (!isKeyboardTrigger) { RECT rect; ::GetClientRect(hwnd, &rect); if (!::PtInRect(&rect, pt)) { return; } } // unmirror the x coordinate LONG style = ::GetWindowLong(hwnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hwnd, &rect); pt.x = max(0, rect.right - rect.left) - pt.x; } JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyMenu, pt.x, pt.y, absX, absY, isKeyboardTrigger); CheckAndClearException(env); } void ViewContainer::HandleViewKeyEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } static const BYTE KEY_STATE_DOWN = 0x80; UINT wKey = static_cast<UINT>(wParam); UINT flags = HIWORD(lParam); jint jKeyCode = WindowsKeyToJavaKey(wKey); if (flags & (1 << 8)) { // this is an extended key (e.g. Right ALT == AltGr) switch (jKeyCode) { case com_sun_glass_events_KeyEvent_VK_ALT: jKeyCode = com_sun_glass_events_KeyEvent_VK_ALT_GRAPH; break; } } BYTE kbState[256]; if (!::GetKeyboardState(kbState)) { return; } jint jModifiers = GetModifiers(); if (jModifiers & com_sun_glass_events_KeyEvent_MODIFIER_CONTROL) { kbState[VK_CONTROL] &= ~KEY_STATE_DOWN; } WORD mbChar; UINT scancode = ::MapVirtualKeyEx(wKey, 0, m_kbLayout); // Depress modifiers to map a Unicode char to a key code kbState[VK_CONTROL] &= ~0x80; kbState[VK_SHIFT] &= ~0x80; kbState[VK_MENU] &= ~0x80; int converted = ::ToAsciiEx(wKey, scancode, kbState, &mbChar, 0, m_kbLayout); wchar_t wChar[4] = {0}; int unicodeConverted = ::ToUnicodeEx(wKey, scancode, kbState, wChar, 4, 0, m_kbLayout); // Some virtual codes require special handling switch (wKey) { case 0x00BA:// VK_OEM_1 case 0x00BB:// VK_OEM_PLUS case 0x00BC:// VK_OEM_COMMA case 0x00BD:// VK_OEM_MINUS case 0x00BE:// VK_OEM_PERIOD case 0x00BF:// VK_OEM_2 case 0x00C0:// VK_OEM_3 case 0x00DB:// VK_OEM_4 case 0x00DC:// VK_OEM_5 case 0x00DD:// VK_OEM_6 case 0x00DE:// VK_OEM_7 case 0x00DF:// VK_OEM_8 case 0x00E2:// VK_OEM_102 if (unicodeConverted < 0) { // Dead key switch (wChar[0]) { case L'`': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_GRAVE; break; case L'\'': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ACUTE; break; case 0x00B4: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ACUTE; break; case L'^': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CIRCUMFLEX; break; case L'~': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_TILDE; break; case 0x02DC: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_TILDE; break; case 0x00AF: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_MACRON; break; case 0x02D8: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_BREVE; break; case 0x02D9: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ABOVEDOT; break; case L'"': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_DIAERESIS; break; case 0x00A8: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_DIAERESIS; break; case 0x02DA: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ABOVERING; break; case 0x02DD: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_DOUBLEACUTE; break; case 0x02C7: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CARON; break; // aka hacek case L',': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CEDILLA; break; case 0x00B8: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CEDILLA; break; case 0x02DB: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_OGONEK; break; case 0x037A: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_IOTA; break; // ASCII ??? case 0x309B: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_VOICED_SOUND; break; case 0x309C: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_SEMIVOICED_SOUND; break; default: jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDEFINED; break; }; } else if (unicodeConverted == 1) { switch (wChar[0]) { case L'!': jKeyCode = com_sun_glass_events_KeyEvent_VK_EXCLAMATION; break; case L'"': jKeyCode = com_sun_glass_events_KeyEvent_VK_DOUBLE_QUOTE; break; case L'#': jKeyCode = com_sun_glass_events_KeyEvent_VK_NUMBER_SIGN; break; case L'$': jKeyCode = com_sun_glass_events_KeyEvent_VK_DOLLAR; break; case L'&': jKeyCode = com_sun_glass_events_KeyEvent_VK_AMPERSAND; break; case L'\'': jKeyCode = com_sun_glass_events_KeyEvent_VK_QUOTE; break; case L'(': jKeyCode = com_sun_glass_events_KeyEvent_VK_LEFT_PARENTHESIS; break; case L')': jKeyCode = com_sun_glass_events_KeyEvent_VK_RIGHT_PARENTHESIS; break; case L'*': jKeyCode = com_sun_glass_events_KeyEvent_VK_ASTERISK; break; case L'+': jKeyCode = com_sun_glass_events_KeyEvent_VK_PLUS; break; case L',': jKeyCode = com_sun_glass_events_KeyEvent_VK_COMMA; break; case L'-': jKeyCode = com_sun_glass_events_KeyEvent_VK_MINUS; break; case L'.': jKeyCode = com_sun_glass_events_KeyEvent_VK_PERIOD; break; case L'/': jKeyCode = com_sun_glass_events_KeyEvent_VK_SLASH; break; case L':': jKeyCode = com_sun_glass_events_KeyEvent_VK_COLON; break; case L';': jKeyCode = com_sun_glass_events_KeyEvent_VK_SEMICOLON; break; case L'<': jKeyCode = com_sun_glass_events_KeyEvent_VK_LESS; break; case L'=': jKeyCode = com_sun_glass_events_KeyEvent_VK_EQUALS; break; case L'>': jKeyCode = com_sun_glass_events_KeyEvent_VK_GREATER; break; case L'@': jKeyCode = com_sun_glass_events_KeyEvent_VK_AT; break; case L'[': jKeyCode = com_sun_glass_events_KeyEvent_VK_OPEN_BRACKET; break; case L'\\': jKeyCode = com_sun_glass_events_KeyEvent_VK_BACK_SLASH; break; case L']': jKeyCode = com_sun_glass_events_KeyEvent_VK_CLOSE_BRACKET; break; case L'^': jKeyCode = com_sun_glass_events_KeyEvent_VK_CIRCUMFLEX; break; case L'_': jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDERSCORE; break; case L'`': jKeyCode = com_sun_glass_events_KeyEvent_VK_BACK_QUOTE; break; case L'{': jKeyCode = com_sun_glass_events_KeyEvent_VK_BRACELEFT; break; case L'}': jKeyCode = com_sun_glass_events_KeyEvent_VK_BRACERIGHT; break; case 0x00A1: jKeyCode = com_sun_glass_events_KeyEvent_VK_INV_EXCLAMATION; break; case 0x20A0: jKeyCode = com_sun_glass_events_KeyEvent_VK_EURO_SIGN; break; default: jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDEFINED; break; } } else if (unicodeConverted == 0 || unicodeConverted > 1) { jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDEFINED; } break; }; int keyCharCount = 0; jchar keyChars[4]; const bool isAutoRepeat = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) && (lParam & (1 << 30)); if (converted < 0) { // Dead key return; } else if (converted == 0) { // No translation available keyCharCount = 0; // This includes SHIFT, CONTROL, ALT, etc. // RT-17062: suppress auto-repeated events for modifier keys if (isAutoRepeat) { switch (jKeyCode) { case com_sun_glass_events_KeyEvent_VK_SHIFT: case com_sun_glass_events_KeyEvent_VK_CONTROL: case com_sun_glass_events_KeyEvent_VK_ALT: case com_sun_glass_events_KeyEvent_VK_ALT_GRAPH: case com_sun_glass_events_KeyEvent_VK_WINDOWS: return; } } } else { // Handle some special cases if ((wKey == VK_BACK) || (wKey == VK_ESCAPE)) { keyCharCount = 0; } else { keyCharCount = ::MultiByteToWideChar(m_codePage, MB_PRECOMPOSED, (LPCSTR)&mbChar, 2, (LPWSTR)keyChars, 4 * sizeof(jchar)) - 1; if (keyCharCount <= 0) { return; } } } JNIEnv* env = GetEnv(); jcharArray jKeyChars = env->NewCharArray(keyCharCount); if (jKeyChars) { if (keyCharCount) { env->SetCharArrayRegion(jKeyChars, 0, keyCharCount, keyChars); CheckAndClearException(env); } if (jKeyCode == com_sun_glass_events_KeyEvent_VK_PRINTSCREEN && (msg == WM_KEYUP || msg == WM_SYSKEYUP)) { // MS Windows doesn't send WM_KEYDOWN for the PrintScreen key, // so we synthesize one env->CallVoidMethod(GetView(), javaIDs.View.notifyKey, com_sun_glass_events_KeyEvent_PRESS, jKeyCode, jKeyChars, jModifiers); CheckAndClearException(env); } if (GetGlassView()) { env->CallVoidMethod(GetView(), javaIDs.View.notifyKey, (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) ? com_sun_glass_events_KeyEvent_PRESS : com_sun_glass_events_KeyEvent_RELEASE, jKeyCode, jKeyChars, jModifiers); CheckAndClearException(env); } // MS Windows doesn't send WM_CHAR for the Delete key, // so we synthesize one if (jKeyCode == com_sun_glass_events_KeyEvent_VK_DELETE && (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) && GetGlassView()) { // 0x7F == U+007F - a Unicode character for DELETE SendViewTypedEvent(1, (jchar)0x7F); } env->DeleteLocalRef(jKeyChars); } } void ViewContainer::SendViewTypedEvent(int repCount, jchar wChar) { if (!GetGlassView()) { return; } JNIEnv* env = GetEnv(); jcharArray jKeyChars = env->NewCharArray(repCount); if (jKeyChars) { jchar* nKeyChars = env->GetCharArrayElements(jKeyChars, NULL); if (nKeyChars) { for (int i = 0; i < repCount; i++) { nKeyChars[i] = wChar; } env->ReleaseCharArrayElements(jKeyChars, nKeyChars, 0); env->CallVoidMethod(GetView(), javaIDs.View.notifyKey, com_sun_glass_events_KeyEvent_TYPED, com_sun_glass_events_KeyEvent_VK_UNDEFINED, jKeyChars, GetModifiers()); CheckAndClearException(env); } env->DeleteLocalRef(jKeyChars); } } void ViewContainer::HandleViewDeadKeyEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } if (!m_deadKeyWParam) { // HandleViewKeyEvent() calls ::ToAsciiEx and ::ToUnicodeEx which clear // the dead key status from the keyboard layout. We store the current dead // key here to use it when processing WM_CHAR in order to get the // actual character typed. m_deadKeyWParam = wParam; } else { // There already was another dead key pressed previously. Clear it // and send two separate TYPED events instead to emulate native behavior. SendViewTypedEvent(1, (jchar)m_deadKeyWParam); SendViewTypedEvent(1, (jchar)wParam); m_deadKeyWParam = 0; } // Since we handle dead keys ourselves, reset the keyboard dead key status (if any) static BYTE kbState[256]; ::GetKeyboardState(kbState); WORD ignored; ::ToAsciiEx(VK_SPACE, ::MapVirtualKey(VK_SPACE, 0), kbState, &ignored, 0, m_kbLayout); } void ViewContainer::HandleViewTypedEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } int repCount = LOWORD(lParam); jchar wChar; if (!m_deadKeyWParam) { wChar = (jchar)wParam; } else { // The character is composed together with the dead key, which // may be translated into one or more combining characters. const size_t COMP_SIZE = 5; wchar_t comp[COMP_SIZE] = { (wchar_t)wParam }; // Some dead keys need additional translation: // http://www.fileformat.info/info/unicode/block/combining_diacritical_marks/images.htm // Also see awt_Component.cpp for the original dead keys table if (LOBYTE(m_idLang) == LANG_GREEK) { switch (m_deadKeyWParam) { case L']': comp[1] = 0x300; break; // varia case L';': comp[1] = 0x301; break; // oxia (wrong? generates tonos, not oxia) case L'-': comp[1] = 0x304; break; // macron case L'_': comp[1] = 0x306; break; // vrachy case L':': comp[1] = 0x308; break; // dialytika case L'"': comp[1] = 0x314; break; // dasia case 0x0384: comp[1] = 0x341; break; // tonos case L'[': comp[1] = 0x342; break; // perispomeni case L'\'': comp[1] = 0x343; break; // psili case L'~': comp[1] = 0x344; break; // dialytika oxia case L'{': comp[1] = 0x345; break; // ypogegrammeni case L'`': comp[1] = 0x308; comp[2] = 0x300; break; // dialytika varia case L'\\': comp[1] = 0x313; comp[2] = 0x300; break; // psili varia case L'/': comp[1] = 0x313; comp[2] = 0x301; break; // psili oxia case L'=': comp[1] = 0x313; comp[2] = 0x342; break; // psili perispomeni case L'|': comp[1] = 0x314; comp[2] = 0x300; break; // dasia varia case L'?': comp[1] = 0x314; comp[2] = 0x301; break; // dasia oxia case L'+': comp[1] = 0x314; comp[2] = 0x342; break; // dasia perispomeni // AltGr dead chars don't work. Maybe kbd isn't reset properly? // case 0x1fc1: comp[1] = 0x308; comp[2] = 0x342; break; // dialytika perispomeni // case 0x1fde: comp[1] = 0x314; comp[2] = 0x301; comp[3] = 0x345; break; // dasia oxia ypogegrammeni default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } } else if (HIWORD(m_kbLayout) == 0xF0B1 && LOBYTE(m_idLang) == LANG_LATVIAN) { // The Latvian (Standard) keyboard, available in Win 8.1 and later. switch (m_deadKeyWParam) { case L'\'': case L'"': // Note: " is Shift-' and automatically capitalizes the typed // character in native Win 8.1 apps. We don't do this, so the user // needs to keep the Shift key down. This is probably the common use // case anyway. switch (wParam) { case L'A': case L'a': case L'E': case L'e': case L'I': case L'i': case L'U': case L'u': comp[1] = 0x304; break; // macron case L'C': case L'c': case L'S': case L's': case L'Z': case L'z': comp[1] = 0x30c; break; // caron case L'G': case L'g': case L'K': case L'k': case L'L': case L'l': case L'N': case L'n': comp[1] = 0x327; break; // cedilla default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } break; default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } } else { switch (m_deadKeyWParam) { case L'`': comp[1] = 0x300; break; case L'\'': comp[1] = 0x301; break; case 0x00B4: comp[1] = 0x301; break; case L'^': comp[1] = 0x302; break; case L'~': comp[1] = 0x303; break; case 0x02DC: comp[1] = 0x303; break; case 0x00AF: comp[1] = 0x304; break; case 0x02D8: comp[1] = 0x306; break; case 0x02D9: comp[1] = 0x307; break; case L'"': comp[1] = 0x308; break; case 0x00A8: comp[1] = 0x308; break; case 0x00B0: comp[1] = 0x30A; break; case 0x02DA: comp[1] = 0x30A; break; case 0x02DD: comp[1] = 0x30B; break; case 0x02C7: comp[1] = 0x30C; break; case L',': comp[1] = 0x327; break; case 0x00B8: comp[1] = 0x327; break; case 0x02DB: comp[1] = 0x328; break; default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } } int compSize = 3; for (int i = 1; i < COMP_SIZE; i++) { if (comp[i] == L'\0') { compSize = i + 1; break; } } wchar_t out[3]; int res = ::FoldString(MAP_PRECOMPOSED, (LPWSTR)comp, compSize, (LPWSTR)out, 3); if (res > 0) { wChar = (jchar)out[0]; if (res == 3) { // The character cannot be accented, so we send a TYPED event // for the dead key itself first. SendViewTypedEvent(1, (jchar)m_deadKeyWParam); } } else { // Folding failed. Use the untranslated original character then wChar = (jchar)wParam; } // Clear the dead key m_deadKeyWParam = 0; } SendViewTypedEvent(repCount, wChar); } BOOL ViewContainer::HandleViewMouseEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return FALSE; } int type = 0; int button = com_sun_glass_events_MouseEvent_BUTTON_NONE; POINT pt; // client coords jdouble wheelRotation = 0.0; if (msg == WM_MOUSELEAVE) { type = com_sun_glass_events_MouseEvent_EXIT; // get the coords (the message does not contain them) lParam = ::GetMessagePos(); pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam); // this is screen coords, convert to client ::ScreenToClient(hwnd, &pt); // Windows has finished tracking mouse pointer already m_bTrackingMouse = FALSE; m_lastMouseMovePosition = -1; } else { // for all other messages lParam contains cursor coords pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam); switch (msg) { case WM_MOUSEMOVE: if (lParam == m_lastMouseMovePosition) { // Avoid sending synthetic MOVE/DRAG events if // the pointer hasn't moved actually. // Just consume the messages. return TRUE; } else { m_lastMouseMovePosition = lParam; } // See RT-11305 regarding the GetCapture() check if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) != 0 && ::GetCapture() == hwnd) { type = com_sun_glass_events_MouseEvent_DRAG; } else { type = com_sun_glass_events_MouseEvent_MOVE; } // Due to RT-11305 we should report the pressed button for both // MOVE and DRAG. This also enables one to filter out these // events in client code in case they're undesired. if (wParam & MK_RBUTTON) { button = com_sun_glass_events_MouseEvent_BUTTON_RIGHT; } else if (wParam & MK_LBUTTON) { button = com_sun_glass_events_MouseEvent_BUTTON_LEFT; } else if (wParam & MK_MBUTTON) { button = com_sun_glass_events_MouseEvent_BUTTON_OTHER; } break; case WM_LBUTTONDOWN: type = com_sun_glass_events_MouseEvent_DOWN; button = com_sun_glass_events_MouseEvent_BUTTON_LEFT; break; case WM_LBUTTONUP: type = com_sun_glass_events_MouseEvent_UP; button = com_sun_glass_events_MouseEvent_BUTTON_LEFT; break; case WM_RBUTTONDOWN: type = com_sun_glass_events_MouseEvent_DOWN; button = com_sun_glass_events_MouseEvent_BUTTON_RIGHT; break; case WM_RBUTTONUP: type = com_sun_glass_events_MouseEvent_UP; button = com_sun_glass_events_MouseEvent_BUTTON_RIGHT; break; case WM_MBUTTONDOWN: type = com_sun_glass_events_MouseEvent_DOWN; button = com_sun_glass_events_MouseEvent_BUTTON_OTHER; break; case WM_MBUTTONUP: type = com_sun_glass_events_MouseEvent_UP; button = com_sun_glass_events_MouseEvent_BUTTON_OTHER; break; case WM_MOUSEWHEEL: case WM_MOUSEHWHEEL: { // MS Windows always sends WHEEL events to the focused window. // Redirect the message to a Glass window under the mouse // cursor instead to match Mac behavior HWND hwndUnderCursor = ::ChildWindowFromPointEx( ::GetDesktopWindow(), pt, CWP_SKIPDISABLED | CWP_SKIPINVISIBLE); if (hwndUnderCursor && hwndUnderCursor != hwnd) { DWORD hWndUnderCursorProcess; ::GetWindowThreadProcessId(hwndUnderCursor, &hWndUnderCursorProcess); if (::GetCurrentProcessId() == hWndUnderCursorProcess) { return (BOOL)::SendMessage(hwndUnderCursor, msg, wParam, lParam); } } // if there's none, proceed as usual type = com_sun_glass_events_MouseEvent_WHEEL; wheelRotation = (jdouble)GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; } break; } } switch (type) { case 0: // not handled return FALSE; case com_sun_glass_events_MouseEvent_DOWN: m_mouseButtonDownCounter++; if (::GetCapture() != hwnd) { ::SetCapture(hwnd); } break; case com_sun_glass_events_MouseEvent_UP: if (m_mouseButtonDownCounter) { m_mouseButtonDownCounter--; } //else { internal inconsistency; quite unimportant though } if (::GetCapture() == hwnd && !m_mouseButtonDownCounter) { ::ReleaseCapture(); } break; } // get screen coords POINT ptAbs = pt; if (type == com_sun_glass_events_MouseEvent_WHEEL) { ::ScreenToClient(hwnd, &pt); } else { ::ClientToScreen(hwnd, &ptAbs); } // unmirror the x coordinate LONG style = ::GetWindowLong(hwnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hwnd, &rect); pt.x = max(0, rect.right - rect.left) - pt.x; } jint jModifiers = GetModifiers(); const jboolean isSynthesized = jboolean(IsTouchEvent()); JNIEnv *env = GetEnv(); if (!m_bTrackingMouse && type != com_sun_glass_events_MouseEvent_EXIT) { TRACKMOUSEEVENT trackData; trackData.cbSize = sizeof(trackData); trackData.dwFlags = TME_LEAVE; trackData.hwndTrack = hwnd; trackData.dwHoverTime = HOVER_DEFAULT; if (::TrackMouseEvent(&trackData)) { // Mouse tracking will be canceled automatically upon receiving WM_MOUSELEAVE m_bTrackingMouse = TRUE; } // Note that (ViewContainer*)this != (BaseWnd*)this. We could use // dynamic_case<>() instead, but it would fail later if 'this' is // already deleted. So we use FromHandle() which is safe. const BaseWnd *origWnd = BaseWnd::FromHandle(hwnd); env->CallVoidMethod(GetView(), javaIDs.View.notifyMouse, com_sun_glass_events_MouseEvent_ENTER, com_sun_glass_events_MouseEvent_BUTTON_NONE, pt.x, pt.y, ptAbs.x, ptAbs.y, jModifiers, JNI_FALSE, isSynthesized); CheckAndClearException(env); // At this point 'this' might have already been deleted if the app // closed the window while processing the ENTER event. Hence the check: if (!::IsWindow(hwnd) || BaseWnd::FromHandle(hwnd) != origWnd || !GetGlassView()) { return TRUE; } } switch (type) { case com_sun_glass_events_MouseEvent_DOWN: GlassDropSource::SetDragButton(button); break; case com_sun_glass_events_MouseEvent_UP: GlassDropSource::SetDragButton(0); break; } if (type == com_sun_glass_events_MouseEvent_WHEEL) { jdouble dx, dy; if (msg == WM_MOUSEHWHEEL) { // native horizontal scroll // Negate the value to be more "natural" dx = -wheelRotation; dy = 0.0; } else if (msg == WM_MOUSEWHEEL && LOWORD(wParam) & MK_SHIFT) { // Do not negate the emulated horizontal scroll amount dx = wheelRotation; dy = 0.0; } else { // vertical scroll dx = 0.0; dy = wheelRotation; } jint ls, cs; UINT val = 0; ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &val, 0); ls = (jint)val; val = 0; ::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &val, 0); cs = (jint)val; env->CallVoidMethod(GetView(), javaIDs.View.notifyScroll, pt.x, pt.y, ptAbs.x, ptAbs.y, dx, dy, jModifiers, ls, cs, 3, 3, (jdouble)40.0, (jdouble)40.0); } else { env->CallVoidMethod(GetView(), javaIDs.View.notifyMouse, type, button, pt.x, pt.y, ptAbs.x, ptAbs.y, jModifiers, type == com_sun_glass_events_MouseEvent_UP && button == com_sun_glass_events_MouseEvent_BUTTON_RIGHT, isSynthesized); } CheckAndClearException(env); return TRUE; } void ViewContainer::NotifyCaptureChanged(HWND hwnd, HWND to) { m_mouseButtonDownCounter = 0; } void ViewContainer::ResetMouseTracking(HWND hwnd) { if (!m_bTrackingMouse) { return; } // We don't expect WM_MOUSELEAVE anymore, so we cancel mouse tracking manually TRACKMOUSEEVENT trackData; trackData.cbSize = sizeof(trackData); trackData.dwFlags = TME_LEAVE | TME_CANCEL; trackData.hwndTrack = hwnd; trackData.dwHoverTime = HOVER_DEFAULT; ::TrackMouseEvent(&trackData); m_bTrackingMouse = FALSE; if (!GetGlassView()) { return; } POINT ptAbs; ::GetCursorPos(&ptAbs); POINT pt = ptAbs; ::ScreenToClient(hwnd, &pt); // unmirror the x coordinate LONG style = ::GetWindowLong(hwnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hwnd, &rect); pt.x = max(0, rect.right - rect.left) - pt.x; } JNIEnv *env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyMouse, com_sun_glass_events_MouseEvent_EXIT, 0, pt.x, pt.y, ptAbs.x, ptAbs.y, GetModifiers(), JNI_FALSE, JNI_FALSE); CheckAndClearException(env); } BOOL ViewContainer::HandleViewInputMethodEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { GlassView* gv = GetGlassView(); if (!gv) { return FALSE; } switch (msg) { case WM_IME_ENDCOMPOSITION: SendInputMethodEvent(NULL, 0, NULL, 0, NULL, NULL, 0, 0, 0); case WM_IME_STARTCOMPOSITION: return gv->IsInputMethodEventEnabled(); case WM_IME_COMPOSITION: if (gv->IsInputMethodEventEnabled()) { WmImeComposition(hwnd, wParam, lParam); return TRUE; } break; case WM_IME_NOTIFY: if (gv->IsInputMethodEventEnabled()) { WmImeNotify(hwnd, wParam, lParam); } break; default: return FALSE; } return FALSE; } void ViewContainer::WmImeComposition(HWND hwnd, WPARAM wParam, LPARAM lParam) { BOOL ret = FALSE; JNIEnv *env = GetEnv(); int* bndClauseW = NULL; int* bndAttrW = NULL; BYTE* valAttrW = NULL; int cClauseW = 0; GlassInputTextInfo textInfo = GlassInputTextInfo(this); HIMC hIMC = ImmGetContext(hwnd); ASSERT(hIMC!=0); try { textInfo.GetContextData(hIMC, lParam); jstring jtextString = textInfo.GetText(); if ((lParam & GCS_RESULTSTR && jtextString != NULL) || (lParam & GCS_COMPSTR)) { int cursorPosW = textInfo.GetCursorPosition(); int cAttrW = textInfo.GetAttributeInfo(bndAttrW, valAttrW); cClauseW = textInfo.GetClauseInfo(bndClauseW); SendInputMethodEvent(jtextString, cClauseW, bndClauseW, cAttrW, bndAttrW, valAttrW, textInfo.GetCommittedTextLength(), cursorPosW, cursorPosW); } ImmReleaseContext(hwnd, hIMC); } catch (...) { // since GetClauseInfo and GetAttributeInfo could throw exception, we have to release // the pointer here. delete [] bndClauseW; delete [] bndAttrW; delete [] valAttrW; ImmReleaseContext(hwnd, hIMC); throw; } /* Free the storage allocated. Since jtextString won't be passed from threads * to threads, we just use the local ref and it will be deleted within the destructor * of GlassInputTextInfo object. */ delete [] bndClauseW; delete [] bndAttrW; delete [] valAttrW; CheckAndClearException(env); } void ViewContainer::WmImeNotify(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (wParam == IMN_OPENCANDIDATE || wParam == IMN_CHANGECANDIDATE) { JNIEnv *env = GetEnv(); POINT curPos; UINT bits = 1; HIMC hIMC = ImmGetContext(hwnd); CANDIDATEFORM cf; GetCandidatePos(&curPos); ::ScreenToClient(hwnd, &curPos); for (int iCandType=0; iCandType<32; iCandType++, bits<<=1) { if (lParam & bits) { cf.dwIndex = iCandType; cf.dwStyle = CFS_CANDIDATEPOS; // The constant offset is needed because Windows is moving the IM window cf.ptCurrentPos.x = curPos.x - 6; cf.ptCurrentPos.y = curPos.y - 15; ::ImmSetCandidateWindow(hIMC, &cf); } } ImmReleaseContext(hwnd, hIMC); } } // // generate and post InputMethodEvent // void ViewContainer::SendInputMethodEvent(jstring text, int cClause, int* rgClauseBoundary, int cAttrBlock, int* rgAttrBoundary, BYTE *rgAttrValue, int commitedTextLength, int caretPos, int visiblePos) { JNIEnv *env = GetEnv(); // assumption for array type casting ASSERT(sizeof(int)==sizeof(jint)); ASSERT(sizeof(BYTE)==sizeof(jbyte)); // caluse information jintArray clauseBoundary = NULL; if (cClause && rgClauseBoundary) { // convert clause boundary offset array to java array clauseBoundary = env->NewIntArray(cClause+1); if (clauseBoundary) { env->SetIntArrayRegion(clauseBoundary, 0, cClause+1, (jint *)rgClauseBoundary); CheckAndClearException(env); } } // attribute information jintArray attrBoundary = NULL; jbyteArray attrValue = NULL; if (cAttrBlock && rgAttrBoundary && rgAttrValue) { // convert attribute boundary offset array to java array attrBoundary = env->NewIntArray(cAttrBlock+1); if (attrBoundary) { env->SetIntArrayRegion(attrBoundary, 0, cAttrBlock+1, (jint *)rgAttrBoundary); CheckAndClearException(env); } // convert attribute value byte array to java array attrValue = env->NewByteArray(cAttrBlock); if (attrValue) { env->SetByteArrayRegion(attrValue, 0, cAttrBlock, (jbyte *)rgAttrValue); CheckAndClearException(env); } } env->CallBooleanMethod(GetView(), javaIDs.View.notifyInputMethod, text, clauseBoundary, attrBoundary, attrValue, commitedTextLength, caretPos, visiblePos); CheckAndClearException(env); if (clauseBoundary) { env->DeleteLocalRef(clauseBoundary); } if (attrBoundary) { env->DeleteLocalRef(attrBoundary); } if (attrValue) { env->DeleteLocalRef(attrValue); } } // Gets the candidate position void ViewContainer::GetCandidatePos(LPPOINT curPos) { JNIEnv *env = GetEnv(); double* nativePos; jdoubleArray pos = (jdoubleArray)env->CallObjectMethod(GetView(), javaIDs.View.notifyInputMethodCandidatePosRequest, 0); nativePos = env->GetDoubleArrayElements(pos, NULL); if (nativePos) { curPos->x = (int)nativePos[0]; curPos->y = (int)nativePos[1]; env->ReleaseDoubleArrayElements(pos, nativePos, 0); } } namespace { class AutoTouchInputHandle { HTOUCHINPUT m_h; private: AutoTouchInputHandle(const AutoTouchInputHandle&); AutoTouchInputHandle& operator=(const AutoTouchInputHandle&); public: explicit AutoTouchInputHandle(LPARAM lParam): m_h((HTOUCHINPUT)lParam) { } ~AutoTouchInputHandle() { if (m_h) { ::CloseTouchInputHandle(m_h); } } operator HTOUCHINPUT() const { return m_h; } }; static BOOL debugTouch = false; static char * touchEventName(unsigned int dwFlags) { if (dwFlags & TOUCHEVENTF_MOVE) { return "MOVE"; } if (dwFlags & TOUCHEVENTF_DOWN) { return "PRESS"; } if (dwFlags & TOUCHEVENTF_UP) { return "RELEASE"; } return "UNKOWN"; } void NotifyTouchInput( HWND hWnd, jobject view, jclass gestureSupportCls, const TOUCHINPUT* ti, unsigned count) { JNIEnv *env = GetEnv(); // TBD: set to 'true' if source device is a touch screen // and to 'false' if source device is a touch pad. // So far assume source device on Windows is always a touch screen. const bool isDirect = true; jint modifiers = GetModifiers(); env->CallStaticObjectMethod(gestureSupportCls, javaIDs.Gestures.notifyBeginTouchEventMID, view, modifiers, jboolean(isDirect), jint(count)); CheckAndClearException(env); for (; count; --count, ++ti) { jlong touchID = jlong(ti->dwID); jint eventID = 0; if (ti->dwFlags & TOUCHEVENTF_MOVE) { eventID = com_sun_glass_events_TouchEvent_TOUCH_MOVED; } if (ti->dwFlags & TOUCHEVENTF_DOWN) { eventID = com_sun_glass_events_TouchEvent_TOUCH_PRESSED; } if (ti->dwFlags & TOUCHEVENTF_UP) { eventID = com_sun_glass_events_TouchEvent_TOUCH_RELEASED; } POINT screen; POINT client; client.x = screen.x = LONG(ti->x / 100); client.y = screen.y = LONG(ti->y / 100); ScreenToClient(hWnd, &client); // unmirror the x coordinate LONG style = ::GetWindowLong(hWnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hWnd, &rect); client.x = max(0, rect.right - rect.left) - client.x; } env->CallStaticObjectMethod(gestureSupportCls, javaIDs.Gestures.notifyNextTouchEventMID, view, eventID, touchID, jint(client.x), jint(client.y), jint(screen.x), jint(screen.y)); CheckAndClearException(env); } env->CallStaticObjectMethod( gestureSupportCls, javaIDs.Gestures.notifyEndTouchEventMID, view); CheckAndClearException(env); } void NotifyManipulationProcessor( IManipulationProcessor& manipProc, const TOUCHINPUT* ti, unsigned count) { for (; count; --count, ++ti) { if (ti->dwFlags & TOUCHEVENTF_DOWN) { manipProc.ProcessDownWithTime(ti->dwID, FLOAT(ti->x), FLOAT(ti->y), ti->dwTime); } if (ti->dwFlags & TOUCHEVENTF_MOVE) { manipProc.ProcessMoveWithTime(ti->dwID, FLOAT(ti->x), FLOAT(ti->y), ti->dwTime); } if (ti->dwFlags & TOUCHEVENTF_UP) { manipProc.ProcessUpWithTime(ti->dwID, FLOAT(ti->x), FLOAT(ti->y), ti->dwTime); } } } } // namespace unsigned int ViewContainer::HandleViewTouchEvent( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { const UINT newCount = static_cast<UINT>(LOWORD(wParam)); TOUCHINPUT * tempTouchInputBuf; unsigned int bufsz = newCount > 10 ? newCount : 10; if (m_thisTouchInputBuf.size() < bufsz) { m_thisTouchInputBuf.resize(bufsz); } if (newCount > 0) { tempTouchInputBuf = new TOUCHINPUT[newCount]; do { AutoTouchInputHandle inputInfo(lParam); if (!::GetTouchInputInfo(inputInfo, newCount, tempTouchInputBuf, sizeof(TOUCHINPUT))) { delete [] tempTouchInputBuf; return 0; } } while(0); // scope for 'inputInfo' } // Fix up the touch point stream. Some drivers seem to lose touch events, // dropping PRESS, MOVE, UP, so we need to add them back in. unsigned int activeCount = 0; unsigned int pointsCount = 0; // check first for any "lost" touches // these need to get added to the send list of points for (unsigned int i = 0 ; i < m_lastTouchInputCount; i++) { if (!(m_lastTouchInputBuf[i].dwFlags & TOUCHEVENTF_UP)) { // looking for a dwID that is // not present in the new batch // was not UP in the old batch bool found = false; for (unsigned int j = 0; j < newCount; j++) { if (m_lastTouchInputBuf[i].dwID == tempTouchInputBuf[j].dwID) { found = true; //break; } } if (!found) { // We have a old event but not a new one, so release it m_thisTouchInputBuf[pointsCount].dwFlags = TOUCHEVENTF_UP; m_thisTouchInputBuf[pointsCount].dwID = m_lastTouchInputBuf[i].dwID; m_thisTouchInputBuf[pointsCount].x = m_lastTouchInputBuf[i].x; m_thisTouchInputBuf[pointsCount].y = m_lastTouchInputBuf[i].y; if (newCount > 0) { //use the time of the first new element for our inserted event m_thisTouchInputBuf[pointsCount].dwTime = tempTouchInputBuf[0].dwTime; } else { m_thisTouchInputBuf[pointsCount].dwTime = m_lastTouchInputBuf[i].dwTime; } m_thisTouchInputBuf[pointsCount].dwMask = m_lastTouchInputBuf[i].dwMask; if (debugTouch) { printf("TOUCH FIX UP %d, %s\n", m_lastTouchInputBuf[i].dwID, touchEventName(m_lastTouchInputBuf[i].dwFlags)); } pointsCount++; } } } if (pointsCount + newCount > m_thisTouchInputBuf.size()) { bufsz = pointsCount + newCount; m_thisTouchInputBuf.resize(bufsz); } // now fold in the current touch points for (unsigned int i = 0 ; i < newCount; i++) { bool found = false; for (unsigned int j = 0 ; j < m_lastTouchInputCount; j++) { if (m_lastTouchInputBuf[j].dwID == tempTouchInputBuf[i].dwID) { found = true; break; } } m_thisTouchInputBuf[pointsCount].dwFlags = tempTouchInputBuf[i].dwFlags; m_thisTouchInputBuf[pointsCount].dwID = tempTouchInputBuf[i].dwID; m_thisTouchInputBuf[pointsCount].dwTime = tempTouchInputBuf[i].dwTime; m_thisTouchInputBuf[pointsCount].dwMask = tempTouchInputBuf[i].dwMask; m_thisTouchInputBuf[pointsCount].x = tempTouchInputBuf[i].x; m_thisTouchInputBuf[pointsCount].y = tempTouchInputBuf[i].y; if (m_thisTouchInputBuf[pointsCount].dwFlags & TOUCHEVENTF_DOWN) { pointsCount++; activeCount ++; } else if (m_thisTouchInputBuf[pointsCount].dwFlags & TOUCHEVENTF_MOVE) { if (!found) { if (debugTouch) { printf("TOUCH FIX MV->DOWN %d, %s\n", m_thisTouchInputBuf[pointsCount].dwID, touchEventName(m_thisTouchInputBuf[pointsCount].dwFlags)); } m_thisTouchInputBuf[pointsCount].dwFlags = TOUCHEVENTF_DOWN; } pointsCount++; activeCount ++; } else if (m_thisTouchInputBuf[pointsCount].dwFlags & TOUCHEVENTF_UP) { if (found) { pointsCount++; } else { // UP without a previous DOWN, ignore it } } } if (debugTouch) { printf("Touch Sequence %d/%d win=%d view=%d %d,%d,%d\n",pointsCount,activeCount, hWnd, GetView(), m_lastTouchInputCount, newCount, pointsCount); for (unsigned int i = 0 ; i < m_lastTouchInputCount; i++) { printf(" old %d, %s\n", m_lastTouchInputBuf[i].dwID, touchEventName(m_lastTouchInputBuf[i].dwFlags)); } for (unsigned int i = 0 ; i < newCount; i++) { printf(" in %d, %s\n", tempTouchInputBuf[i].dwID, touchEventName(tempTouchInputBuf[i].dwFlags)); } for (unsigned int i = 0 ; i < pointsCount; i++) { printf(" this %d, %d\n", m_thisTouchInputBuf[i].dwID, m_thisTouchInputBuf[i].dwFlags & 0x07); } printf(" ---\n"); fflush(stdout); } if (pointsCount > 0) { NotifyTouchInput(hWnd, GetView(), m_gestureSupportCls, &m_thisTouchInputBuf[0], pointsCount); if (m_manipProc) { NotifyManipulationProcessor(*m_manipProc, &m_thisTouchInputBuf[0], pointsCount); } std::swap(m_lastTouchInputBuf, m_thisTouchInputBuf); m_lastTouchInputCount = pointsCount; } if ( newCount > 0) { delete [] tempTouchInputBuf; } return activeCount; } void ViewContainer::HandleViewTimerEvent(HWND hwnd, UINT_PTR timerID) { if (IDT_GLASS_INERTIAPROCESSOR == timerID) { BOOL completed = FALSE; HRESULT hr = m_inertiaProc->Process(&completed); if (SUCCEEDED(hr) && completed) { StopTouchInputInertia(hwnd); JNIEnv *env = GetEnv(); env->CallStaticVoidMethod(m_gestureSupportCls, javaIDs.Gestures.inertiaGestureFinishedMID, GetView()); CheckAndClearException(env); } } } void ViewContainer::NotifyGesturePerformed(HWND hWnd, bool isDirect, bool isInertia, FLOAT x, FLOAT y, FLOAT deltaX, FLOAT deltaY, FLOAT scaleDelta, FLOAT expansionDelta, FLOAT rotationDelta, FLOAT cumulativeDeltaX, FLOAT cumulativeDeltaY, FLOAT cumulativeScale, FLOAT cumulativeExpansion, FLOAT cumulativeRotation) { JNIEnv *env = GetEnv(); POINT screen; screen.x = LONG((x + 0.5) / 100); screen.y = LONG((y + 0.5) / 100); POINT client; client.x = screen.x; client.y = screen.y; ScreenToClient(hWnd, &client); // unmirror the x coordinate LONG style = ::GetWindowLong(hWnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hWnd, &rect); client.x = max(0, rect.right - rect.left) - client.x; } jint modifiers = GetModifiers(); env->CallStaticVoidMethod(m_gestureSupportCls, javaIDs.Gestures.gesturePerformedMID, GetView(), modifiers, jboolean(isDirect), jboolean(isInertia), jint(client.x), jint(client.y), jint(screen.x), jint(screen.y), deltaX / 100, deltaY / 100, cumulativeDeltaX / 100, cumulativeDeltaY / 100, cumulativeScale, cumulativeExpansion / 100, cumulativeRotation); CheckAndClearException(env); } void ViewContainer::StartTouchInputInertia(HWND hwnd) { // TBD: check errors // // Collect initial inertia data // FLOAT vX, vY; m_manipProc->GetVelocityX(&vX); m_manipProc->GetVelocityY(&vY); const FLOAT VELOCITY_THRESHOLD = 10.0f; if (fabs(vX) < VELOCITY_THRESHOLD && fabs(vY) < VELOCITY_THRESHOLD) { return; } // TBD: check errors POINT origin; GetCursorPos(&origin); // // Setup inertia. // m_inertiaProc->Reset(); m_inertiaProc->put_DesiredDeceleration(0.23f); // Set initial origins. m_inertiaProc->put_InitialOriginX(origin.x * 100.0f); m_inertiaProc->put_InitialOriginY(origin.y * 100.0f); // Set initial velocities. m_inertiaProc->put_InitialVelocityX(vX); m_inertiaProc->put_InitialVelocityY(vY); // TBD: check errors ::SetTimer(hwnd, IDT_GLASS_INERTIAPROCESSOR, 16, NULL); } void ViewContainer::StopTouchInputInertia(HWND hwnd) { // TBD: check errors ::KillTimer(hwnd, IDT_GLASS_INERTIAPROCESSOR); } extern "C" { JNIEXPORT void JNICALL Java_com_sun_glass_ui_win_WinGestureSupport__1initIDs( JNIEnv *env, jclass cls) { javaIDs.Gestures.gesturePerformedMID = env->GetStaticMethodID(cls, "gesturePerformed", "(Lcom/sun/glass/ui/View;IZZIIIIFFFFFFF)V"); CheckAndClearException(env); javaIDs.Gestures.inertiaGestureFinishedMID = env->GetStaticMethodID(cls, "inertiaGestureFinished", "(Lcom/sun/glass/ui/View;)V"); CheckAndClearException(env); javaIDs.Gestures.notifyBeginTouchEventMID = env->GetStaticMethodID(cls, "notifyBeginTouchEvent", "(Lcom/sun/glass/ui/View;IZI)V"); CheckAndClearException(env); javaIDs.Gestures.notifyNextTouchEventMID = env->GetStaticMethodID(cls, "notifyNextTouchEvent", "(Lcom/sun/glass/ui/View;IJIIII)V"); CheckAndClearException(env); javaIDs.Gestures.notifyEndTouchEventMID = env->GetStaticMethodID(cls, "notifyEndTouchEvent", "(Lcom/sun/glass/ui/View;)V"); CheckAndClearException(env); } } // extern "C"
teamfx/openjfx-9-dev-rt
modules/javafx.graphics/src/main/native-glass/win/ViewContainer.cpp
C++
gpl-2.0
58,952
<?php $params = array_merge( require(__DIR__ . '/../../common/config/params.php'), require(__DIR__ . '/../../common/config/params-local.php'), require(__DIR__ . '/params.php'), require(__DIR__ . '/params-local.php') ); return [ 'id' => 'app-frontend', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'controllerNamespace' => 'frontend\controllers', 'components' => [ 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'i18n' => [ 'translations' => [ 'app*' => [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => '@frontend/messages', 'sourceLanguage' => 'en', 'fileMap' => [ 'app' => 'app.php', 'app/tag' => 'tag.php', 'app/poll' => 'poll.php', 'app/user' => 'user.php', 'app/form' => 'form.php', 'app/content' => 'content.php', ], ], ], ], ], 'params' => $params, ];
cangsalak/Yii2-CMS
frontend/config/main.php
PHP
gpl-2.0
1,425
<div class="metabox-holder indeed"> <div class="stuffbox"> <div class="ism-top-message"><b>"Share Bar"</b> - is a special Social Icons Display on the top of the page when the visitor scroll down.</div> </div> <div class="stuffbox"> <h3> <label style="font-size:16px;"> AddOn Status </label> </h3> <div class="inside"> <div class="submit" style="float:left; width:80%;"> This AddOn is not installed into your system. To use this section you need to install and activate the "Social Share Bar Display" AddOn. </div> <div class="submit" style="float:left; width:20%; text-align:center;"> </div> <div class="clear"></div> </div> </div> <div class="stuffbox"> <h3> <label style="font-size:16px;"> AddOn Details </label> </h3> <div class="inside"> <div class="ism_not_item"> <?php if($_GET['tab'] == 'isb'){ $url = 'http://codecanyon.net/item/social-share-on-images-addon-wordpress/9719076'; $html = file_get_contents($url); $get1 = explode( '<div class="item-preview">' , $html ); $get2 = explode( '</div>' , $get1[1] ); preg_match_all('/<img.*?>/', $get2[0], $out); if(isset($out) && count($out) > 0){ foreach($out as $value){ echo '<div class="top-preview">'.$value[0].'</div>'; } } $get3 = explode( '<div class="user-html">' , $html ); $get4 = explode( '</div>' , $get3[1] ); preg_match_all('/<img.*?>/', $get4[0], $images); if(isset($images) && count($images) > 0){ foreach($images as $img){ foreach($img as $value){ if (strpos($value,'preview') === false && strpos($value,'button') === false) echo $value; } } } } ?> </div> <div class="clear"></div> </div> </div> </div> </div>
srwiser/ssctube
wp-content/plugins/indeed-social-media_v5.1/admin/tabs/isb.php
PHP
gpl-2.0
1,740
<?php function getSentNotificationNum() { return intval(file_get_contents('http://localhost:55555/')); } ?>
marco-c/wp-web-push
tests/test-utils.php
PHP
gpl-2.0
112
/** * @fileoverview * Tool '서식' Source, * */ TrexConfig.addTool( "tabletemplate", { sync: _FALSE, status: _TRUE, rows: 5, cols: 9, options: [ { label: 'image', data: 1 , klass: 'tx-tabletemplate-1' }, { label: 'image', data: 2 , klass: 'tx-tabletemplate-2' }, { label: 'image', data: 3 , klass: 'tx-tabletemplate-3' }, { label: 'image', data: 4 , klass: 'tx-tabletemplate-4' }, { label: 'image', data: 5 , klass: 'tx-tabletemplate-5' }, { label: 'image', data: 6 , klass: 'tx-tabletemplate-6' }, { label: 'image', data: 7 , klass: 'tx-tabletemplate-7' }, { label: 'image', data: 8 , klass: 'tx-tabletemplate-8' }, { label: 'image', data: 9 , klass: 'tx-tabletemplate-9' }, { label: 'image', data: 10 , klass: 'tx-tabletemplate-10' }, { label: 'image', data: 11 , klass: 'tx-tabletemplate-11' }, { label: 'image', data: 12 , klass: 'tx-tabletemplate-12' }, { label: 'image', data: 13 , klass: 'tx-tabletemplate-13' }, { label: 'image', data: 14 , klass: 'tx-tabletemplate-14' }, { label: 'image', data: 15 , klass: 'tx-tabletemplate-15' }, { label: 'image', data: 16 , klass: 'tx-tabletemplate-16' }, { label: 'image', data: 17 , klass: 'tx-tabletemplate-17' }, { label: 'image', data: 18 , klass: 'tx-tabletemplate-18' }, { label: 'image', data: 19 , klass: 'tx-tabletemplate-19' }, { label: 'image', data: 20 , klass: 'tx-tabletemplate-20' }, { label: 'image', data: 21 , klass: 'tx-tabletemplate-21' }, { label: 'image', data: 22 , klass: 'tx-tabletemplate-22' }, { label: 'image', data: 23 , klass: 'tx-tabletemplate-23' }, { label: 'image', data: 24 , klass: 'tx-tabletemplate-24' }, { label: 'image', data: 25 , klass: 'tx-tabletemplate-25' }, { label: 'image', data: 26 , klass: 'tx-tabletemplate-26' }, { label: 'image', data: 27 , klass: 'tx-tabletemplate-27' }, { label: 'image', data: 28 , klass: 'tx-tabletemplate-28' }, { label: 'image', data: 29 , klass: 'tx-tabletemplate-29' }, { label: 'image', data: 30 , klass: 'tx-tabletemplate-30' }, { label: 'image', data: 31 , klass: 'tx-tabletemplate-31' }, { label: 'image', data: 32 , klass: 'tx-tabletemplate-32' }, { label: 'image', data: 33 , klass: 'tx-tabletemplate-33' }, { label: 'image', data: 34 , klass: 'tx-tabletemplate-34' }, { label: 'image', data: 35 , klass: 'tx-tabletemplate-35' }, { label: 'image', data: 36 , klass: 'tx-tabletemplate-36' }, { label: 'image', data: 37 , klass: 'tx-tabletemplate-37' }, { label: 'image', data: 38 , klass: 'tx-tabletemplate-38' }, { label: 'image', data: 39 , klass: 'tx-tabletemplate-39' }, { label: 'image', data: 40 , klass: 'tx-tabletemplate-40' }, { label: 'image', data: 41 , klass: 'tx-tabletemplate-41' }, { label: 'image', data: 42 , klass: 'tx-tabletemplate-42' }, { label: 'image', data: 43 , klass: 'tx-tabletemplate-43' }, { label: 'image', data: 44 , klass: 'tx-tabletemplate-44' }, { label: 'image', data: 45 , klass: 'tx-tabletemplate-45' } ] } ); Trex.Tool.Tabletemplate = Trex.Class.create({ $const: { __Identity: 'tabletemplate' }, $extend: Trex.Tool, oninitialized: function(config) { var _tool = this; var _canvas = this.canvas; var _map = {}; config.options.each(function(option) { _map[option.data] = { type: option.type }; }); var _toolHandler = function(data) { if(!_map[data]) { return; } var _table = _NULL; _canvas.execute(function(processor) { if (processor.table) { _table = processor.findNode('table'); processor.table.setTemplateStyle(_table, data); } }); }; /* button & menu weave */ this.weave.bind(this)( /* button */ new Trex.Button(this.buttonCfg), /* menu */ new Trex.Menu.List(this.menuCfg), /* handler */ _toolHandler ); } });
zaljayo/TestProject
lib_editor/js/trex/tool/tabletemplate.js
JavaScript
gpl-2.0
3,877
#include "GitRevision.h" #include "CompilerDefs.h" #include "revision_data.h" char const* GitRevision::GetHash() { return _HASH; } char const* GitRevision::GetDate() { return _DATE; } char const* GitRevision::GetBranch() { return _BRANCH; } char const* GitRevision::GetSourceDirectory() { return _SOURCE_DIRECTORY; } char const* GitRevision::GetMySQLExecutable() { return _MYSQL_EXECUTABLE; } char const* GitRevision::GetFullDatabase() { return _FULL_DATABASE; } char const* GitRevision::GetHotfixesDatabase() { return _HOTFIXES_DATABASE; } #define _PACKAGENAME "TrinityCore" char const* GitRevision::GetFullVersion() { #if PLATFORM == PLATFORM_WINDOWS # ifdef _WIN64 return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Win64, " _BUILD_DIRECTIVE ")"; # else return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Win32, " _BUILD_DIRECTIVE ")"; # endif #else return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Unix, " _BUILD_DIRECTIVE ")"; #endif } char const* GitRevision::GetCompanyNameStr() { return VER_COMPANYNAME_STR; } char const* GitRevision::GetLegalCopyrightStr() { return VER_LEGALCOPYRIGHT_STR; } char const* GitRevision::GetFileVersionStr() { return VER_FILEVERSION_STR; } char const* GitRevision::GetProductVersionStr() { return VER_PRODUCTVERSION_STR; }
pizcogirl/TrinityCore
src/server/shared/GitRevision.cpp
C++
gpl-2.0
1,344
<?php namespace TYPO3\CMS\Core\Resource\Driver; /** * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Class AbstractHierarchicalFilesystemDriver */ abstract class AbstractHierarchicalFilesystemDriver extends AbstractDriver { /** * Wrapper for \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr() * * @param string $theFile Filepath to evaluate * @return boolean TRUE if no '/', '..' or '\' is in the $theFile * @see \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr() */ protected function isPathValid($theFile) { return \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr($theFile); } /** * Makes sure the Path given as parameter is valid * * @param string $filePath The file path (including the file name!) * @return string * @throws \TYPO3\CMS\Core\Resource\Exception\InvalidPathException */ protected function canonicalizeAndCheckFilePath($filePath) { $filePath = \TYPO3\CMS\Core\Utility\PathUtility::getCanonicalPath($filePath); // filePath must be valid // Special case is required by vfsStream in Unit Test context if (!$this->isPathValid($filePath) && substr($filePath, 0, 6) !== 'vfs://') { throw new \TYPO3\CMS\Core\Resource\Exception\InvalidPathException('File ' . $filePath . ' is not valid (".." and "//" is not allowed in path).', 1320286857); } return $filePath; } /** * Makes sure the Path given as parameter is valid * * @param string $fileIdentifier The file path (including the file name!) * @return string * @throws \TYPO3\CMS\Core\Resource\Exception\InvalidPathException */ protected function canonicalizeAndCheckFileIdentifier($fileIdentifier) { if ($fileIdentifier !== '') { $fileIdentifier = $this->canonicalizeAndCheckFilePath($fileIdentifier); $fileIdentifier = '/' . ltrim($fileIdentifier, '/'); if (!$this->isCaseSensitiveFileSystem()) { $fileIdentifier = strtolower($fileIdentifier); } } return $fileIdentifier; } /** * Makes sure the Path given as parameter is valid * * @param string $folderPath The file path (including the file name!) * @return string */ protected function canonicalizeAndCheckFolderIdentifier($folderPath) { if ($folderPath === '/') { $canonicalizedIdentifier = $folderPath; } else { $canonicalizedIdentifier = rtrim($this->canonicalizeAndCheckFileIdentifier($folderPath), '/') . '/'; } return $canonicalizedIdentifier; } /** * Returns the identifier of the folder the file resides in * * @param string $fileIdentifier * @return mixed */ public function getParentFolderIdentifierOfIdentifier($fileIdentifier) { $fileIdentifier = $this->canonicalizeAndCheckFileIdentifier($fileIdentifier); return \TYPO3\CMS\Core\Utility\PathUtility::dirname($fileIdentifier) . '/'; } }
demonege/sutogo
typo3/sysext/core/Classes/Resource/Driver/AbstractHierarchicalFilesystemDriver.php
PHP
gpl-2.0
3,140
/** -*- c++ -*- * Copyright (C) 2008 Doug Judd (Zvents, 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 2 of the * License, or any later version. * * 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 <cassert> #include <cstdio> #include <cstring> #include <boost/progress.hpp> #include <boost/timer.hpp> #include <boost/thread/xtime.hpp> extern "C" { #include <time.h> } #include "AsyncComm/DispatchHandlerSynchronizer.h" #include "Common/Error.h" #include "Common/FileUtils.h" #include "Hypertable/Lib/HqlHelpText.h" #include "Hypertable/Lib/HqlParser.h" #include "Hypertable/Lib/Key.h" #include "Hypertable/Lib/LoadDataSource.h" #include "Hypertable/Lib/RangeState.h" #include "Hypertable/Lib/ScanBlock.h" #include "Hypertable/Lib/ScanSpec.h" #include "Hypertable/Lib/TestSource.h" #include "RangeServerCommandInterpreter.h" #define BUFFER_SIZE 65536 using namespace std; using namespace Hypertable; using namespace Hql; using namespace Serialization; namespace { void process_event(EventPtr &event_ptr) { int32_t error; const uint8_t *decode_ptr = event_ptr->payload + 4; size_t decode_remain = event_ptr->payload_len - 4; uint32_t offset, len; if (decode_remain == 0) cout << "success" << endl; else { while (decode_remain) { try { error = decode_i32(&decode_ptr, &decode_remain); offset = decode_i32(&decode_ptr, &decode_remain); len = decode_i32(&decode_ptr, &decode_remain); } catch (Exception &e) { HT_ERROR_OUT << e << HT_END; break; } cout << "rejected: offset=" << offset << " span=" << len << " " << Error::get_text(error) << endl; } } } } RangeServerCommandInterpreter::RangeServerCommandInterpreter(Comm *comm, Hyperspace::SessionPtr &hyperspace_ptr, const sockaddr_in addr, RangeServerClientPtr &range_server_ptr) : m_comm(comm), m_hyperspace_ptr(hyperspace_ptr), m_addr(addr), m_range_server_ptr(range_server_ptr), m_cur_scanner_id(-1) { HqlHelpText::install_range_server_client_text(); return; } void RangeServerCommandInterpreter::execute_line(const String &line) { TableIdentifier *table = 0; RangeSpec range; TableInfo *table_info; String schema_str; String out_str; SchemaPtr schema_ptr; Hql::ParserState state; Hql::Parser parser(state); parse_info<> info; DispatchHandlerSynchronizer sync_handler; ScanBlock scanblock; int32_t scanner_id; EventPtr event_ptr; info = parse(line.c_str(), parser, space_p); if (info.full) { // if table name specified, get associated objects if (state.table_name != "") { table_info = m_table_map[state.table_name]; if (table_info == 0) { table_info = new TableInfo(state.table_name); table_info->load(m_hyperspace_ptr); m_table_map[state.table_name] = table_info; } table = table_info->get_table_identifier(); table_info->get_schema_ptr(schema_ptr); } // if end row is "??", transform it to 0xff 0xff if (state.range_end_row == "??") state.range_end_row = Key::END_ROW_MARKER; if (state.command == COMMAND_LOAD_RANGE) { RangeState range_state; cout << "TableName = " << state.table_name << endl; cout << "StartRow = " << state.range_start_row << endl; cout << "EndRow = " << state.range_end_row << endl; range.start_row = state.range_start_row.c_str(); range.end_row = state.range_end_row.c_str(); range_state.soft_limit = 200000000LL; m_range_server_ptr->load_range(m_addr, *table, range, 0, range_state, 0); } else if (state.command == COMMAND_UPDATE) { TestSource *tsource = 0; if (!FileUtils::exists(state.input_file.c_str())) HT_THROW(Error::FILE_NOT_FOUND, String("Input file '") + state.input_file + "' does not exist"); tsource = new TestSource(state.input_file, schema_ptr.get()); uint8_t *send_buf = 0; size_t send_buf_len = 0; DynamicBuffer buf(BUFFER_SIZE); SerializedKey key; ByteString value; size_t key_len, value_len; uint32_t send_count = 0; bool outstanding = false; while (true) { while (tsource->next(key, value)) { key_len = key.length(); value_len = value.length(); buf.ensure(key_len + value_len); buf.add_unchecked(key.ptr, key_len); buf.add_unchecked(value.ptr, value_len); if (buf.fill() > BUFFER_SIZE) break; } /** * Sort the keys */ if (buf.fill()) { std::vector<SerializedKey> keys; const uint8_t *ptr; size_t len; key.ptr = ptr = buf.base; while (ptr < buf.ptr) { keys.push_back(key); key.next(); key.next(); ptr = key.ptr; } std::sort(keys.begin(), keys.end()); send_buf = new uint8_t [buf.fill()]; uint8_t *sendp = send_buf; for (size_t i=0; i<keys.size(); i++) { key = keys[i]; key.next(); key.next(); len = key.ptr - keys[i].ptr; memcpy(sendp, keys[i].ptr, len); sendp += len; } send_buf_len = sendp - send_buf; buf.clear(); send_count = keys.size(); } else { send_buf_len = 0; send_count = 0; } if (outstanding) { if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); process_event(event_ptr); } outstanding = false; if (send_buf_len > 0) { StaticBuffer mybuf(send_buf, send_buf_len); m_range_server_ptr->update(m_addr, *table, send_count, mybuf, 0, &sync_handler); outstanding = true; } else break; } if (outstanding) { if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); process_event(event_ptr); } } else if (state.command == COMMAND_CREATE_SCANNER) { range.start_row = state.range_start_row.c_str(); range.end_row = state.range_end_row.c_str(); m_range_server_ptr->create_scanner(m_addr, *table, range, state.scan.builder.get(), scanblock); m_cur_scanner_id = scanblock.get_scanner_id(); SerializedKey key; ByteString value; while (scanblock.next(key, value)) display_scan_data(key, value, schema_ptr); if (scanblock.eos()) m_cur_scanner_id = -1; } else if (state.command == COMMAND_FETCH_SCANBLOCK) { if (state.scanner_id == -1) { if (m_cur_scanner_id == -1) HT_THROW(Error::RANGESERVER_INVALID_SCANNER_ID, "No currently open scanner"); scanner_id = m_cur_scanner_id; m_cur_scanner_id = -1; } else scanner_id = state.scanner_id; /** */ m_range_server_ptr->fetch_scanblock(m_addr, scanner_id, scanblock); SerializedKey key; ByteString value; while (scanblock.next(key, value)) display_scan_data(key, value, schema_ptr); if (scanblock.eos()) m_cur_scanner_id = -1; } else if (state.command == COMMAND_DESTROY_SCANNER) { if (state.scanner_id == -1) { if (m_cur_scanner_id == -1) return; scanner_id = m_cur_scanner_id; m_cur_scanner_id = -1; } else scanner_id = state.scanner_id; m_range_server_ptr->destroy_scanner(m_addr, scanner_id); } else if (state.command == COMMAND_DROP_RANGE) { range.start_row = state.range_start_row.c_str(); range.end_row = state.range_end_row.c_str(); m_range_server_ptr->drop_range(m_addr, *table, range, &sync_handler); if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); } else if (state.command == COMMAND_REPLAY_BEGIN) { // fix me!! added metadata boolean m_range_server_ptr->replay_begin(m_addr, false, &sync_handler); if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); } else if (state.command == COMMAND_REPLAY_LOG) { cout << "Not implemented." << endl; } else if (state.command == COMMAND_DUMP) { m_range_server_ptr->dump(m_addr, state.output_file, state.nokeys); cout << "success" << endl; } else if (state.command == COMMAND_REPLAY_COMMIT) { m_range_server_ptr->replay_commit(m_addr, &sync_handler); if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); } else if (state.command == COMMAND_HELP) { const char **text = HqlHelpText::get(state.str); if (text) { for (size_t i=0; text[i]; i++) cout << text[i] << endl; } else cout << endl << "no help for '" << state.str << "'" << endl << endl; } else if (state.command == COMMAND_CLOSE) { m_range_server_ptr->close(m_addr); } else if (state.command == COMMAND_SHUTDOWN) { m_range_server_ptr->close(m_addr); m_range_server_ptr->shutdown(m_addr); } else HT_THROW(Error::HQL_PARSE_ERROR, "unsupported command"); } else HT_THROW(Error::HQL_PARSE_ERROR, String("parse error at: ") + info.stop); } /** * */ void RangeServerCommandInterpreter::display_scan_data(const SerializedKey &serkey, const ByteString &value, SchemaPtr &schema_ptr) { Key key(serkey); Schema::ColumnFamily *cf; if (key.flag == FLAG_DELETE_ROW) { cout << key.timestamp << " " << key.row << " DELETE" << endl; } else if (key.flag == FLAG_DELETE_COLUMN_FAMILY) { cf = schema_ptr->get_column_family(key.column_family_code); cout << key.timestamp << " " << key.row << " " << cf->name << " DELETE" << endl; } else { if (key.column_family_code > 0) { cf = schema_ptr->get_column_family(key.column_family_code); if (key.flag == FLAG_DELETE_CELL) cout << key.timestamp << " " << key.row << " " << cf->name << ":" << key.column_qualifier << " DELETE" << endl; else { cout << key.timestamp << " " << key.row << " " << cf->name << ":" << key.column_qualifier; cout << endl; } } else { cerr << "Bad column family (" << (int)key.column_family_code << ") for row key " << key.row; cerr << endl; } } }
tempbottle/hypertable
src/cc/Tools/rsclient/RangeServerCommandInterpreter.cc
C++
gpl-2.0
11,721
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package games.stendhal.client.gui.j2d.entity; // // import games.stendhal.client.entity.IEntity; import games.stendhal.client.sprite.Sprite; import games.stendhal.client.sprite.SpriteStore; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; /** * The 2D view of an animated entity. * * @param <T> entity type */ abstract class StateEntity2DView<T extends IEntity> extends Entity2DView<T> { /** * Log4J. */ private static final Logger logger = Logger .getLogger(StateEntity2DView.class); /** * Map of named sprites. */ protected Map<Object, Sprite> sprites = new HashMap<Object, Sprite>(); // // StateEntity2DView // /** * Build animations. * * @param entity the entity to build animations for */ private void buildAnimations(T entity) { buildSprites(entity, sprites); } /** * Populate named state sprites. * * @param entity The entity to build sprites for * @param map * The map to populate. */ protected abstract void buildSprites(T entity, final Map<Object, Sprite> map); /** * Get a keyed state sprite. * * @param state * The state. * * @return The appropriate sprite for the given state. */ protected Sprite getSprite(final Object state) { return sprites.get(state); } /** * Get the current model state. * * @param entity * @return The model state. */ protected abstract Object getState(T entity); /** * Get the current animated sprite. * * @param entity * @return The appropriate sprite for the current state. */ private Sprite getStateSprite(T entity) { final Object state = getState(entity); final Sprite sprite = getSprite(state); if (sprite == null) { logger.debug("No sprite found for: " + state); return SpriteStore.get().getFailsafe(); } return sprite; } // // Entity2DView // /** * Build the visual representation of this entity. This builds all the * animation sprites and sets the default frame. */ @Override protected void buildRepresentation(T entity) { buildAnimations(entity); setSprite(getStateSprite(entity)); } /** * Update sprite state of the entity. * * @param entity */ protected void proceedChangedState(T entity) { setSprite(getStateSprite(entity)); } }
acsid/stendhal
src/games/stendhal/client/gui/j2d/entity/StateEntity2DView.java
Java
gpl-2.0
3,163
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \*---------------------------------------------------------------------------*/ #include "meshTriangulation.H" #include "polyMesh.H" #include "faceTriangulation.H" // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // bool Foam::meshTriangulation::isInternalFace ( const primitiveMesh& mesh, const boolList& includedCell, const label faceI ) { if (mesh.isInternalFace(faceI)) { label own = mesh.faceOwner()[faceI]; label nei = mesh.faceNeighbour()[faceI]; if (includedCell[own] && includedCell[nei]) { // Neighbouring cell will get included in subset // as well so face is internal. return true; } else { return false; } } else { return false; } } void Foam::meshTriangulation::getFaces ( const primitiveMesh& mesh, const boolList& includedCell, boolList& faceIsCut, label& nFaces, label& nInternalFaces ) { // All faces to be triangulated. faceIsCut.setSize(mesh.nFaces()); faceIsCut = false; nFaces = 0; nInternalFaces = 0; forAll(includedCell, cellI) { // Include faces of cut cells only. if (includedCell[cellI]) { const labelList& cFaces = mesh.cells()[cellI]; forAll(cFaces, i) { label faceI = cFaces[i]; if (!faceIsCut[faceI]) { // First visit of face. nFaces++; faceIsCut[faceI] = true; // See if would become internal or external face if (isInternalFace(mesh, includedCell, faceI)) { nInternalFaces++; } } } } } Pout<< "Subset consists of " << nFaces << " faces out of " << mesh.nFaces() << " of which " << nInternalFaces << " are internal" << endl; } void Foam::meshTriangulation::insertTriangles ( const triFaceList& faceTris, const label faceI, const label regionI, const bool reverse, List<labelledTri>& triangles, label& triI ) { // Copy triangles. Optionally reverse them forAll(faceTris, i) { const triFace& f = faceTris[i]; labelledTri& tri = triangles[triI]; if (reverse) { tri[0] = f[0]; tri[2] = f[1]; tri[1] = f[2]; } else { tri[0] = f[0]; tri[1] = f[1]; tri[2] = f[2]; } tri.region() = regionI; faceMap_[triI] = faceI; triI++; } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Null constructor Foam::meshTriangulation::meshTriangulation() : triSurface(), nInternalFaces_(0), faceMap_() {} // Construct from faces of cells Foam::meshTriangulation::meshTriangulation ( const polyMesh& mesh, const label internalFacesPatch, const boolList& includedCell, const bool faceCentreDecomposition ) : triSurface(), nInternalFaces_(0), faceMap_() { const faceList& faces = mesh.faces(); const pointField& points = mesh.points(); const polyBoundaryMesh& patches = mesh.boundaryMesh(); // All faces to be triangulated. boolList faceIsCut; label nFaces, nInternalFaces; getFaces ( mesh, includedCell, faceIsCut, nFaces, nInternalFaces ); // Find upper limit for number of triangles // (can be less if triangulation fails) label nTotTri = 0; if (faceCentreDecomposition) { forAll(faceIsCut, faceI) { if (faceIsCut[faceI]) { nTotTri += faces[faceI].size(); } } } else { forAll(faceIsCut, faceI) { if (faceIsCut[faceI]) { nTotTri += faces[faceI].nTriangles(points); } } } Pout<< "nTotTri : " << nTotTri << endl; // Storage for new and old points (only for faceCentre decomposition; // for triangulation uses only existing points) pointField newPoints; if (faceCentreDecomposition) { newPoints.setSize(mesh.nPoints() + faces.size()); forAll(mesh.points(), pointI) { newPoints[pointI] = mesh.points()[pointI]; } // Face centres forAll(faces, faceI) { newPoints[mesh.nPoints() + faceI] = mesh.faceCentres()[faceI]; } } // Storage for all triangles List<labelledTri> triangles(nTotTri); faceMap_.setSize(nTotTri); label triI = 0; if (faceCentreDecomposition) { // Decomposition around face centre // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Triangulate internal faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && isInternalFace(mesh, includedCell, faceI)) { // Face was internal to the mesh and will be 'internal' to // the surface. // Triangulate face const face& f = faces[faceI]; forAll(f, fp) { faceMap_[triI] = faceI; triangles[triI++] = labelledTri ( f[fp], f.nextLabel(fp), mesh.nPoints() + faceI, // face centre internalFacesPatch ); } } } nInternalFaces_ = triI; // Triangulate external faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && !isInternalFace(mesh, includedCell, faceI)) { // Face will become outside of the surface. label patchI = -1; bool reverse = false; if (mesh.isInternalFace(faceI)) { patchI = internalFacesPatch; // Check orientation. Check which side of the face gets // included (note: only one side is). if (includedCell[mesh.faceOwner()[faceI]]) { reverse = false; } else { reverse = true; } } else { // Face was already outside so orientation ok. patchI = patches.whichPatch(faceI); reverse = false; } // Triangulate face const face& f = faces[faceI]; if (reverse) { forAll(f, fp) { faceMap_[triI] = faceI; triangles[triI++] = labelledTri ( f.nextLabel(fp), f[fp], mesh.nPoints() + faceI, // face centre patchI ); } } else { forAll(f, fp) { faceMap_[triI] = faceI; triangles[triI++] = labelledTri ( f[fp], f.nextLabel(fp), mesh.nPoints() + faceI, // face centre patchI ); } } } } } else { // Triangulation using existing vertices // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Triangulate internal faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && isInternalFace(mesh, includedCell, faceI)) { // Face was internal to the mesh and will be 'internal' to // the surface. // Triangulate face. Fall back to naive triangulation if failed. faceTriangulation faceTris(points, faces[faceI], true); if (faceTris.empty()) { WarningIn("meshTriangulation::meshTriangulation") << "Could not find triangulation for face " << faceI << " vertices " << faces[faceI] << " coords " << IndirectList<point>(points, faces[faceI])() << endl; } else { // Copy triangles. Make them internalFacesPatch insertTriangles ( faceTris, faceI, internalFacesPatch, false, // no reverse triangles, triI ); } } } nInternalFaces_ = triI; // Triangulate external faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && !isInternalFace(mesh, includedCell, faceI)) { // Face will become outside of the surface. label patchI = -1; bool reverse = false; if (mesh.isInternalFace(faceI)) { patchI = internalFacesPatch; // Check orientation. Check which side of the face gets // included (note: only one side is). if (includedCell[mesh.faceOwner()[faceI]]) { reverse = false; } else { reverse = true; } } else { // Face was already outside so orientation ok. patchI = patches.whichPatch(faceI); reverse = false; } // Triangulate face faceTriangulation faceTris(points, faces[faceI], true); if (faceTris.empty()) { WarningIn("meshTriangulation::meshTriangulation") << "Could not find triangulation for face " << faceI << " vertices " << faces[faceI] << " coords " << IndirectList<point>(points, faces[faceI])() << endl; } else { // Copy triangles. Optionally reverse them insertTriangles ( faceTris, faceI, patchI, reverse, // whether to reverse triangles, triI ); } } } } // Shrink if nessecary (because of invalid triangulations) triangles.setSize(triI); faceMap_.setSize(triI); Pout<< "nInternalFaces_:" << nInternalFaces_ << endl; Pout<< "triangles:" << triangles.size() << endl; geometricSurfacePatchList surfPatches(patches.size()); forAll(patches, patchI) { surfPatches[patchI] = geometricSurfacePatch ( patches[patchI].physicalType(), patches[patchI].name(), patchI ); } // Create globally numbered tri surface if (faceCentreDecomposition) { // Use newPoints (mesh points + face centres) triSurface globalSurf(triangles, surfPatches, newPoints); // Create locally numbered tri surface triSurface::operator= ( triSurface ( globalSurf.localFaces(), surfPatches, globalSurf.localPoints() ) ); } else { // Use mesh points triSurface globalSurf(triangles, surfPatches, mesh.points()); // Create locally numbered tri surface triSurface::operator= ( triSurface ( globalSurf.localFaces(), surfPatches, globalSurf.localPoints() ) ); } } // ************************************************************************* //
CFDEMproject/OpenFOAM-1.6-ext
src/triSurface/meshTriangulation/meshTriangulation.C
C++
gpl-2.0
14,053
/* * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.beans.decoder; /** * This class is intended to handle &lt;int&gt; element. * This element specifies {@code int} values. * The class {@link Integer} is used as wrapper for these values. * The result value is created from text of the body of this element. * The body parsing is described in the class {@link StringElementHandler}. * For example:<pre> * &lt;int&gt;-1&lt;/int&gt;</pre> * is shortcut to<pre> * &lt;method name="decode" class="java.lang.Integer"&gt; * &lt;string&gt;-1&lt;/string&gt; * &lt;/method&gt;</pre> * which is equivalent to {@code Integer.decode("-1")} in Java code. * <p>The following attribute is supported: * <dl> * <dt>id * <dd>the identifier of the variable that is intended to store the result * </dl> * * @since 1.7 * * @author Sergey A. Malenkov */ final class IntElementHandler extends StringElementHandler { /** * Creates {@code int} value from * the text of the body of this element. * * @param argument the text of the body * @return evaluated {@code int} value */ @Override public Object getValue(String argument) { return Integer.decode(argument); } }
openjdk/jdk7u
jdk/src/share/classes/com/sun/beans/decoder/IntElementHandler.java
Java
gpl-2.0
2,393
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.phases.util; import jdk.internal.jvmci.meta.*; import com.oracle.graal.phases.*; /** * Lazily computed debug value name composed of a prefix and a {@linkplain JavaMethod#getName() * method name}. */ public class MethodDebugValueName extends LazyName { final String prefix; final JavaMethod method; public MethodDebugValueName(String prefix, JavaMethod method) { this.prefix = prefix; this.method = method; } @Override public String createString() { return prefix + "[" + method.getName() + "]"; } }
mur47x111/GraalVM
graal/com.oracle.graal.phases/src/com/oracle/graal/phases/util/MethodDebugValueName.java
Java
gpl-2.0
1,635
<?php include 'common.php'; include 'header.php'; include 'menu.php'; Typecho_Widget::widget('Widget_Contents_Page_Edit')->to($page); ?> <div class="main"> <div class="body container"> <?php include 'page-title.php'; ?> <div class="row typecho-page-main typecho-post-area" role="form"> <form action="<?php $security->index('/action/contents-page-edit'); ?>" method="post" name="write_page"> <div class="col-mb-12 col-tb-9" role="main"> <?php if ($page->draft): ?> <?php if ($page->draft['cid'] != $page->cid): ?> <?php $pageModifyDate = new Typecho_Date($page->draft['modified']); ?> <cite class="edit-draft-notice"><?php _e('当前正在编辑的是保存于%s的草稿, 你可以<a href="%s">删除它</a>', $pageModifyDate->word(), $security->getIndex('/action/contents-page-edit?do=deleteDraft&cid=' . $page->cid)); ?></cite> <?php else: ?> <cite class="edit-draft-notice"><?php _e('当前正在编辑的是未发布的草稿'); ?></cite> <?php endif; ?> <input name="draft" type="hidden" value="<?php echo $page->draft['cid'] ?>" /> <?php endif; ?> <p class="title"> <label for="title" class="sr-only"><?php _e('标题'); ?></label> <input type="text" id="title" name="title" autocomplete="off" value="<?php $page->title(); ?>" placeholder="<?php _e('标题'); ?>" class="w-100 text title" /> </p> <?php $permalink = Typecho_Common::url($options->routingTable['page']['url'], $options->index); list ($scheme, $permalink) = explode(':', $permalink, 2); $permalink = ltrim($permalink, '/'); $permalink = preg_replace("/\[([_a-z0-9-]+)[^\]]*\]/i", "{\\1}", $permalink); if ($page->have()) { $permalink = str_replace('{cid}', $page->cid, $permalink); } $input = '<input type="text" id="slug" name="slug" autocomplete="off" value="' . htmlspecialchars($page->slug) . '" class="mono" />'; ?> <p class="mono url-slug"> <label for="slug" class="sr-only"><?php _e('网址缩略名'); ?></label> <?php echo preg_replace("/\{slug\}/i", $input, $permalink); ?> </p> <p> <label for="text" class="sr-only"><?php _e('页面内容'); ?></label> <textarea style="height: <?php $options->editorSize(); ?>px" autocomplete="off" id="text" name="text" class="w-100 mono"><?php echo htmlspecialchars($page->text); ?></textarea> </p> <?php include 'custom-fields.php'; ?> <p class="submit clearfix"> <span class="left"> <button type="button" id="btn-cancel-preview" class="btn"><i class="i-caret-left"></i> <?php _e('取消预览'); ?></button> </span> <span class="right"> <input type="hidden" name="cid" value="<?php $page->cid(); ?>" /> <button type="button" id="btn-preview" class="btn"><i class="i-exlink"></i> <?php _e('预览页面'); ?></button> <button type="submit" name="do" value="save" id="btn-save" class="btn"><?php _e('保存草稿'); ?></button> <button type="submit" name="do" value="publish" class="btn primary" id="btn-submit"><?php _e('发布页面'); ?></button> <?php if ($options->markdown && (!$page->have() || $page->isMarkdown)): ?> <input type="hidden" name="markdown" value="1" /> <?php endif; ?> </span> </p> <?php Typecho_Plugin::factory('admin/write-page.php')->content($page); ?> </div> <div id="edit-secondary" class="col-mb-12 col-tb-3" role="complementary"> <ul class="typecho-option-tabs clearfix"> <li class="active w-50"><a href="#tab-advance"><?php _e('选项'); ?></a></li> <li class="w-50"><a href="#tab-files" id="tab-files-btn"><?php _e('附件'); ?></a></li> </ul> <div id="tab-advance" class="tab-content"> <section class="typecho-post-option" role="application"> <label for="date" class="typecho-label"><?php _e('发布日期'); ?></label> <p><input class="typecho-date w-100" type="text" name="date" id="date" value="<?php $page->have() ? $page->date('Y-m-d H:i') : ''; ?>" /></p> </section> <section class="typecho-post-option"> <label for="order" class="typecho-label"><?php _e('页面顺序'); ?></label> <p><input type="text" id="order" name="order" value="<?php $page->order(); ?>" class="w-100" /></p> <p class="description"><?php _e('为你的自定义页面设定一个序列值以后, 能够使得它们按此值从小到大排列'); ?></p> </section> <section class="typecho-post-option"> <label for="template" class="typecho-label"><?php _e('自定义模板'); ?></label> <p> <select name="template" id="template"> <option value=""><?php _e('不选择'); ?></option> <?php $templates = $page->getTemplates(); foreach ($templates as $template => $name): ?> <option value="<?php echo $template; ?>"<?php if($template == $page->template): ?> selected="true"<?php endif; ?>><?php echo $name; ?></option> <?php endforeach; ?> </select> </p> <p class="description"><?php _e('如果你为此页面选择了一个自定义模板, 系统将按照你选择的模板文件展现它'); ?></p> </section> <?php Typecho_Plugin::factory('admin/write-page.php')->option($page); ?> <button type="button" id="advance-panel-btn" class="btn btn-xs"><?php _e('高级选项'); ?> <i class="i-caret-down"></i></button> <div id="advance-panel"> <section class="typecho-post-option visibility-option"> <label for="visibility" class="typecho-label"><?php _e('公开度'); ?></label> <p> <select id="visibility" name="visibility"> <option value="publish"<?php if ($page->status == 'publish' || !$page->status): ?> selected<?php endif; ?>><?php _e('公开'); ?></option> <option value="hidden"<?php if ($page->status == 'hidden'): ?> selected<?php endif; ?>><?php _e('隐藏'); ?></option> </select> </p> </section> <section class="typecho-post-option allow-option"> <label class="typecho-label"><?php _e('权限控制'); ?></label> <ul> <li><input id="allowComment" name="allowComment" type="checkbox" value="1" <?php if($page->allow('comment')): ?>checked="true"<?php endif; ?> /> <label for="allowComment"><?php _e('允许评论'); ?></label></li> <li><input id="allowPing" name="allowPing" type="checkbox" value="1" <?php if($page->allow('ping')): ?>checked="true"<?php endif; ?> /> <label for="allowPing"><?php _e('允许被引用'); ?></label></li> <li><input id="allowFeed" name="allowFeed" type="checkbox" value="1" <?php if($page->allow('feed')): ?>checked="true"<?php endif; ?> /> <label for="allowFeed"><?php _e('允许在聚合中出现'); ?></label></li> </ul> </section> <?php Typecho_Plugin::factory('admin/write-page.php')->advanceOption($page); ?> </div> <?php if($page->have()): ?> <?php $modified = new Typecho_Date($page->modified); ?> <section class="typecho-post-option"> <p class="description"> <br>&mdash;<br> <?php _e('本页面由 <a href="%s">%s</a> 创建', Typecho_Common::url('manage-pages.php?uid=' . $page->author->uid, $options->adminUrl), $page->author->screenName); ?><br> <?php _e('最后更新于 %s', $modified->word()); ?> </p> </section> <?php endif; ?> </div><!-- end #tab-advance --> <div id="tab-files" class="tab-content hidden"> <?php include 'file-upload.php'; ?> </div><!-- end #tab-files --> </div> </form> </div> </div> </div> <?php include 'copyright.php'; include 'common-js.php'; include 'form-js.php'; include 'write-js.php'; Typecho_Plugin::factory('admin/write-page.php')->trigger($plugged)->richEditor($page); if (!$plugged) { include 'editor-js.php'; } include 'file-upload-js.php'; include 'custom-fields-js.php'; Typecho_Plugin::factory('admin/write-page.php')->bottom($page); include 'footer.php'; ?>
engine-go/pizida
admin/write-page.php
PHP
gpl-2.0
10,482
package org.bouncycastle.asn1; import java.io.IOException; public interface ASN1SequenceParser extends DEREncodable, InMemoryRepresentable { DEREncodable readObject() throws IOException; }
Z-Shang/onscripter-gbk
svn/onscripter-read-only/src/org/bouncycastle/asn1/ASN1SequenceParser.java
Java
gpl-2.0
207
<?php /** * @version $Id$ * * @author Valérie Isaksen * @package VirtueMart * @copyright Copyright (C) iStraxx - All rights reserved. * @license istraxx_license.txt Proprietary License. This code belongs to istraxx UG (haftungsbeschränkt) * You are not allowed to distribute or sell this code. * You are not allowed to modify this code */ defined('JPATH_BASE') or die(); /** * Renders a label element */ class JElementKlarnaLabel extends JElement { /** * Element name * * @access protected * @var string */ var $_name = 'KlarnaLabel'; function fetchElement($name, $value, &$node, $control_name) { $class = ( $node->attributes('class') ? 'class="'.$node->attributes('class').'"' : 'class="text_area"' ); return '<label for="'.$name.'"'.$class.'>'.$value.'</label>'; } }
Jasonudoo/platform
administrator/components/com_virtuemart_allinone/plugins/vmpayment/klarna/klarna/elements/klarnalabel.php
PHP
gpl-2.0
800
/* * Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/> * * 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, see <http://www.gnu.org/licenses/>. */ #include "GuildPackets.h" void WorldPackets::Guild::QueryGuildInfo::Read() { _worldPacket >> GuildGuid; _worldPacket >> PlayerGuid; } WorldPackets::Guild::QueryGuildInfoResponse::QueryGuildInfoResponse() : ServerPacket(SMSG_QUERY_GUILD_INFO_RESPONSE) { } WorldPacket const* WorldPackets::Guild::QueryGuildInfoResponse::Write() { _worldPacket << GuildGuid; _worldPacket.WriteBit(Info.is_initialized()); _worldPacket.FlushBits(); if (Info) { _worldPacket << Info->GuildGUID; _worldPacket << uint32(Info->VirtualRealmAddress); _worldPacket << uint32(Info->Ranks.size()); _worldPacket << uint32(Info->EmblemStyle); _worldPacket << uint32(Info->EmblemColor); _worldPacket << uint32(Info->BorderStyle); _worldPacket << uint32(Info->BorderColor); _worldPacket << uint32(Info->BackgroundColor); _worldPacket.WriteBits(Info->GuildName.size(), 7); _worldPacket.FlushBits(); for (GuildInfo::GuildInfoRank const& rank : Info->Ranks) { _worldPacket << uint32(rank.RankID); _worldPacket << uint32(rank.RankOrder); _worldPacket.WriteBits(rank.RankName.size(), 7); _worldPacket.FlushBits(); _worldPacket.WriteString(rank.RankName); } _worldPacket.WriteString(Info->GuildName); } return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildRoster::Write() { _worldPacket << NumAccounts; _worldPacket.AppendPackedTime(CreateDate); _worldPacket << GuildFlags; _worldPacket << uint32(MemberData.size()); _worldPacket.WriteBits(WelcomeText.length(), 10); _worldPacket.WriteBits(InfoText.length(), 11); _worldPacket.FlushBits(); for (GuildRosterMemberData const& member : MemberData) _worldPacket << member; _worldPacket.WriteString(WelcomeText); _worldPacket.WriteString(InfoText); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildRosterUpdate::Write() { _worldPacket << uint32(MemberData.size()); for (GuildRosterMemberData const& member : MemberData) _worldPacket << member; return &_worldPacket; } void WorldPackets::Guild::GuildUpdateMotdText::Read() { uint32 textLen = _worldPacket.ReadBits(10); MotdText = _worldPacket.ReadString(textLen); } WorldPacket const* WorldPackets::Guild::GuildCommandResult::Write() { _worldPacket << Result; _worldPacket << Command; _worldPacket.WriteBits(Name.length(), 8); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); return &_worldPacket; } void WorldPackets::Guild::DeclineGuildInvites::Read() { Allow = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildInviteByName::Read() { uint32 nameLen = _worldPacket.ReadBits(9); Name = _worldPacket.ReadString(nameLen); } WorldPacket const* WorldPackets::Guild::GuildInvite::Write() { _worldPacket.WriteBits(InviterName.length(), 6); _worldPacket.WriteBits(GuildName.length(), 7); _worldPacket.WriteBits(OldGuildName.length(), 7); _worldPacket.FlushBits(); _worldPacket << InviterVirtualRealmAddress; _worldPacket << GuildVirtualRealmAddress; _worldPacket << GuildGUID; _worldPacket << OldGuildVirtualRealmAddress; _worldPacket << OldGuildGUID; _worldPacket << EmblemStyle; _worldPacket << EmblemColor; _worldPacket << BorderStyle; _worldPacket << BorderColor; _worldPacket << Background; _worldPacket << AchievementPoints; _worldPacket.WriteString(InviterName); _worldPacket.WriteString(GuildName); _worldPacket.WriteString(OldGuildName); return &_worldPacket; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRosterProfessionData const& rosterProfessionData) { data << rosterProfessionData.DbID; data << rosterProfessionData.Rank; data << rosterProfessionData.Step; return data; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRosterMemberData const& rosterMemberData) { data << rosterMemberData.Guid; data << rosterMemberData.RankID; data << rosterMemberData.AreaID; data << rosterMemberData.PersonalAchievementPoints; data << rosterMemberData.GuildReputation; data << rosterMemberData.LastSave; for (uint8 i = 0; i < 2; i++) data << rosterMemberData.Profession[i]; data << rosterMemberData.VirtualRealmAddress; data << rosterMemberData.Status; data << rosterMemberData.Level; data << rosterMemberData.ClassID; data << rosterMemberData.Gender; data.WriteBits(rosterMemberData.Name.length(), 6); data.WriteBits(rosterMemberData.Note.length(), 8); data.WriteBits(rosterMemberData.OfficerNote.length(), 8); data.WriteBit(rosterMemberData.Authenticated); data.WriteBit(rosterMemberData.SorEligible); data.FlushBits(); data.WriteString(rosterMemberData.Name); data.WriteString(rosterMemberData.Note); data.WriteString(rosterMemberData.OfficerNote); return data; } WorldPacket const* WorldPackets::Guild::GuildEventPresenceChange::Write() { _worldPacket << Guid; _worldPacket << VirtualRealmAddress; _worldPacket.WriteBits(Name.length(), 6); _worldPacket.WriteBit(LoggedOn); _worldPacket.WriteBit(Mobile); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventMotd::Write() { _worldPacket.WriteBits(MotdText.length(), 10); _worldPacket.FlushBits(); _worldPacket.WriteString(MotdText); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventPlayerJoined::Write() { _worldPacket << Guid; _worldPacket << VirtualRealmAddress; _worldPacket.WriteBits(Name.length(), 6); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventRankChanged::Write() { _worldPacket << RankID; return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventBankMoneyChanged::Write() { _worldPacket << Money; return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventLogQueryResults::Write() { _worldPacket.reserve(4 + Entry.size() * 38); _worldPacket << uint32(Entry.size()); for (GuildEventEntry const& entry : Entry) { _worldPacket << entry.PlayerGUID; _worldPacket << entry.OtherGUID; _worldPacket << entry.TransactionType; _worldPacket << entry.RankID; _worldPacket << entry.TransactionDate; } return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventPlayerLeft::Write() { _worldPacket.WriteBit(Removed); _worldPacket.WriteBits(LeaverName.length(), 6); _worldPacket.FlushBits(); if (Removed) { _worldPacket.WriteBits(RemoverName.length(), 6); _worldPacket.FlushBits(); _worldPacket << RemoverGUID; _worldPacket << RemoverVirtualRealmAddress; _worldPacket.WriteString(RemoverName); } _worldPacket << LeaverGUID; _worldPacket << LeaverVirtualRealmAddress; _worldPacket.WriteString(LeaverName); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildPermissionsQueryResults::Write() { _worldPacket << RankID; _worldPacket << WithdrawGoldLimit; _worldPacket << Flags; _worldPacket << NumTabs; _worldPacket << uint32(Tab.size()); for (GuildRankTabPermissions const& tab : Tab) { _worldPacket << tab.Flags; _worldPacket << tab.WithdrawItemLimit; } return &_worldPacket; } void WorldPackets::Guild::GuildSetRankPermissions::Read() { _worldPacket >> RankID; _worldPacket >> RankOrder; _worldPacket >> Flags; _worldPacket >> OldFlags; _worldPacket >> WithdrawGoldLimit; for (uint8 i = 0; i < GUILD_BANK_MAX_TABS; i++) { _worldPacket >> TabFlags[i]; _worldPacket >> TabWithdrawItemLimit[i]; } _worldPacket.ResetBitPos(); uint32 rankNameLen = _worldPacket.ReadBits(7); RankName = _worldPacket.ReadString(rankNameLen); } WorldPacket const* WorldPackets::Guild::GuildEventNewLeader::Write() { _worldPacket.WriteBit(SelfPromoted); _worldPacket.WriteBits(NewLeaderName.length(), 6); _worldPacket.WriteBits(OldLeaderName.length(), 6); _worldPacket.FlushBits(); _worldPacket << OldLeaderGUID; _worldPacket << OldLeaderVirtualRealmAddress; _worldPacket << NewLeaderGUID; _worldPacket << NewLeaderVirtualRealmAddress; _worldPacket.WriteString(NewLeaderName); _worldPacket.WriteString(OldLeaderName); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventTabModified::Write() { _worldPacket << Tab; _worldPacket.WriteBits(Name.length(), 7); _worldPacket.WriteBits(Icon.length(), 9); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); _worldPacket.WriteString(Icon); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventTabTextChanged::Write() { _worldPacket << Tab; return &_worldPacket; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRankData const& rankData) { data << rankData.RankID; data << rankData.RankOrder; data << rankData.Flags; data << rankData.WithdrawGoldLimit; for (uint8 i = 0; i < GUILD_BANK_MAX_TABS; i++) { data << rankData.TabFlags[i]; data << rankData.TabWithdrawItemLimit[i]; } data.WriteBits(rankData.RankName.length(), 7); data.FlushBits(); data.WriteString(rankData.RankName); return data; } void WorldPackets::Guild::GuildAddRank::Read() { uint32 nameLen = _worldPacket.ReadBits(7); _worldPacket.ResetBitPos(); _worldPacket >> RankOrder; Name = _worldPacket.ReadString(nameLen); } void WorldPackets::Guild::GuildAssignMemberRank::Read() { _worldPacket >> Member; _worldPacket >> RankOrder; } void WorldPackets::Guild::GuildDeleteRank::Read() { _worldPacket >> RankOrder; } void WorldPackets::Guild::GuildGetRanks::Read() { _worldPacket >> GuildGUID; } WorldPacket const* WorldPackets::Guild::GuildRanks::Write() { _worldPacket << uint32(Ranks.size()); for (GuildRankData const& rank : Ranks) _worldPacket << rank; return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildSendRankChange::Write() { _worldPacket << Officer; _worldPacket << Other; _worldPacket << RankID; _worldPacket.WriteBit(Promote); _worldPacket.FlushBits(); return &_worldPacket; } void WorldPackets::Guild::GuildShiftRank::Read() { _worldPacket >> RankOrder; ShiftUp = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildUpdateInfoText::Read() { uint32 textLen = _worldPacket.ReadBits(11); InfoText = _worldPacket.ReadString(textLen); } void WorldPackets::Guild::GuildSetMemberNote::Read() { _worldPacket >> NoteeGUID; uint32 noteLen = _worldPacket.ReadBits(8); IsPublic = _worldPacket.ReadBit(); Note = _worldPacket.ReadString(noteLen); } WorldPacket const* WorldPackets::Guild::GuildMemberUpdateNote::Write() { _worldPacket.reserve(16 + 2 + Note.size()); _worldPacket << Member; _worldPacket.WriteBits(Note.length(), 8); _worldPacket.WriteBit(IsPublic); _worldPacket.FlushBits(); _worldPacket.WriteString(Note); return &_worldPacket; } void WorldPackets::Guild::GuildDemoteMember::Read() { _worldPacket >> Demotee; } void WorldPackets::Guild::GuildPromoteMember::Read() { _worldPacket >> Promotee; } void WorldPackets::Guild::GuildOfficerRemoveMember::Read() { _worldPacket >> Removee; } void WorldPackets::Guild::GuildChangeNameRequest::Read() { uint32 nameLen = _worldPacket.ReadBits(7); NewName = _worldPacket.ReadString(nameLen); } WorldPacket const* WorldPackets::Guild::GuildFlaggedForRename::Write() { _worldPacket.WriteBit(FlagSet); return &_worldPacket; } void WorldPackets::Guild::RequestGuildPartyState::Read() { _worldPacket >> GuildGUID; } WorldPacket const* WorldPackets::Guild::GuildPartyState::Write() { _worldPacket.WriteBit(InGuildParty); _worldPacket.FlushBits(); _worldPacket << NumMembers; _worldPacket << NumRequired; _worldPacket << GuildXPEarnedMult; return &_worldPacket; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRewardItem const& rewardItem) { data << rewardItem.ItemID; data << rewardItem.Unk4; data << uint32(rewardItem.AchievementsRequired.size()); data << rewardItem.RaceMask; data << rewardItem.MinGuildLevel; data << rewardItem.MinGuildRep; data << rewardItem.Cost; for (uint8 i = 0; i < rewardItem.AchievementsRequired.size(); i++) data << rewardItem.AchievementsRequired[i]; return data; } void WorldPackets::Guild::RequestGuildRewardsList::Read() { _worldPacket >> CurrentVersion; } WorldPacket const* WorldPackets::Guild::GuildRewardList::Write() { _worldPacket << Version; _worldPacket << uint32(RewardItems.size()); for (GuildRewardItem const& item : RewardItems) _worldPacket << item; return &_worldPacket; } void WorldPackets::Guild::GuildBankActivate::Read() { _worldPacket >> Banker; FullUpdate = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildBankBuyTab::Read() { _worldPacket >> Banker; _worldPacket >> BankTab; } void WorldPackets::Guild::GuildBankUpdateTab::Read() { _worldPacket >> Banker; _worldPacket >> BankTab; _worldPacket.ResetBitPos(); uint32 nameLen = _worldPacket.ReadBits(7); uint32 iconLen = _worldPacket.ReadBits(9); Name = _worldPacket.ReadString(nameLen); Icon = _worldPacket.ReadString(iconLen); } void WorldPackets::Guild::GuildBankDepositMoney::Read() { _worldPacket >> Banker; _worldPacket >> Money; } void WorldPackets::Guild::GuildBankQueryTab::Read() { _worldPacket >> Banker; _worldPacket >> Tab; FullUpdate = _worldPacket.ReadBit(); } WorldPacket const* WorldPackets::Guild::GuildBankRemainingWithdrawMoney::Write() { _worldPacket << RemainingWithdrawMoney; return &_worldPacket; } void WorldPackets::Guild::GuildBankWithdrawMoney::Read() { _worldPacket >> Banker; _worldPacket >> Money; } WorldPacket const* WorldPackets::Guild::GuildBankQueryResults::Write() { _worldPacket << Money; _worldPacket << Tab; _worldPacket << WithdrawalsRemaining; _worldPacket << uint32(TabInfo.size()); _worldPacket << uint32(ItemInfo.size()); _worldPacket.WriteBit(FullUpdate); _worldPacket.FlushBits(); for (GuildBankTabInfo const& tab : TabInfo) { _worldPacket << tab.TabIndex; _worldPacket.WriteBits(tab.Name.length(), 7); _worldPacket.WriteBits(tab.Icon.length(), 9); _worldPacket.FlushBits(); _worldPacket.WriteString(tab.Name); _worldPacket.WriteString(tab.Icon); } for (GuildBankItemInfo const& item : ItemInfo) { _worldPacket << item.Slot; _worldPacket << item.Count; _worldPacket << item.EnchantmentID; _worldPacket << item.Charges; _worldPacket << item.OnUseEnchantmentID; _worldPacket << item.Flags; _worldPacket << item.Item; _worldPacket.WriteBits(item.SocketEnchant.size(), 2); _worldPacket.WriteBit(item.Locked); _worldPacket.FlushBits(); for (Item::ItemGemData const& socketEnchant : item.SocketEnchant) _worldPacket << socketEnchant; } return &_worldPacket; } void WorldPackets::Guild::GuildBankSwapItems::Read() { _worldPacket >> Banker; _worldPacket >> BankTab; _worldPacket >> BankSlot; _worldPacket >> ItemID; _worldPacket >> BankTab1; _worldPacket >> BankSlot1; _worldPacket >> ItemID1; _worldPacket >> BankItemCount; _worldPacket >> ContainerSlot; _worldPacket >> ContainerItemSlot; _worldPacket >> ToSlot; _worldPacket >> StackCount; _worldPacket.ResetBitPos(); BankOnly = _worldPacket.ReadBit(); AutoStore = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildBankLogQuery::Read() { _worldPacket >> Tab; } WorldPacket const* WorldPackets::Guild::GuildBankLogQueryResults::Write() { _worldPacket << Tab; _worldPacket << uint32(Entry.size()); _worldPacket.WriteBit(WeeklyBonusMoney.is_initialized()); _worldPacket.FlushBits(); for (GuildBankLogEntry const& logEntry : Entry) { _worldPacket << logEntry.PlayerGUID; _worldPacket << logEntry.TimeOffset; _worldPacket << logEntry.EntryType; _worldPacket.WriteBit(logEntry.Money.is_initialized()); _worldPacket.WriteBit(logEntry.ItemID.is_initialized()); _worldPacket.WriteBit(logEntry.Count.is_initialized()); _worldPacket.WriteBit(logEntry.OtherTab.is_initialized()); _worldPacket.FlushBits(); if (logEntry.Money.is_initialized()) _worldPacket << *logEntry.Money; if (logEntry.ItemID.is_initialized()) _worldPacket << *logEntry.ItemID; if (logEntry.Count.is_initialized()) _worldPacket << *logEntry.Count; if (logEntry.OtherTab.is_initialized()) _worldPacket << *logEntry.OtherTab; } if (WeeklyBonusMoney) _worldPacket << *WeeklyBonusMoney; return &_worldPacket; } void WorldPackets::Guild::GuildBankTextQuery::Read() { _worldPacket >> Tab; } WorldPacket const* WorldPackets::Guild::GuildBankTextQueryResult::Write() { _worldPacket << Tab; _worldPacket.WriteBits(Text.length(), 14); _worldPacket.FlushBits(); _worldPacket.WriteString(Text); return &_worldPacket; } void WorldPackets::Guild::GuildBankSetTabText::Read() { _worldPacket >> Tab; TabText = _worldPacket.ReadString(_worldPacket.ReadBits(14)); } void WorldPackets::Guild::GuildQueryNews::Read() { _worldPacket >> GuildGUID; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildNewsEvent const& newsEvent) { data << newsEvent.Id; data.AppendPackedTime(newsEvent.CompletedDate); data << newsEvent.Type; data << newsEvent.Flags; for (uint8 i = 0; i < 2; i++) data << newsEvent.Data[i]; data << newsEvent.MemberGuid; data << uint32(newsEvent.MemberList.size()); for (ObjectGuid memberGuid : newsEvent.MemberList) data << memberGuid; data.WriteBit(newsEvent.Item.is_initialized()); data.FlushBits(); if (newsEvent.Item) data << *newsEvent.Item; // WorldPackets::Item::ItemInstance return data; } WorldPacket const* WorldPackets::Guild::GuildNews::Write() { _worldPacket << uint32(NewsEvents.size()); for (GuildNewsEvent const& newsEvent : NewsEvents) _worldPacket << newsEvent; return &_worldPacket; } void WorldPackets::Guild::GuildNewsUpdateSticky::Read() { _worldPacket >> GuildGUID; _worldPacket >> NewsID; NewsID = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildSetGuildMaster::Read() { uint32 nameLen = _worldPacket.ReadBits(9); NewMasterName = _worldPacket.ReadString(nameLen); } WorldPacket const* WorldPackets::Guild::GuildChallengeUpdate::Write() { for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(CurrentCount[i]); for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(MaxCount[i]); for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(MaxLevelGold[i]); for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(Gold[i]); return &_worldPacket; } void WorldPackets::Guild::SaveGuildEmblem::Read() { _worldPacket >> Vendor; _worldPacket >> EStyle; _worldPacket >> EColor; _worldPacket >> BStyle; _worldPacket >> BColor; _worldPacket >> Bg; } WorldPacket const* WorldPackets::Guild::PlayerSaveGuildEmblem::Write() { _worldPacket << int32(Error); return &_worldPacket; } void WorldPackets::Guild::GuildSetAchievementTracking::Read() { uint32 count; _worldPacket >> count; for (uint32 i = 0; i < count; ++i) { uint32 value; _worldPacket >> value; AchievementIDs.insert(value); } } WorldPacket const* WorldPackets::Guild::GuildNameChanged::Write() { _worldPacket << GuildGUID; _worldPacket.WriteBits(GuildName.length(), 7); _worldPacket.FlushBits(); _worldPacket.WriteString(GuildName); return &_worldPacket; }
Dozorov/TrinityCore
src/server/game/Server/Packets/GuildPackets.cpp
C++
gpl-2.0
21,360
<?php /** * @file * Template for the 1 column panel layout. * * This template provides a three column 25%-50%-25% panel display layout. * * Variables: * - $id: An optional CSS id to use for the layout. * - $content: An array of content, each item in the array is keyed to one * panel of the layout. This layout supports the following sections: * - $content['left']: Content in the left column. * - $content['middle']: Content in the middle column. * - $content['right']: Content in the right column. */ ?> <div class="panel-display general-two-col clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>> <div class="panel-panel general-left"> <?php if ($content['left']): ?> <div class="inside"><?php print $content['left']; ?></div> <?php endif ?> </div> <div class="panel-panel general-right"> <?php if ($content['right']): ?> <div class="inside"><?php print $content['right']; ?></div> <?php endif ?> </div> <div class="vertical-line"></div> </div>
SLAC-OCIO/slac-www
sites/all/themes/slac_www/plugins/layouts/two_col/two-col.tpl.php
PHP
gpl-2.0
1,034
<?php /** * AJAX handler plugin manager * * PHP version 7 * * Copyright (C) Villanova University 2018. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * 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 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 * * @category VuFind * @package AJAX * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ namespace VuFind\AjaxHandler; /** * AJAX handler plugin manager * * @category VuFind * @package AJAX * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ class PluginManager extends \VuFind\ServiceManager\AbstractPluginManager { /** * Default plugin aliases. * * @var array */ protected $aliases = [ 'checkRequestIsValid' => CheckRequestIsValid::class, 'commentRecord' => CommentRecord::class, 'deleteRecordComment' => DeleteRecordComment::class, 'doiLookup' => DoiLookup::class, 'getACSuggestions' => GetACSuggestions::class, 'getFacetData' => GetFacetData::class, 'getIlsStatus' => GetIlsStatus::class, 'getItemStatuses' => GetItemStatuses::class, 'getLibraryPickupLocations' => GetLibraryPickupLocations::class, 'getRecordCommentsAsHTML' => GetRecordCommentsAsHTML::class, 'getRecordDetails' => GetRecordDetails::class, 'getRecordTags' => GetRecordTags::class, 'getRequestGroupPickupLocations' => GetRequestGroupPickupLocations::class, 'getResolverLinks' => GetResolverLinks::class, 'getSaveStatuses' => GetSaveStatuses::class, 'getSideFacets' => GetSideFacets::class, 'getUserFines' => GetUserFines::class, 'getUserHolds' => GetUserHolds::class, 'getUserILLRequests' => GetUserILLRequests::class, 'getUserStorageRetrievalRequests' => GetUserStorageRetrievalRequests::class, 'getUserTransactions' => GetUserTransactions::class, 'getVisData' => GetVisData::class, 'keepAlive' => KeepAlive::class, 'recommend' => Recommend::class, 'relaisAvailability' => RelaisAvailability::class, 'relaisInfo' => RelaisInfo::class, 'relaisOrder' => RelaisOrder::class, 'systemStatus' => SystemStatus::class, 'tagRecord' => TagRecord::class, ]; /** * Default plugin factories. * * @var array */ protected $factories = [ CheckRequestIsValid::class => AbstractIlsAndUserActionFactory::class, CommentRecord::class => CommentRecordFactory::class, DeleteRecordComment::class => DeleteRecordCommentFactory::class, DoiLookup::class => DoiLookupFactory::class, GetACSuggestions::class => GetACSuggestionsFactory::class, GetFacetData::class => GetFacetDataFactory::class, GetIlsStatus::class => GetIlsStatusFactory::class, GetItemStatuses::class => GetItemStatusesFactory::class, GetLibraryPickupLocations::class => AbstractIlsAndUserActionFactory::class, GetRecordCommentsAsHTML::class => GetRecordCommentsAsHTMLFactory::class, GetRecordDetails::class => GetRecordDetailsFactory::class, GetRecordTags::class => GetRecordTagsFactory::class, GetRequestGroupPickupLocations::class => AbstractIlsAndUserActionFactory::class, GetResolverLinks::class => GetResolverLinksFactory::class, GetSaveStatuses::class => GetSaveStatusesFactory::class, GetSideFacets::class => GetSideFacetsFactory::class, GetUserFines::class => GetUserFinesFactory::class, GetUserHolds::class => AbstractIlsAndUserActionFactory::class, GetUserILLRequests::class => AbstractIlsAndUserActionFactory::class, GetUserStorageRetrievalRequests::class => AbstractIlsAndUserActionFactory::class, GetUserTransactions::class => AbstractIlsAndUserActionFactory::class, GetVisData::class => GetVisDataFactory::class, KeepAlive::class => KeepAliveFactory::class, Recommend::class => RecommendFactory::class, RelaisAvailability::class => AbstractRelaisActionFactory::class, RelaisInfo::class => AbstractRelaisActionFactory::class, RelaisOrder::class => AbstractRelaisActionFactory::class, SystemStatus::class => SystemStatusFactory::class, TagRecord::class => TagRecordFactory::class, ]; /** * Return the name of the base class or interface that plug-ins must conform * to. * * @return string */ protected function getExpectedInterface() { return AjaxHandlerInterface::class; } }
arto70/NDL-VuFind2
module/VuFind/src/VuFind/AjaxHandler/PluginManager.php
PHP
gpl-2.0
5,361
<?php /** * @package WordPress * @subpackage GoodDay * @version 1.0.0 * * Post Options Functions * Created by CMSMasters * */ $cmsms_option = cmsms_get_global_options(); $cmsms_global_blog_post_layout = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_layout']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_layout'] !== '') ? $cmsms_option[CMSMS_SHORTNAME . '_blog_post_layout'] : 'r_sidebar'; $cmsms_global_bottom_sidebar = (isset($cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar']) && $cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_bottom_sidebar_layout = (isset($cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar_layout'])) ? $cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar_layout'] : '14141414'; $cmsms_global_blog_post_title = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_title']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_title'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_blog_post_title'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_blog_post_share_box = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_share_box']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_share_box'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_blog_post_share_box'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_blog_post_author_box = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_author_box']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_author_box'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_blog_post_author_box'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_bg = (isset($cmsms_option[CMSMS_SHORTNAME . '_theme_layout']) && $cmsms_option[CMSMS_SHORTNAME . '_theme_layout'] === 'boxed') ? true : false; if (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_more_posts_box']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_more_posts_box'] !== '') { $cmsms_global_blog_more_posts_box = array(); foreach($cmsms_option[CMSMS_SHORTNAME . '_blog_more_posts_box'] as $key => $val) { if ($val == 'true') { $cmsms_global_blog_more_posts_box[] = $key; } } } else { $cmsms_global_blog_more_posts_box = array( 'related', 'popular', 'recent' ); } $cmsms_option_name = 'cmsms_post_'; $tabs_array = array(); $tabs_array['cmsms_post'] = array( 'label' => __('Post', 'cmsmasters'), 'value' => 'cmsms_post' ); $tabs_array['cmsms_layout'] = array( 'label' => __('Layout', 'cmsmasters'), 'value' => 'cmsms_layout' ); if ($cmsms_global_bg) { $tabs_array['cmsms_bg'] = array( 'label' => __('Background', 'cmsmasters'), 'value' => 'cmsms_bg' ); } $tabs_array['cmsms_heading'] = array( 'label' => __('Heading', 'cmsmasters'), 'value' => 'cmsms_heading' ); $custom_post_meta_fields = array( array( 'id' => 'cmsms_post_aside', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Aside Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'aside_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_aside', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_status', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Status Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'status_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_status', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_chat', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Chat Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'chat_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_chat', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_quote', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Quote Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'quote_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'label' => __('Quote Author', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'quote_author', 'type' => 'text', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_quote', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_link', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Link Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'link_text', 'type' => 'text', 'hide' => '', 'std' => '' ), array( 'label' => __('Link Address', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'link_address', 'type' => 'text_long', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_link', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_image', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Post Image', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'image_link', 'type' => 'image', 'hide' => '', 'cancel' => 'true', 'std' => '', 'frame' => 'select', 'multiple' => false ), array( 'id' => 'cmsms_post_image', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_gallery', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Post Gallery', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'images', 'type' => 'images_list', 'hide' => '', 'std' => '', 'frame' => 'post', 'multiple' => true ), array( 'id' => 'cmsms_post_gallery', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_video', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Video Type', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'video_type', 'type' => 'radio', 'hide' => '', 'std' => 'embedded', 'options' => array( 'embedded' => array( 'label' => __('Embedded (YouTube, Vimeo)', 'cmsmasters'), 'value' => 'embedded' ), 'selfhosted' => array( 'label' => __('Self-Hosted', 'cmsmasters'), 'value' => 'selfhosted' ) ) ), array( 'label' => __('Embedded Video Link', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'video_link', 'type' => 'text_long', 'hide' => 'true', 'std' => '' ), array( 'label' => __('Self-Hosted Video Links', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'video_links', 'type' => 'repeatable', 'hide' => 'true', 'std' => '' ), array( 'id' => 'cmsms_post_video', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_audio', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Audio Links', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'audio_links', 'type' => 'repeatable', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_audio', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_format', 'type' => 'content_start', 'box' => '' ), array( 'id' => 'cmsms_post_format', 'type' => 'content_finish' ), array( 'id' => $cmsms_option_name . 'tabs', 'type' => 'tabs', 'std' => 'cmsms_post', 'options' => $tabs_array ), array( 'id' => 'cmsms_post', 'type' => 'tab_start', 'std' => 'true' ), array( 'label' => __('Post Title', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => $cmsms_option_name . 'title', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_blog_post_title ), array( 'label' => __('Sharing Box', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => $cmsms_option_name . 'sharing_box', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_blog_post_share_box ), array( 'label' => __('About Author Box', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => $cmsms_option_name . 'author_box', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_blog_post_author_box ), array( 'label' => __('More Posts Box', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'more_posts', 'type' => 'checkbox_group', 'hide' => '', 'std' => ((isset($_GET['post']) && get_post_meta($_GET['post'], 'cmsms_heading', true)) ? '' : $cmsms_global_blog_more_posts_box), 'options' => array( 'related' => array( 'label' => 'Show Related Tab', 'value' => 'related' ), 'popular' => array( 'label' => 'Show Popular Tab', 'value' => 'popular' ), 'recent' => array( 'label' => 'Show Recent Tab', 'value' => 'recent' ) ) ), array( 'label' => __("'Read More' Buttons Text", 'cmsmasters'), 'desc' => __("Enter the 'Read More' button text that should be used in you blog shortcode", 'cmsmasters'), 'id' => $cmsms_option_name . 'read_more', 'type' => 'text', 'hide' => '', 'std' => __('Read More', 'cmsmasters') ), array( 'id' => 'cmsms_post', 'type' => 'tab_finish' ), array( 'id' => 'cmsms_layout', 'type' => 'tab_start', 'std' => '' ), array( 'label' => __('Page Color Scheme', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_page_scheme', 'type' => 'select_scheme', 'hide' => 'false', 'std' => 'default' ), array( 'label' => __('Page Layout', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_layout', 'type' => 'radio_img', 'hide' => '', 'std' => $cmsms_global_blog_post_layout, 'options' => array( 'r_sidebar' => array( 'img' => get_template_directory_uri() . '/framework/admin/inc/img/sidebar_r.jpg', 'label' => __('Right Sidebar', 'cmsmasters'), 'value' => 'r_sidebar' ), 'l_sidebar' => array( 'img' => get_template_directory_uri() . '/framework/admin/inc/img/sidebar_l.jpg', 'label' => __('Left Sidebar', 'cmsmasters'), 'value' => 'l_sidebar' ), 'fullwidth' => array( 'img' => get_template_directory_uri() . '/framework/admin/inc/img/fullwidth.jpg', 'label' => __('Full Width', 'cmsmasters'), 'value' => 'fullwidth' ) ) ), array( 'label' => __('Choose Right\Left Sidebar', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_sidebar_id', 'type' => 'select_sidebar', 'hide' => 'true', 'std' => '' ), array( 'label' => __('Bottom Sidebar', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => 'cmsms_bottom_sidebar', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_bottom_sidebar ), array( 'label' => __('Choose Bottom Sidebar', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_bottom_sidebar_id', 'type' => 'select_sidebar', 'hide' => 'true', 'std' => '' ), array( 'label' => __('Choose Bottom Sidebar Layout', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_bottom_sidebar_layout', 'type' => 'select', 'hide' => 'true', 'std' => $cmsms_global_bottom_sidebar_layout, 'options' => array( '11' => array( 'label' => '1/1', 'value' => '11' ), '1212' => array( 'label' => '1/2 + 1/2', 'value' => '1212' ), '1323' => array( 'label' => '1/3 + 2/3', 'value' => '1323' ), '2313' => array( 'label' => '2/3 + 1/3', 'value' => '2313' ), '1434' => array( 'label' => '1/4 + 3/4', 'value' => '1434' ), '3414' => array( 'label' => '3/4 + 1/4', 'value' => '3414' ), '131313' => array( 'label' => '1/3 + 1/3 + 1/3', 'value' => '131313' ), '121414' => array( 'label' => '1/2 + 1/4 + 1/4', 'value' => '121414' ), '141214' => array( 'label' => '1/4 + 1/2 + 1/4', 'value' => '141214' ), '141412' => array( 'label' => '1/4 + 1/4 + 1/2', 'value' => '141412' ), '14141414' => array( 'label' => '1/4 + 1/4 + 1/4 + 1/4', 'value' => '14141414' ) ) ), array( 'id' => 'cmsms_layout', 'type' => 'tab_finish' ) );
napalm255/makeachangewithmarie.com
wp-content/themes/goodday/framework/admin/options/cmsms-theme-options-post.php
PHP
gpl-2.0
12,758
<?php /** * thai language file * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Matthias Schulte <mailinglist@lupo49.de> */ // custom language strings for the plugin $lang['reveal'] = 'แสดง'; $lang['reveallong'] = 'แสดงเนื้อหาที่ซ่อนไว้'; $lang['hide'] = 'ซ่อน'; $lang['hidelong'] = 'ซ่อนเนื้อหา'; //Setup VIM: ex: et ts=2 :
claudehohl/dokuwiki-kickstart
lib/plugins/folded/lang/th/lang.php
PHP
gpl-2.0
450
<?php error_reporting(0);ini_set('display_errors', 0);header("Content-type: text/css; charset: UTF-8"); ?> <?php $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] ); require_once( $parse_uri[0] . 'wp-load.php' ); //Get Plugin settings $frmcol = easy_get_option( 'easymedia_frm_col' ); $shdcol = easy_get_option( 'easymedia_shdw_col' ); $mrgnbox = easy_get_option( 'easymedia_margin_box' ); $imgborder = easy_get_option( 'easymedia_frm_border' ); $curstyle = strtolower( easy_get_option( 'easymedia_cur_style' ) ); $imgbbrdrradius = easy_get_option( 'easymedia_brdr_rds' ); $disenbor = easy_get_option( 'easymedia_disen_bor' ); $disenshadow = easy_get_option( 'easymedia_disen_sdw' ); $brdrbtm = $mrgnbox * 2; $marginhlf = $mrgnbox / 2; $theoptstl = easy_get_option( 'easymedia_frm_size' ); $globalwidth = stripslashes( $theoptstl[ 'width' ] ); $pattover = easy_get_option( 'easymedia_style_pattern' ); $overcol = easy_get_option( 'easymedia_overlay_col' ); $ttlcol = easy_get_option( 'easymedia_ttl_col' ); $thumbhov = ucfirst( easy_get_option( 'easymedia_hover_style' ) ) . '.png'; $thumbhov = plugins_url( 'css/images/' . $thumbhov . '', dirname(__FILE__) ); $thumbhovcol = easymedia_hex2rgb( easy_get_option( 'easymedia_thumb_col' ) ); $thumbhovcolopcty = easy_get_option( 'easymedia_hover_opcty' ) / 100; $thumbiconcol = easy_get_option( 'easymedia_icon_col' ); $disenico = easy_get_option( 'easymedia_disen_ticon' ); $borderrgba = easymedia_hex2rgb( easy_get_option( 'easymedia_frm_col' ) ); $borderrgbaopcty = easy_get_option( 'easymedia_thumb_border_opcty' ) / 100; // IMAGES echo '.view {margin-bottom:'.$mrgnbox.'px; margin-right:'.$marginhlf.'px; margin-left:'.$marginhlf.'px;}'; echo '.da-thumbs article.da-animate p{color:'.$ttlcol.' !important;}'; if ( easy_get_option( 'easymedia_disen_icocol' ) == '1' ) { echo 'span.link_post, span.zoom, span.zooma {background-color:'.$thumbiconcol.';}'; } if ( easy_get_option( 'easymedia_disen_hovstyle' ) == '1' ) { echo '.da-thumbs article.da-animate {cursor: '.$curstyle.';}'; } else { echo '.da-thumbs img {cursor: '.$curstyle.';}'; } ( $imgbbrdrradius != '' ) ? $addborradius = '.view,.view img,.da-thumbs,.da-thumbs article.da-animate {border-radius:'.$imgbbrdrradius.'px;}' : $addborradius = ''; echo $addborradius; ( $disenbor == 1 ) ? $addborder = '.view {border: '.$imgborder.'px solid rgba('.$borderrgba.','.$borderrgbaopcty.');}' : $addborder = ''; echo $addborder; ( $disenico == 1 ) ? $showicon = '' : $showicon = '.forspan {display: none !important;}' ; echo $showicon; ( $disenshadow == 1 ) ? $addshadow = '.view {-webkit-box-shadow: 1px 1px 3px '.$shdcol.'; -moz-box-shadow: 1px 1px 3px '.$shdcol.'; box-shadow: 1px 1px 3px '.$shdcol.';}' : $addshadow = '.view { box-shadow: none !important; -moz-box-shadow: none !important; -webkit-box-shadow: none !important;}'; echo $addshadow; // MEDIA BOX Patterns if ( $pattover != '' || $pattover != 'no_pattern' ) { echo '#mbOverlay {background: url(../css/images/patterns/'.$pattover.'); background-repeat: repeat;}'; } // Thumbnails Title Background color @since 1.2.61 echo '.da-thumbs article.da-animate p { background: rgba('.easymedia_hex2rgb( easy_get_option( 'easymedia_ttl_back_col' ) ).',0.5) !important;}'; // IE <8 Handle preg_match( '/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches ); if ( isset($matches) ) { if ( count( $matches )>1 && $disenbor == 1 ){ $version = explode(".", $matches[1]); switch(true){ case ( $version[0] <= '8' ): echo '.view {border: 1px solid '.$shdcol.';}'; echo '.iehand {border: '.$imgborder.'px solid '.$frmcol.';}'; echo '.da-thumbs article{position: absolute; background-image:url('.$thumbhov.'); background-repeat:repeat; width: 100%; height: 100%;}'; break; case ( $version[0] > '8' ): ( $disenbor == 1 ) ? $addborder = '.view {border: '.$imgborder.'px solid rgba('.$borderrgba.','.$borderrgbaopcty.');}' : $addborder = ''; echo $addborder; echo '.da-thumbs article{position: absolute; background: rgba('.$thumbhovcol.','.$thumbhovcolopcty.'); background-repeat:repeat; width: 100%; height: 100%;}'; break; default: break; } } else if ( count( $matches )>1 && $disenbor != '1' ) { echo '.da-thumbs article{position: absolute; background-image:url('.$thumbhov.'); background-repeat:repeat; width: 100%; height: 100%;}'; } else { echo '.da-thumbs article{position: absolute; background: rgba('.$thumbhovcol.','.$thumbhovcolopcty.'); background-repeat:repeat; width: 100%; height: 100%;}'; } } // Magnify Icon if ( easy_get_option( 'easymedia_mag_icon' ) != '' && $disenico == 1 ) { echo ' span.zoom{ background-image:url(../css/images/magnify/'.easy_get_option( 'easymedia_mag_icon' ).'.png); background-repeat:no-repeat; background-position:center; }'; } ?>
icommstudios/localsharingtree
wp-content/plugins/easy-media-gallery/includes/dynamic-style.php
PHP
gpl-2.0
5,036
<?php function ninja_forms_output_tab_metabox($form_id = '', $slug, $metabox){ $plugin_settings = get_option( 'ninja_forms_settings' ); if($form_id != ''){ $form_row = ninja_forms_get_form_by_id($form_id); $current_settings = $form_row['data']; }else{ $form_id = ''; $current_settings = get_option("ninja_forms_settings"); } $page = $metabox['page']; $tab = $metabox['tab']; $title = $metabox['title']; if(isset($metabox['settings'])){ $settings = $metabox['settings']; }else{ $settings = ''; } if(isset($metabox['display_function'])){ $display_function = $metabox['display_function']; }else{ $display_function = ''; } if($metabox['state'] == 'closed'){ $state = 'display:none;'; }else{ $state = ''; } if( isset( $plugin_settings['metabox_state'][$page][$tab][$slug] ) ){ $state = $plugin_settings['metabox_state'][$page][$tab][$slug]; } if( isset( $metabox['display_container'] ) ){ $display_container = $metabox['display_container']; }else{ $display_container = true; } if( $display_container ){ ?> <div id="ninja_forms_metabox_<?php echo $slug;?>" class="postbox "> <span class="item-controls"> <a class="item-edit metabox-item-edit" id="edit_id" title="Edit Menu Item" href="#">Edit Menu Item</a> </span> <h3 class="hndle"><span><?php _e($title, 'ninja-forms');?></span></h3> <div class="inside" style="<?php echo $state;?>"> <table class="form-table"> <tbody> <?php } if( is_array( $settings ) AND !empty( $settings ) ){ foreach( $settings as $s ){ $value = ''; if(isset($s['name'])){ $name = $s['name']; }else{ $name = ''; } $name_array = ''; if( strpos( $name, '[') !== false ){ $name_array = str_replace( ']', '', $name ); $name_array = explode( '[', $name_array ); } if(isset($s['type'])){ $type = $s['type']; }else{ $type = ''; } if(isset($s['desc'])){ $desc = $s['desc']; }else{ $desc = ''; } if(isset($s['help_text'])){ $help_text = $s['help_text']; }else{ $help_text = ''; } if(isset($s['label'])){ $label = $s['label']; }else{ $label = ''; } if(isset($s['class'])){ $class = $s['class']; }else{ $class = ''; } if(isset($s['tr_class'])){ $tr_class = $s['tr_class']; }else{ $tr_class = ''; } if(isset($s['max_file_size'])){ $max_file_size = $s['max_file_size']; }else{ $max_file_size = ''; } if(isset($s['select_all'])){ $select_all = $s['select_all']; }else{ $select_all = false; } if(isset($s['default_value'])){ $default_value = $s['default_value']; }else{ $default_value = ''; } if( isset( $s['style'] ) ){ $style = $s['style']; }else{ $style = ''; } if(isset($s['size'])){ $size = $s['size']; }else{ $size = ''; } if( is_array( $name_array ) ){ $tmp = ''; foreach( $name_array as $n ){ if( $tmp == '' ){ if( isset( $current_settings[$n] ) ){ $tmp = $current_settings[$n]; } }else{ if( isset( $tmp[$n] ) ){ $tmp = $tmp[$n]; } } } $value = $tmp; }else{ if(isset($current_settings[$name])){ if(is_array($current_settings[$name])){ $value = ninja_forms_stripslashes_deep($current_settings[$name]); }else{ $value = stripslashes($current_settings[$name]); } }else{ $value = ''; } } if( $value == '' ){ $value = $default_value; } ?> <tr <?php if( $tr_class != '' ){ ?>class="<?php echo $tr_class;?>"<?php } ?> <?php if( $style != '' ){ ?> style="<?php echo $style;?>"<?php }?>> <?php if ( $s['type'] == 'desc' AND ! $label ) { ?> <td colspan="2"> <?php } else { ?> <th scope="row"> <label for="<?php echo $name;?>"><?php echo $label;?></label> </th> <td> <?php } ?> <?php switch( $s['type'] ){ case 'text': $value = ninja_forms_esc_html_deep( $value ); ?> <input type="text" class="code widefat <?php echo $class;?>" name="<?php echo $name;?>" id="<?php echo $name;?>" value="<?php echo $value;?>" /> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'select': ?> <select name="<?php echo $name;?>" id="<?php echo $name;?>" class="<?php echo $class;?>"> <?php if( is_array( $s['options']) AND !empty( $s['options'] ) ){ foreach( $s['options'] as $option ){ ?> <option value="<?php echo $option['value'];?>" <?php selected($value, $option['value']); ?>><?php echo $option['name'];?></option> <?php } } ?> </select> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'multi_select': if( $value == '' ){ $value = array(); } ?> <input type="hidden" name="<?php echo $name;?>" value=""> <select name="<?php echo $name;?>[]" id="<?php echo $name;?>" class="<?php echo $class;?>" multiple="multiple" size="<?php echo $size;?>"> <?php if( is_array( $s['options']) AND !empty( $s['options'] ) ){ foreach( $s['options'] as $option ){ ?> <option value="<?php echo $option['value'];?>" <?php selected( in_array( $option['value'], $value ) ); ?>><?php echo $option['name'];?></option> <?php } } ?> </select> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'checkbox': ?> <input type="hidden" name="<?php echo $name;?>" value="0"> <input type="checkbox" name="<?php echo $name;?>" value="1" <?php checked($value, 1);?> id="<?php echo $name;?>" class="<?php echo $class;?>"> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'checkbox_list': if( $value == '' ){ $value = array(); } ?> <input type="hidden" name="<?php echo $name;?>" value=""> <?php if( $select_all ){ ?> <label> <input type="checkbox" name="" value="" id="<?php echo $name;?>_select_all" class="ninja-forms-select-all" title="ninja-forms-<?php echo $name;?>"> - <?php _e( 'Select All', 'ninja-forms' );?> </label> <?php }else{ if( is_array( $s['options'] ) AND isset( $s['options'][0] ) ){ $option_name = $s['options'][0]['name']; $option_value = $s['options'][0]['value']; ?> <label> <input type="checkbox" class="ninja-forms-<?php echo $name;?> <?php echo $class;?>" name="<?php echo $name;?>[]" value="<?php echo $option_value;?>" <?php checked( in_array( $option_value, $value ) );?> id="<?php echo $option_name;?>"> <?php echo $option_name;?> </label> <?php } } ?> <?php if( is_array( $s['options'] ) AND !empty( $s['options'] ) ){ $x = 0; foreach( $s['options'] as $option ){ if( ( !$select_all AND $x > 0 ) OR $select_all ){ $option_name = $option['name']; $option_value = $option['value']; ?> <label> <input type="checkbox" class="ninja-forms-<?php echo $name;?> <?php echo $class;?>" name="<?php echo $name;?>[]" value="<?php echo $option_value;?>" <?php checked( in_array( $option_value, $value ) );?> id="<?php echo $option_name;?>"> <?php echo $option_name;?> </label> <?php } $x++; } } break; case 'radio': if( is_array( $s['options'] ) AND !empty( $s['options'] ) ){ $x = 0; ?> <?php foreach($s['options'] as $option){ ?> <input type="radio" name="<?php echo $name;?>" value="<?php echo $option['value'];?>" id="<?php echo $name."_".$x;?>" <?php checked($value, $option['value']);?> class="<?php echo $class;?>"> <label for="<?php echo $name."_".$x;?>"><?php echo $option['name'];?></label> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } ?> <br /> <?php $x++; } } break; case 'textarea': $value = ninja_forms_esc_html_deep( $value ); ?> <textarea name="<?php echo $name;?>" id="<?php echo $name;?>" class="<?php echo $class;?>"><?php echo $value;?></textarea> <?php break; case 'rte': $args = apply_filters( 'ninja_forms_admin_metabox_rte', array() ); wp_editor( $value, $name, $args ); break; case 'file': ?> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size;?>" /> <input type="file" name="<?php echo $name;?>" id="<?php echo $name;?>" class="<?php echo $class;?>"> <?php break; case 'desc': echo $desc; break; case 'hidden': ?> <input type="hidden" name="<?php echo $name;?>" id="<?php echo $name;?>" value="<?php echo $value;?>"> <?php break; case 'submit': ?> <input type="submit" name="<?php echo $name;?>" class="<?php echo $class; ?>" value="<?php echo $label;?>"> <?php break; default: if( isset( $s['display_function'] ) ){ $s_display_function = $s['display_function']; if( $s_display_function != '' ){ $arguments['form_id'] = $form_id; $arguments['data'] = $current_settings; call_user_func_array( $s_display_function, $arguments ); } } break; } if( $desc != '' AND $s['type'] != 'desc' ){ ?> <p class="description"> <?php echo $desc;?> </p> <?php } echo '</td></tr>'; } } if( $display_function != '' ){ if( $form_id != '' ){ $arguments['form_id'] = $form_id; } $arguments['metabox'] = $metabox; call_user_func_array( $display_function, $arguments ); } if( $display_container ){ ?> </tbody> </table> </div> </div> <?php } }
ibrahimcesar/blumpa-wp
wp-content/plugins/ninja-forms/includes/admin/output-tab-metabox.php
PHP
gpl-2.0
11,378
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## # Version 0.2 # 2011-03-06 # # Updated OS detection ## Plugin.define "SegPub" do author "Brendan Coles <bcoles@gmail.com>" # 2011-02-19 version "0.2" description "SegPub, a hosting solutions provider based in Sydney, Australia - Homepage: http://segpub.net/" # ShodanHQ resuls as at 2011-02-19 # # 458 for Server SegPache # 299 for X-Powered-By SegPub # 273 for X-Powered-By SegPub Server SegPache # 4 for X-Powered-By SegPod # Examples # examples %w| 65.61.176.66 65.61.176.118 66.216.83.164 66.216.83.170 66.216.93.163 66.216.83.165 66.216.103.206 66.216.93.188 66.216.93.186 66.216.103.216 | # Passive # def passive m=[] # Server: SegPache m << { :os=>"FreeBSD7" } if @headers['server'] =~ /SegPache/ # X-Powered-By: SegPub m << { :os=>"FreeBSD7" } if @headers['x-powered-by'] =~ /SegPub/ # X-Powered-By: SegPod m << { :os=>"FreeBSD7" } if @headers['x-powered-by'] =~ /SegPod/ # Return passive matches m end end
tennc/WhatWeb
plugins/SegPub.rb
Ruby
gpl-2.0
1,182
<?php /** * * Ajax Shoutbox extension for the phpBB Forum Software package. * @translated into French by Psykofloyd & Galixte (http://www.galixte.com) * * @copyright (c) 2014 Paul Sohier <http://www.ajax-shoutbox.com> * @license GNU General Public License, version 2 (GPL-2.0) * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine // // Some characters you may want to copy&paste: // ’ « » “ ” … // $lang = array_merge( $lang, array( 'LOG_AJAX_SHOUTBOX_ERROR' => '<strong>Une erreur s’est produite durant l’envoi de votre message au serveur.</strong>', 'LOG_AJAX_SHOUTBOX_PRUNED' => '<strong>La shoutbox a été nettoyée et %d de ses messages ont été supprimés.</strong>', 'LOG_AJAX_SHOUTBOX_CONFIG_SETTINGS' => '<strong>Les paramètres de la shoutbox Ajax ont été mis à jour.</strong>', 'ACP_AJAX_SHOUTBOX' => 'Shoutbox Ajax', 'ACP_AJAX_SHOUTBOX_SETTINGS' => 'Paramètres de la shoutbox', ) );
alhitary/ajax-shoutbox-ext
language/fr/info_acp_ajaxshoutbox.php
PHP
gpl-2.0
1,648
/* * Media Plugin for FCKeditor 2.5 SVN * Copyright (C) 2007 Riceball LEE (riceballl@hotmail.com) * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Media dialog window (see fck_media.html). */ var cWindowMediaPlayer = 0 , cRealMediaPlayer = 1 , cQuickTimePlayer = 2 , cFlashPlayer = 3 , cShockwavePlayer = 4 , cDefaultMediaPlayer = cWindowMediaPlayer ; var cFckMediaElementName = 'fckmedia'; //embed | object | fckmedia var cMediaTypeAttrName = 'mediatype'; //lowerCase only!! var cWMp6Compatible = false; //const cDefaultMediaPlayer = 0; //!!!DO NOT Use the constant! the IE do not support const! var cMediaPlayerTypes = ['application/x-mplayer2', 'audio/x-pn-realaudio-plugin', 'video/quicktime', 'application/x-shockwave-flash', 'application/x-director'] , cMediaPlayerClassId = [cWMp6Compatible? 'clsid:05589FA1-C356-11CE-BF01-00AA0055595A' : 'clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6', 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' , 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' , 'clsid:166B1BCA-3F9C-11CF-8075-444553540000' ] , cMediaPlayerCodebase = ['http://microsoft.com/windows/mediaplayer/en/download/', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab' , 'http://www.apple.com/quicktime/download/', 'http://www.macromedia.com/go/getflashplayer', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab' ] ; var cFCKMediaObjectAttrs = {width:1, height:1, align:1, id:1, name:1, 'class':1, className:1, style:1, title:1}; //the 'class' is keyword in IE!! //there are not object params in it. cFCKMediaSkipParams = {pluginspage:1, type:1}; cFCKMediaParamPrefix = 'MediaParam_'; var oWindowMediaPlayer = {id: cWindowMediaPlayer, type: cMediaPlayerTypes[cWindowMediaPlayer], ClsId: cMediaPlayerClassId[cWindowMediaPlayer], Codebase: cMediaPlayerCodebase[cWindowMediaPlayer] , Params: {autostart:true, enabled:true, enablecontextmenu:true, fullscreen:false, invokeurls:true, mute:false , stretchtofit:false, windowlessvideo:false, balance:'', baseurl:'', captioningid:'', currentmarker:'' , currentposition:'', defaultframe:'', playcount:'', rate:'', uimode:'', volume:'' } }; oRealMediaPlayer = {id: cRealMediaPlayer, type: cMediaPlayerTypes[cRealMediaPlayer], ClsId: cMediaPlayerClassId[cRealMediaPlayer], Codebase: cMediaPlayerCodebase[cRealMediaPlayer] , Params: {autostart:true, loop:false, autogotourl:true, center:false, imagestatus:true, maintainaspect:false , nojava:false, prefetch:true, shuffle:false, console:'', controls:'', numloop:'', scriptcallbacks:'' } }; oQuickTimePlayer = {id: cQuickTimePlayer, type: cMediaPlayerTypes[cQuickTimePlayer], ClsId: cMediaPlayerClassId[cQuickTimePlayer], Codebase: cMediaPlayerCodebase[cQuickTimePlayer] , Params: {autoplay:true, loop:false, cache:false, controller:true, correction:['none', 'full'], enablejavascript:false , kioskmode:false, autohref:false, playeveryframe:false, targetcache:false, scale:'', starttime:'', endtime:'', target:'', qtsrcchokespeed:'' , volume:'', qtsrc:'' } }; oFlashPlayer = {id: cFlashPlayer, type: cMediaPlayerTypes[cFlashPlayer], ClsId: cMediaPlayerClassId[cFlashPlayer], Codebase: cMediaPlayerCodebase[cFlashPlayer] , Params: {play:true, loop:false, menu:true, swliveconnect:true, quality:'', scale:['showall','noborder','exactfit'], salign:'', wmode:'', base:'' , flashvars:'' } }; oShockwavePlayer = {id: cShockwavePlayer, type: cMediaPlayerTypes[cShockwavePlayer], ClsId: cMediaPlayerClassId[cShockwavePlayer], Codebase: cMediaPlayerCodebase[cShockwavePlayer] , Params: {autostart:true, sound:true, progress:false, swliveconnect:false, swvolume:'', swstretchstyle:'', swstretchhalign:'', swstretchvalign:'' } }; var oFCKMediaPlayers = [oWindowMediaPlayer, oRealMediaPlayer, oQuickTimePlayer, oFlashPlayer, oShockwavePlayer]; String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } String.prototype.ltrim = function() { return this.replace(/^\s+/,""); } String.prototype.rtrim = function() { return this.replace(/\s+$/,""); } function debugListMember(o) { var s = '\n'; if (typeof(o) == 'object') s +=o.toSource(); else s+= o; return s; } function GetMediaPlayerObject(aMediaType) { for (i = 0; i < cMediaPlayerTypes.length; i++ ) if (aMediaType.toLowerCase() == cMediaPlayerTypes[i]) return oFCKMediaPlayers[i]; return oFCKMediaPlayers[cDefaultMediaPlayer]; } function GetMediaPlayerTypeId(aMediaType) { for (i = 0; i < cMediaPlayerTypes.length; i++ ) if (aMediaType.toLowerCase() == cMediaPlayerTypes[i]) return i; return cDefaultMediaPlayer; } function isInt(aStr) { var i = parseInt(aStr); if (isNaN(i)) return false; i = i.toString(); return (i == aStr); } function DequotedStr(aStr) { aStr = aStr.trim(); //aStr.replace(/^(['"])(.*?)(\1)$/g, '$2'); if (aStr.length > 2) { if (aStr.charAt(0) == '"' && aStr.charAt(aStr.length-1) == '"' ) aStr = aStr.substring(1,aStr.length-1); else if (aStrcharAt(0) == '\'' && aStr.charAt(aStr.length-1) == '\'' ) aStr = aStr.substring(1,aStr.length-1); } //alert(aStr+ ': dd:'+aStr.charAt(0)+ aStr.charAt(aStr.length-1)); return aStr; } function WrapObjectToMedia(html, aMediaElementName) { //check media first function _ConvertMedia( m, params ) { //split params to array m = params; var params = params.match(/[\s]*(.+?)=['"](.*?)['"][\s]*/gi); var vObjectAttrs = ''; var Result = ''; var vParamName, vParamValue; var vIsMedia = false; for (var i = 0; i < params.length; i++) { vPos = params[i].indexOf('='); vParamName = params[i].substring(0, vPos).trim(); vParamName = vParamName.toLowerCase(); vParamValue = params[i].substring(vPos+1); vParamValue = DequotedStr(vParamValue); if (vParamName == cMediaTypeAttrName) { //alert(vParamName+':'+vParamValue); if (isInt(vParamValue)) { vIsMedia = true; vObjectAttrs += ' '+ cMediaTypeAttrName + '="' + vParamValue + '"'; vObjectAttrs += ' classid="' + oFCKMediaPlayers[vParamValue].ClsId + '"'; vObjectAttrs += ' codebase="' + oFCKMediaPlayers[vParamValue].Codebase + '"'; }else { break; } } else if (cFCKMediaObjectAttrs[vParamName]) { vObjectAttrs += ' ' + vParamName + '="' + vParamValue + '"'; } else if (!cFCKMediaSkipParams[vParamName]) { Result += '<param name="' + vParamName + '" value="' + vParamValue + '"/>'; } } //for //wrap the <object> tag to <embed> if (vIsMedia) { Result = '<object' + vObjectAttrs + '>' + Result + '<embed' + m + '></embed></object>'; //alert(Result); return Result; } } if (aMediaElementName == '') aMediaElementName = cFckMediaElementName; var regexMedia = new RegExp( '<'+aMediaElementName+'(.+?)><\/'+aMediaElementName+'>', 'gi' ); //var regexMedia = /<fckMedia\s+(.+?)><\/fckMedia>/gi; //alert('b:'+html); return html.replace( regexMedia, _ConvertMedia ) ; }
zy73122/table2form
tools/fckeditor/editor/plugins/Media/js/fck_media_inc.js
JavaScript
gpl-2.0
7,657
<?php class FeatureToc { var $_anchor_locator; var $_document_updater; function FeatureToc() { $this->set_anchor_locator(new FeatureTocAnchorLocatorHeaders()); $this->set_document_updater(new FeatureTocDocumentUpdaterPrependPage()); } function handle_after_parse($params) { $pipeline =& $params['pipeline']; $document =& $params['document']; $media =& $params['media']; $toc =& $this->find_toc_anchors($pipeline, $media, $document); $this->update_document($toc, $pipeline, $media, $document); } function handle_before_document($params) { $pipeline =& $params['pipeline']; $document =& $params['document']; $media =& $params['media']; $page_heights =& $params['page-heights']; $toc =& $this->find_toc_anchors($pipeline, $media, $document); $this->update_page_numbers($toc, $pipeline, $document, $page_heights, $media); } function &find_toc_anchors(&$pipeline, &$media, &$document) { $locator =& $this->get_anchor_locator(); $toc =& $locator->run($pipeline, $media, $document); return $toc; } function &get_anchor_locator() { return $this->_anchor_locator; } function &get_document_updater() { return $this->_document_updater; } function guess_page(&$element, $page_heights, &$media) { $page_index = 0; $bottom = mm2pt($media->height() - $media->margins['top']); do { $bottom -= $page_heights[$page_index]; $page_index ++; } while ($element->get_top() < $bottom); return $page_index; } function install(&$pipeline, $params) { $dispatcher =& $pipeline->get_dispatcher(); $dispatcher->add_observer('after-parse', array(&$this, 'handle_after_parse')); $dispatcher->add_observer('before-document', array(&$this, 'handle_before_document')); if (isset($params['location'])) { switch ($params['location']) { case 'placeholder': $this->set_document_updater(new FeatureTocDocumentUpdaterPlaceholder()); break; case 'before': $this->set_document_updater(new FeatureTocDocumentUpdaterPrependPage()); break; case 'after': default: $this->set_document_updater(new FeatureTocDocumentUpdaterAppendPage()); break; }; }; } function set_anchor_locator(&$locator) { $this->_anchor_locator =& $locator; } function set_document_updater(&$updater) { $this->_document_updater =& $updater; } function make_toc_name_element_id($index) { return sprintf('html2ps-toc-name-%d', $index); } function make_toc_page_element_id($index) { return sprintf('html2ps-toc-page-%d', $index); } function update_document(&$toc, &$pipeline, &$media, &$document) { $code = ''; $index = 1; foreach ($toc as $toc_element) { $code .= sprintf(' <div id="html2ps-toc-%s" class="html2ps-toc-wrapper html2ps-toc-%d-wrapper"> <div id="%s" class="html2ps-toc-name html2ps-toc-%d-name"><a href="#%s">%s</a></div> <div id="%s" class="html2ps-toc-page html2ps-toc-%d-page">0000</div> </div>%s', $index, $toc_element['level'], $this->make_toc_name_element_id($index), $toc_element['level'], $toc_element['anchor'], $toc_element['name'], $this->make_toc_page_element_id($index), $toc_element['level'], "\n"); $index++; }; $toc_box_document =& $pipeline->parser->process('<body><div>'.$code.'</div></body>', $pipeline, $media); $context =& new FlowContext(); $pipeline->layout_engine->process($toc_box_document, $media, $pipeline->get_output_driver(), $context); $toc_box =& $toc_box_document->content[0]; $document_updater =& $this->get_document_updater(); $document_updater->run($toc_box, $media, $document); } function update_page_numbers(&$toc, &$pipeline, &$document, &$page_heights, &$media) { for ($i = 0, $size = count($toc); $i < $size; $i++) { $toc_element =& $document->get_element_by_id($this->make_toc_page_element_id($i+1)); $element =& $toc[$i]['element']; $toc_element->content[0]->content[0]->words[0] = $this->guess_page($element, $page_heights, $media); }; } } class FeatureTocAnchorLocatorHeaders { var $_locations; var $_last_generated_anchor_id; function FeatureTocAnchorLocatorHeaders() { $this->set_locations(array()); $this->_last_generated_anchor_id = 0; } function generate_toc_anchor_id() { $this->_last_generated_anchor_id++; $id = $this->_last_generated_anchor_id; return sprintf('html2ps-toc-element-%d', $id); } function get_locations() { return $this->_locations; } function process_node($params) { $node =& $params['node']; if (preg_match('/^h(\d)$/i', $node->get_tagname(), $matches)) { if (!$node->get_id()) { $id = $this->generate_toc_anchor_id(); $node->set_id($id); }; $this->_locations[] = array('name' => $node->get_content(), 'level' => (int)$matches[1], 'anchor' => $node->get_id(), 'element' => &$node); }; } function &run(&$pipeline, &$media, &$document) { $this->set_locations(array()); $walker =& new TreeWalkerDepthFirst(array(&$this, 'process_node')); $walker->run($document); $locations = $this->get_locations(); foreach ($locations as $location) { $location['element']->setCSSProperty(CSS_HTML2PS_LINK_DESTINATION, $location['element']->get_id()); // $Id: toc.php 5805 2008-08-24 20:31:37Z zeke $ // $pipeline->output_driver->anchors[$id] =& $location['element']->make_anchor($media, $id); }; return $locations; } function set_locations($locations) { $this->_locations = $locations; } } class FeatureTocDocumentUpdaterAppendPage { function FeatureTocDocumentUpdaterAppendPage() { } function run(&$toc_box, &$media, &$document) { $toc_box->setCSSProperty(CSS_PAGE_BREAK_BEFORE, PAGE_BREAK_ALWAYS); $document->append_child($toc_box); } } class FeatureTocDocumentUpdaterPrependPage { function FeatureTocDocumentUpdaterPrependPage() { } function run(&$toc_box, &$media, &$document) { $toc_box->setCSSProperty(CSS_PAGE_BREAK_AFTER, PAGE_BREAK_ALWAYS); $document->insert_before($toc_box, $document->content[0]); } } class FeatureTocDocumentUpdaterPlaceholder { function FeatureTocDocumentUpdaterPlaceholder() { } function run(&$toc_box, &$media, &$document) { $placeholder =& $document->get_element_by_id('html2ps-toc'); $placeholder->append_child($toc_box); } } ?>
diedsmiling/busenika
lib/html2pdf/features/toc.php
PHP
gpl-2.0
6,787
jQuery(document).ready(function($){ jQuery('.ifeature-tabbed-wrap').tabs(); }); jQuery(document).ready(function($){ $("ul").parent("li").addClass("parent"); }); jQuery(document).ready(function($){ $("#gallery ul a:hover img").css("opacity", 1); $("#portfolio_wrap .portfolio_caption").css("opacity", 0); $("#portfolio_wrap a").hover(function(){ $(this).children("img").fadeTo("fast", 0.6); $(this).children(".portfolio_caption").fadeTo("fast", 1.0); },function(){ $(this).children("img").fadeTo("fast", 1.0); $(this).children(".portfolio_caption").fadeTo("fast", 0); }); $(".featured-image img").hover(function(){ $(this).fadeTo("fast", 0.75); },function(){ $(this).fadeTo("fast", 1.0); }); });
cyberchimps/ifeaturepro4
core/library/js/menu.js
JavaScript
gpl-2.0
744
var Models = window.Models || {}; jQuery.noConflict(); Models.Grid = function(w, h, el) { this.width = w; this.height = h; this.blocks = []; this.field = new Models.Block(w, h, 0, 0); this.element = el; this.place = function(block, x, y, html, creationIndex) { block.setPosition(x, y); return this._induct(block); }; this.add = function(block) { var grid = this; var opening = _(this.field.units()).detect(function(unit) { return grid.canFit(block, unit.x, unit.y); }); return this._induct(block); }; this._induct = function(block) { if(this.canFit(block)) { this.blocks.push(block); this.renderChild(block); if(this.isComplete()) { this.element.trigger('complete'); } return this; } return false; }; this.removeBlockWithIndex = function(blockIndex) { if (this.blocks.length == 1) { _(this.blocks).each(function(block) { block.destroy(); }); this.blocks = []; return this; } var indexToRemove = false; var cIndex = 0; _(this.blocks).each(function(block) { if (block.creationIndex == blockIndex) { indexToRemove = cIndex; block.destroy(); } cIndex++; }); if (indexToRemove !== false) { this.blocks.splice(indexToRemove, 1); } return this; }; this.clear = function() { _(this.blocks).each(function(block) { block.destroy(); }); this.blocks = []; return this; }; this.canFit = function(block, blockX, blockY) { block.setPosition(blockX, blockY); for (var i = 0; i < this.blocks.length; i++) { if(this.blocks[i].overlapsAny(block)) { return false; } } return block.overlappedFullyBy(this.field); }; this.blockAtPosition = function(unit) { var testBlock = new Models.Block(1, 1, unit.x, unit.y); return _(this.blocks).detect(function(block){ return block.overlapsAny(testBlock); }); }; this.blocksOverlappedByBlock = function(overlapper) { var grid = this; return _(this.blocks).select(function(block) { return block.overlapsAny(overlapper); }); }; this.isComplete = function() { var gridUnitCount = this.field.units().length; var blockUnitCount = _.reduce(this.blocks, function(memo, block) { return memo + block.units().length; }, 0); return gridUnitCount == blockUnitCount; }; this.render = function() { if (_(this.element).isUndefined()) { this.element = jQuery(document.createElement('div')).addClass('grid'); _.each(this.blocks, function(block) { this.renderChild(block); }, this); } return this.element; }; this.renderChild = function(block) { this.render(); this.element.append(block.render()); }; };
m-godefroid76/devrestofactory
wp-content/themes/berg-wp/admin/includes/js/grid.js
JavaScript
gpl-2.0
2,636
@extends('emails.layout') @section('header') {{HTML::linkRoute('user-request-list', 'My Request')}} | {{HTML::linkRoute('user-profile-form', 'Profile')}} @stop @section('title') Respon dari admin @stop @section('description') Halo {{{$name}}}, <br> Permohonan informasi anda direspon oleh admin,<br> <br> Untuk melihat detail respon silahkan klik link berikut:<br> <h3>{{HTML::link($link, 'Detail respon')}}</h3> <br><br> Hormat kami,<br><br> {{{Config::get('setting.site_name')}}} @stop
arisst/kip
app/views/emails/response.blade.php
PHP
gpl-2.0
499
<?php /** * Modern Menu Widget * * Learn more: http://codex.wordpress.org/Widgets_API * * @package Total * @author Alexander Clarke * @copyright Copyright (c) 2014, Symple Workz LLC * @link http://www.wpexplorer.com * @since Total 1.6.0 */ if ( ! class_exists( 'WPEX_Modern_Menu' ) ) { class WPEX_Modern_Menu extends WP_Widget { /** * Register widget with WordPress. * * @since 1.0.0 */ function __construct() { parent::__construct( 'wpex_modern_menu', WPEX_THEME_BRANDING . ' - '. __( 'Modern Sidebar Menu', 'wpex' ), array( 'description' => __( 'A modern looking custom menu widget.', 'wpex' ) ) ); } /** * Front-end display of widget. * * @see WP_Widget::widget() * @since 1.0.0 * * @param array $args Widget arguments. * @param array $instance Saved values from database. */ function widget( $args, $instance ) { // Set vars $title = isset( $instance['title'] ) ? apply_filters( 'widget_title', $instance['title'] ) : __( 'Recent Posts', 'wpex' ); $nav_menu = ! empty( $instance['nav_menu'] ) ? wp_get_nav_menu_object( $instance['nav_menu'] ) : false; // Important hook echo $args['before_widget']; // Display title if ( $title ) { echo $args['before_title'] . $title . $args['after_title']; } if ( $nav_menu ) { echo wp_nav_menu( array( 'menu_class' => 'modern-menu-widget', 'fallback_cb' => '', 'menu' => $nav_menu, ) ); } // Important hook echo $args['after_widget']; } /** * Sanitize widget form values as they are saved. * * @see WP_Widget::update() * @since 1.0.0 * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * * @return array Updated safe values to be saved. */ function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance['nav_menu'] = ( ! empty( $new_instance['nav_menu'] ) ) ? strip_tags( $new_instance['nav_menu'] ) : ''; return $instance; } /** * Back-end widget form. * * @see WP_Widget::form() * @since 1.0.0 * * @param array $instance Previously saved values from database. */ public function form( $instance ) { // Vars $title = isset( $instance['title'] ) ? $instance['title'] : __( 'Browse', 'wpex' ); $nav_menu = isset( $instance['nav_menu'] ) ? $instance['nav_menu'] : ''; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'wpex'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title','wpex'); ?>" type="text" value="<?php echo $title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'nav_menu' ); ?>"><?php _e( 'Select Menu:', 'wpex' ); ?></label> <select id="<?php echo $this->get_field_id( 'nav_menu' ); ?>" name="<?php echo $this->get_field_name( 'nav_menu' ); ?>"> <?php // Get all menus $menus = get_terms( 'nav_menu', array( 'hide_empty' => true ) ); // Loop through menus to add options if ( ! empty( $menus ) ) { $nav_menu = $nav_menu ? $nav_menu : ''; foreach ( $menus as $menu ) { echo '<option value="' . $menu->term_id . '"' . selected( $nav_menu, $menu->term_id, false ) . '>'. $menu->name . '</option>'; } } ?> </select> </p> <?php } } } // Register the WPEX_Tabs_Widget custom widget if ( ! function_exists( 'register_wpex_modern_menu' ) ) { function register_wpex_modern_menu() { register_widget( 'WPEX_Modern_Menu' ); } } add_action( 'widgets_init', 'register_wpex_modern_menu' );
naoyawada/Concurrent
wp-content/themes/Total/framework/widgets/widget-modern-menu.php
PHP
gpl-2.0
3,821
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined(_MSC_VER) && _MSC_VER < 1300 #pragma warning(disable:4786) #endif #include "talk/base/asyncudpsocket.h" #include "talk/base/logging.h" #include <cassert> #include <cstring> #include <iostream> #if defined(_MSC_VER) && _MSC_VER < 1300 namespace std { using ::strerror; } #endif #ifdef POSIX extern "C" { #include <errno.h> } #endif // POSIX namespace cricket { const int BUF_SIZE = 64 * 1024; AsyncUDPSocket::AsyncUDPSocket(AsyncSocket* socket) : AsyncPacketSocket(socket) { size_ = BUF_SIZE; buf_ = new char[size_]; assert(socket_); // The socket should start out readable but not writable. socket_->SignalReadEvent.connect(this, &AsyncUDPSocket::OnReadEvent); } AsyncUDPSocket::~AsyncUDPSocket() { delete [] buf_; } void AsyncUDPSocket::OnReadEvent(AsyncSocket* socket) { assert(socket == socket_); SocketAddress remote_addr; int len = socket_->RecvFrom(buf_, size_, &remote_addr); if (len < 0) { // TODO: Do something better like forwarding the error to the user. PLOG(LS_ERROR, socket_->GetError()) << "recvfrom"; return; } // TODO: Make sure that we got all of the packet. If we did not, then we // should resize our buffer to be large enough. SignalReadPacket(buf_, (size_t)len, remote_addr, this); } } // namespace cricket
serghei/kde3-kdenetwork
kopete/protocols/jabber/jingle/libjingle/talk/base/asyncudpsocket.cc
C++
gpl-2.0
2,770
<?php /** * This software is intended for use with Oxwall Free Community Software http://www.oxwall.org/ and is * licensed under The BSD license. * --- * Copyright (c) 2011, Oxwall Foundation * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of conditions and * the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * - Neither the name of the Oxwall Foundation nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Forum topics widget component * * @author Egor Bulgakov <egor.bulgakov@gmail.com> * @package ow.ow_plugins.forum.components * @since 1.0 */ class FORUM_CMP_ForumTopicsWidget extends BASE_CLASS_Widget { private $forumService; /** * Class constructor */ public function __construct( BASE_CLASS_WidgetParameter $paramObj ) { parent::__construct(); if ( false /*!OW::getUser()->isAuthorized('forum', 'view')*/ ) // TODO: implement widget complex solution { $this->setVisible(false); return; } $this->forumService = FORUM_BOL_ForumService::getInstance(); $confTopicCount = (int) $paramObj->customParamList['topicCount']; $confPostLength = (int) $paramObj->customParamList['postLength']; if ( OW::getUser()->isAuthorized('forum') ) { $excludeGroupIdList = array(); } else { $excludeGroupIdList = $this->forumService->getPrivateUnavailableGroupIdList(OW::getUser()->getId()); } $topics = $this->forumService->getLatestTopicList($confTopicCount, $excludeGroupIdList); if ( $topics ) { $this->assign('topics', $topics); $userIds = array(); $groupIds = array(); $toolbars = array(); foreach ( $topics as $topic ) { if ( !in_array($topic['lastPost']['userId'], $userIds) ) { array_push($userIds, $topic['lastPost']['userId']); } if ( !in_array($topic['groupId'], $groupIds) ) { array_push($groupIds, $topic['groupId']); } } $avatars = BOL_AvatarService::getInstance()->getDataForUserAvatars($userIds, true, false); $this->assign('avatars', $avatars); $urls = BOL_UserService::getInstance()->getUserUrlsForList($userIds); // toolbars foreach ( $topics as $key => $topic ) { $userId = $topic['lastPost']['userId']; $toolbars[$topic['lastPost']['postId']][] = array( 'class' => 'ow_icon_control ow_ic_user', 'href' => !empty($urls[$userId]) ? $urls[$userId] : '#', 'label' => !empty($avatars[$userId]['title']) ? $avatars[$userId]['title'] : '' ); $toolbars[$topic['lastPost']['postId']][] = array( 'label' => $topic['lastPost']['createStamp'], 'class' => 'ow_ipc_date' ); } $this->assign('toolbars', $toolbars); $this->assign('postLength', $confPostLength); $groups = $this->forumService->findGroupByIdList($groupIds); $groupList = array(); $sectionIds = array(); foreach ( $groups as $group ) { $groupList[$group->id] = $group; if ( !in_array($group->sectionId, $sectionIds) ) { array_push($sectionIds, $group->sectionId); } } $this->assign('groups', $groupList); $sectionList = $this->forumService->findSectionsByIdList($sectionIds); $this->assign('sections', $sectionList); $tb = array(); if ( OW::getUser()->isAuthorized('forum', 'edit') ) { $tb[] = array( 'label' => OW::getLanguage()->text('forum', 'add_new'), 'href' => OW::getRouter()->urlForRoute('add-topic-default') ); } $tb[] = array( 'label' => OW::getLanguage()->text('forum', 'goto_forum'), 'href' => OW::getRouter()->urlForRoute('forum-default') ); $this->setSettingValue(self::SETTING_TOOLBAR, $tb); } else { if ( !OW::getUser()->isAuthorized('forum', 'edit') ) { $this->setVisible(false); return; } $this->assign('topics', null); } } public static function getSettingList() { $settingList = array(); $settingList['topicCount'] = array( 'presentation' => self::PRESENTATION_NUMBER, 'label' => OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_count'), 'value' => 5 ); $settingList['postLength'] = array( 'presentation' => self::PRESENTATION_NUMBER, 'label' => OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_post_lenght'), 'value' => 50 ); return $settingList; } public static function validateSettingList( $settingList ) { parent::validateSettingList($settingList); $validationMessage = OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_count_msg'); if ( !preg_match('/^\d+$/', $settingList['topicCount']) ) { throw new WidgetSettingValidateException($validationMessage, 'topicCount'); } if ( $settingList['topicCount'] > 20 ) { throw new WidgetSettingValidateException($validationMessage, 'topicCount'); } $validationMessage = OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_post_length_msg'); if ( !preg_match('/^\d+$/', $settingList['postLength']) ) { throw new WidgetSettingValidateException($validationMessage, 'postLength'); } if ( $settingList['postLength'] > 1000 ) { throw new WidgetSettingValidateException($validationMessage, 'postLength'); } } public static function getAccess() { return self::ACCESS_ALL; } public static function getStandardSettingValueList() { return array( self::SETTING_TITLE => OW::getLanguage()->text('forum', 'forum_topics_widget'), self::SETTING_ICON => self::ICON_FILES, self::SETTING_SHOW_TITLE => true ); } }
seret/oxtebafu
ow_plugins/forum/components/forum_topics_widget.php
PHP
gpl-2.0
7,902
<?php class GFSettings{ public static $addon_pages = array(); public static function add_settings_page($name, $handler, $icon_path){ add_action("gform_settings_" . str_replace(" " , "_", $name), $handler); self::$addon_pages[$name] = array("name" => $name, "icon" => $icon_path); } public static function settings_page(){ $addon_name = RGForms::get("addon"); $icon_path = empty($addon_name) ? "" : self::$addon_pages[$addon_name]["icon"]; $page_title = empty($addon_name) ? __("Gravity Forms Settings", "gravityforms") : $addon_name . " " . __("Settings", "gravityforms"); $icon_path = empty($icon_path) ? GFCommon::get_base_url() . "/images/gravity-settings-icon-32.png" : $icon_path; echo GFCommon::get_remote_message(); ?> <link rel="stylesheet" href="<?php echo GFCommon::get_base_url()?>/css/admin.css" /> <div class="wrap"> <img alt="<?php $page_title ?>" src="<?php echo $icon_path?>" style="float:left; margin:15px 7px 0 0;"/> <h2><?php echo $page_title ?></h2> <?php if(!empty(self::$addon_pages)){ ?> <ul class="subsubsub"> <li><a href="?page=gf_settings">Gravity Forms</a> |</li> <?php $count = sizeof(self::$addon_pages); for($i = 0; $i<$count; $i++){ $addon_keys = array_keys(self::$addon_pages); $addon = $addon_keys[$i]; ?> <li><a href="?page=gf_settings&addon=<?php echo urlencode($addon) ?>"><?php echo esc_html($addon) ?></a> <?php echo $i < $count-1 ? "|" : ""?></li> <?php } ?> </ul> <br style="clear:both;"/> <?php } if(empty($addon_name)){ self::gravityforms_settings_page(); } else{ do_action("gform_settings_" . str_replace(" ", "_", $addon_name)); } } public static function gravityforms_settings_page(){ global $wpdb; if(!GFCommon::ensure_wp_version()) return; if(isset($_POST["submit"])){ check_admin_referer('gforms_update_settings', 'gforms_update_settings'); if(!GFCommon::current_user_can_any("gravityforms_edit_settings")) die(__("You don't have adequate permission to edit settings.", "gravityforms")); RGFormsModel::save_key($_POST["gforms_key"]); update_option("rg_gforms_disable_css", $_POST["gforms_disable_css"]); update_option("rg_gforms_enable_html5", $_POST["gforms_enable_html5"]); update_option("rg_gforms_captcha_public_key", $_POST["gforms_captcha_public_key"]); update_option("rg_gforms_captcha_private_key", $_POST["gforms_captcha_private_key"]); update_option("rg_gforms_currency", $_POST["gforms_currency"]); //Updating message because key could have been changed GFCommon::cache_remote_message(); //Re-caching version info $version_info = GFCommon::get_version_info(false); ?> <div class="updated fade" style="padding:6px;"> <?php _e("Settings Updated", "gravityforms"); ?>. </div> <?php } else if(isset($_POST["uninstall"])){ if(!GFCommon::current_user_can_any("gravityforms_uninstall") || (function_exists("is_multisite") && is_multisite() && !is_super_admin())) die(__("You don't have adequate permission to uninstall Gravity Forms.", "gravityforms")); //droping all tables RGFormsModel::drop_tables(); //removing options delete_option("rg_form_version"); delete_option("rg_gforms_key"); delete_option("rg_gforms_disable_css"); delete_option("rg_gforms_enable_html5"); delete_option("rg_gforms_captcha_public_key"); delete_option("rg_gforms_captcha_private_key"); delete_option("rg_gforms_message"); delete_option("gf_dismissed_upgrades"); delete_option("rg_gforms_currency"); //removing gravity forms upload folder GFCommon::delete_directory(RGFormsModel::get_upload_root()); //Deactivating plugin $plugin = "gravityforms/gravityforms.php"; deactivate_plugins($plugin); update_option('recently_activated', array($plugin => time()) + (array)get_option('recently_activated')); ?> <div class="updated fade" style="padding:20px;"><?php echo sprintf(__("Gravity Forms have been successfully uninstalled. It can be re-activated from the %splugins page%s.", "gravityforms"), "<a href='plugins.php'>","</a>")?></div> <?php return; } if(!isset($version_info)) $version_info = GFCommon::get_version_info(); ?> <form method="post"> <?php wp_nonce_field('gforms_update_settings', 'gforms_update_settings') ?> <h3><?php _e("General Settings", "gravityforms"); ?></h3> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="gforms_key"><?php _e("Support License Key", "gravityforms"); ?></label> <?php gform_tooltip("settings_license_key") ?></th> <td> <?php $key = GFCommon::get_key(); $key_field = '<input type="password" name="gforms_key" id="gforms_key" style="width:350px;" value="' . $key . '" />'; if($version_info["is_valid_key"]) $key_field .= "&nbsp;<img src='" . GFCommon::get_base_url() ."/images/tick.png' class='gf_keystatus_valid' alt='valid key' title='valid key'/>"; else if (!empty($key)) $key_field .= "&nbsp;<img src='" . GFCommon::get_base_url() ."/images/cross.png' class='gf_keystatus_invalid' alt='invalid key' title='invalid key'/>"; echo apply_filters('gform_settings_key_field', $key_field); ?> <br /> <?php _e("The license key is used for access to automatic upgrades and support.", "gravityforms"); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_disable_css"><?php _e("Output CSS", "gravityforms"); ?></label> <?php gform_tooltip("settings_output_css") ?></th> <td> <input type="radio" name="gforms_disable_css" value="0" id="gforms_css_output_enabled" <?php echo get_option('rg_gforms_disable_css') == 1 ? "" : "checked='checked'" ?> /> <?php _e("Yes", "gravityforms"); ?>&nbsp;&nbsp; <input type="radio" name="gforms_disable_css" value="1" id="gforms_css_output_disabled" <?php echo get_option('rg_gforms_disable_css') == 1 ? "checked='checked'" : "" ?> /> <?php _e("No", "gravityforms"); ?><br /> <?php _e("Set this to No if you would like to disable the plugin from outputting the form CSS.", "gravityforms"); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_enable_html5"><?php _e("Output HTML5", "gravityforms"); ?></label> <?php gform_tooltip("settings_html5") ?></th> <td> <input type="radio" name="gforms_enable_html5" value="1" <?php echo get_option('rg_gforms_enable_html5') == 1 ? "checked='checked'" : "" ?> id="gforms_enable_html5"/> <?php _e("Yes", "gravityforms"); ?>&nbsp;&nbsp; <input type="radio" name="gforms_enable_html5" value="0" <?php echo get_option('rg_gforms_enable_html5') == 1 ? "" : "checked='checked'" ?> /><?php _e("No", "gravityforms"); ?><br /> <?php _e("Set this to No if you would like to disable the plugin from outputting HTML5 form fields.", "gravityforms"); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_currency"><?php _e("Currency", "gravityforms"); ?></label> <?php gform_tooltip("settings_currency") ?></th> <td> <select id="gforms_currency" name="gforms_currency"> <?php require_once("currency.php"); $current_currency = GFCommon::get_currency(); foreach(RGCurrency::get_currencies() as $code => $currency){ ?> <option value="<?php echo $code ?>" <?php echo $current_currency == $code ? "selected='selected'" : "" ?>><?php echo $currency["name"]?></option> <?php } ?> </select> </td> </tr> </table> <div class="hr-divider"></div> <h3><?php _e("reCAPTCHA Settings", "gravityforms"); ?></h3> <p style="text-align: left;"><?php _e("Gravity Forms integrates with reCAPTCHA, a free CAPTCHA service that helps to digitize books while protecting your forms from spam bots. ", "gravityforms"); ?><a href="http://www.google.com/recaptcha/" target="_blank"><?php _e("Read more about reCAPTCHA", "gravityforms"); ?></a>.</p> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="gforms_captcha_public_key"><?php _e("reCAPTCHA Public Key", "gravityforms"); ?></label> <?php gform_tooltip("settings_recaptcha_public") ?></th> <td> <input type="text" name="gforms_captcha_public_key" style="width:350px;" value="<?php echo get_option("rg_gforms_captcha_public_key") ?>" /><br /> <?php _e("Required only if you decide to use the reCAPTCHA field.", "gravityforms"); ?> <?php printf(__("%sSign up%s for a free account to get the key.", "gravityforms"), '<a target="_blank" href="http://www.google.com/recaptcha/whyrecaptcha">', '</a>'); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_captcha_private_key"><?php _e("reCAPTCHA Private Key", "gravityforms"); ?></label> <?php gform_tooltip("settings_recaptcha_private") ?></th> <td> <input type="text" name="gforms_captcha_private_key" style="width:350px;" value="<?php echo esc_attr(get_option("rg_gforms_captcha_private_key")) ?>" /><br /> <?php _e("Required only if you decide to use the reCAPTCHA field.", "gravityforms"); ?> <?php printf(__("%sSign up%s for a free account to get the key.", "gravityforms"), '<a target="_blank" href="http://www.google.com/recaptcha/whyrecaptcha">', '</a>'); ?> </td> </tr> </table> <?php if(GFCommon::current_user_can_any("gravityforms_edit_settings")){ ?> <br/><br/> <p class="submit" style="text-align: left;"> <?php $save_button = '<input type="submit" name="submit" value="' . __("Save Settings", "gravityforms"). '" class="button-primary gf_settings_savebutton"/>'; echo apply_filters("gform_settings_save_button", $save_button); ?> </p> <?php } ?> </form> <div id='gform_upgrade_license' style="display:none;"></div> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery.post(ajaxurl,{ action:"gf_upgrade_license", gf_upgrade_license: "<?php echo wp_create_nonce("gf_upgrade_license") ?>", cookie: encodeURIComponent(document.cookie)}, function(data){ if(data.trim().length > 0) jQuery("#gform_upgrade_license").replaceWith(data); } ); }); </script> <div class="hr-divider"></div> <h3><?php _e("Installation Status", "gravityforms"); ?></h3> <table class="form-table"> <tr valign="top"> <th scope="row"><label><?php _e("PHP Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo phpversion(); ?></strong> </td> <td> <?php if(version_compare(phpversion(), '5.0.0', '>')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/cross.png"/> <span class="installation_item_message"><?php _e("Gravity Forms requires PHP 5 or above.", "gravityforms"); ?></span> <?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><label><?php _e("MySQL Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo $wpdb->db_version();?></strong> </td> <td> <?php if(version_compare($wpdb->db_version(), '5.0.0', '>')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/cross.png"/> <span class="installation_item_message"><?php _e("Gravity Forms requires MySQL 5 or above.", "gravityforms"); ?></span> <?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><label><?php _e("WordPress Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo get_bloginfo("version"); ?></strong> </td> <td> <?php if(version_compare(get_bloginfo("version"), '2.8.0', '>')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/cross.png"/> <span class="installation_item_message"><?php _e("Gravity Forms requires WordPress 2.8 or above.", "gravityforms"); ?></span> <?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><label><?php _e("Gravity Forms Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo GFCommon::$version ?></strong> </td> <td> <?php if(version_compare(GFCommon::$version, $version_info["version"], '>=')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ echo sprintf(__("New version %s available. Automatic upgrade available on the %splugins page%s", "gravityforms"), $version_info["version"], '<a href="plugins.php">', '</a>'); } ?> </td> </tr> </table> <form action="" method="post"> <?php if(GFCommon::current_user_can_any("gravityforms_uninstall") && (!function_exists("is_multisite") || !is_multisite() || is_super_admin())){ ?> <div class="hr-divider"></div> <h3><?php _e("Uninstall Gravity Forms", "gravityforms") ?></h3> <div class="delete-alert alert_red"><h3><?php _e("Warning", "gravityforms") ?></h3><p><?php _e("This operation deletes ALL Gravity Forms data. If you continue, You will not be able to retrieve or restore your forms or entries.", "gravityforms") ?></p> <?php $uninstall_button = '<input type="submit" name="uninstall" value="' . __("Uninstall Gravity Forms", "gravityforms") . '" class="button" onclick="return confirm(\'' . __("Warning! ALL Gravity Forms data, including form entries will be deleted. This cannot be undone. \'OK\' to delete, \'Cancel\' to stop", "gravityforms") . '\');"/>'; echo apply_filters("gform_uninstall_button", $uninstall_button); ?> </div> <?php } ?> </form> <?php } public static function upgrade_license(){ check_ajax_referer('gf_upgrade_license','gf_upgrade_license'); $key = GFCommon::get_key(); $body = "key=$key"; $options = array('method' => 'POST', 'timeout' => 3, 'body' => $body); $options['headers'] = array( 'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset'), 'Content-Length' => strlen($body), 'User-Agent' => 'WordPress/' . get_bloginfo("version"), 'Referer' => get_bloginfo("url") ); $request_url = GRAVITY_MANAGER_URL . "/api.php?op=upgrade_message&key=" . GFCommon::get_key(); $raw_response = wp_remote_request($request_url, $options); if ( is_wp_error( $raw_response ) || 200 != $raw_response['response']['code'] ) $message = ""; else $message = $raw_response['body']; //validating that message is a valid Gravity Form message. If message is invalid, don't display anything if(substr($message, 0, 10) != "<!--GFM-->") $message = ""; echo $message; exit; } } ?>
noahjohn9259/emberrcom
wp-content/plugins/gravityforms_1.5.2.8/settings.php
PHP
gpl-2.0
19,359
<?php include_once('../../config/symbini.php'); include_once($SERVER_ROOT.'/content/lang/collections/list.'.$LANG_TAG.'.php'); include_once($SERVER_ROOT.'/classes/OccurrenceListManager.php'); include_once($SERVER_ROOT.'/classes/SOLRManager.php'); $stArrCollJson = $_REQUEST["jsoncollstarr"]; $stArrSearchJson = $_REQUEST["starr"]; $targetTid = $_REQUEST["targettid"]; $occIndex = $_REQUEST['occindex']; $sortField1 = $_REQUEST['sortfield1']; $sortField2 = $_REQUEST['sortfield2']; $sortOrder = $_REQUEST['sortorder']; $stArrSearchJson = str_replace("%apos;","'",$stArrSearchJson); $collStArr = json_decode($stArrCollJson, true); $searchStArr = json_decode($stArrSearchJson, true); if($collStArr && $searchStArr) $stArr = array_merge($searchStArr,$collStArr); if(!$collStArr && $searchStArr) $stArr = $searchStArr; if($collStArr && !$searchStArr) $stArr = $collStArr; if($SOLR_MODE){ $collManager = new SOLRManager(); $collManager->setSearchTermsArr($stArr); $collManager->setSorting($sortField1,$sortField2,$sortOrder); $solrArr = $collManager->getRecordArr($occIndex,1000); $recArr = $collManager->translateSOLRRecList($solrArr); } else{ $collManager = new OccurrenceListManager(false); $collManager->setSearchTermsArr($stArr); $collManager->setSorting($sortField1,$sortField2,$sortOrder); $recArr = $collManager->getRecordArr($occIndex,1000); } $targetClid = $collManager->getSearchTerm("targetclid"); $urlPrefix = (isset($_SERVER['HTTPS'])?'https://':'http://').$_SERVER['HTTP_HOST'].$CLIENT_ROOT.'/collections/listtabledisplay.php'; $recordListHtml = ''; $qryCnt = $collManager->getRecordCnt(); $navStr = '<div style="float:right;">'; if(($occIndex*1000) > 1000){ $navStr .= "<a href='' title='Previous 1000 records' onclick='changeTablePage(".($occIndex-1).");return false;'>&lt;&lt;</a>"; } $navStr .= ' | '; $navStr .= ($occIndex <= 1?1:(($occIndex-1)*1000)+1).'-'.($qryCnt<1000+$occIndex?$qryCnt:(($occIndex-1)*1000)+1000).' of '.$qryCnt.' records'; $navStr .= ' | '; if($qryCnt > (1000+$occIndex)){ $navStr .= "<a href='' title='Next 1000 records' onclick='changeTablePage(".($occIndex+1).");return false;'>&gt;&gt;</a>"; } $navStr .= '</div>'; if($recArr){ $recordListHtml .= '<div style="width:790px;clear:both;margin:5px;">'; $recordListHtml .= '<div style="float:left;"><button type="button" id="copyurl" onclick="copySearchUrl();">Copy URL to These Results</button></div>'; if($qryCnt > 1){ $recordListHtml .= $navStr; } $recordListHtml .= '</div>'; $recordListHtml .= '<div style="clear:both;height:5px;"></div>'; $recordListHtml .= '<table class="styledtable" style="font-family:Arial;font-size:12px;"><tr>'; $recordListHtml .= '<th>Symbiota ID</th>'; $recordListHtml .= '<th>Collection</th>'; $recordListHtml .= '<th>Catalog Number</th>'; $recordListHtml .= '<th>Family</th>'; $recordListHtml .= '<th>Scientific Name</th>'; $recordListHtml .= '<th>Country</th>'; $recordListHtml .= '<th>State/Province</th>'; $recordListHtml .= '<th>County</th>'; $recordListHtml .= '<th>Locality</th>'; $recordListHtml .= '<th>Habitat</th>'; if($QUICK_HOST_ENTRY_IS_ACTIVE) $recordListHtml .= '<th>Host</th>'; $recordListHtml .= '<th>Elevation</th>'; $recordListHtml .= '<th>Event Date</th>'; $recordListHtml .= '<th>Collector</th>'; $recordListHtml .= '<th>Number</th>'; $recordListHtml .= '<th>Individual Count</th>'; $recordListHtml .= '<th>Life Stage</th>'; $recordListHtml .= '<th>Sex</th>'; $recordListHtml .= '</tr>'; $recCnt = 0; foreach($recArr as $id => $occArr){ $isEditor = false; if($SYMB_UID && ($IS_ADMIN || (array_key_exists('CollAdmin',$USER_RIGHTS) && in_array($occArr['collid'],$USER_RIGHTS['CollAdmin'])) || (array_key_exists('CollEditor',$USER_RIGHTS) && in_array($occArr['collid'],$USER_RIGHTS['CollEditor'])))){ $isEditor = true; } $collection = $occArr['institutioncode']; if($occArr['collectioncode']) $collection .= ':'.$occArr['collectioncode']; if($occArr['sciname']) $occArr['sciname'] = '<i>'.$occArr['sciname'].'</i> '; $recordListHtml .= "<tr ".($recCnt%2?'class="alt"':'').">\n"; $recordListHtml .= '<td>'; $recordListHtml .= '<a href="#" onclick="return openIndPU('.$id.",".($targetClid?$targetClid:"0").');">'.$id.'</a> '; if($isEditor || ($SYMB_UID && $SYMB_UID == $fieldArr['observeruid'])){ $recordListHtml .= '<a href="editor/occurrenceeditor.php?occid='.$id.'" target="_blank">'; $recordListHtml .= '<img src="../images/edit.png" style="height:13px;" title="Edit Record" />'; $recordListHtml .= '</a>'; } if(isset($occArr['img'])){ $recordListHtml .= '<img src="../images/image.png" style="height:13px;margin-left:5px;" title="Has Image" />'; } $recordListHtml .= '</td>'."\n"; $recordListHtml .= '<td>'.$collection.'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['accession'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['family'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['sciname'].($occArr['author']?" ".$occArr['author']:"").'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['country'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['state'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['county'].'</td>'."\n"; $recordListHtml .= '<td>'.((strlen($occArr['locality'])>80)?substr($occArr['locality'],0,80).'...':$occArr['locality']).'</td>'."\n"; $recordListHtml .= '<td>'.((strlen($occArr['habitat'])>80)?substr($occArr['habitat'],0,80).'...':$occArr['habitat']).'</td>'."\n"; if($QUICK_HOST_ENTRY_IS_ACTIVE){ if(array_key_exists('assochost',$occArr)){ $recordListHtml .= '<td>'.((strlen($occArr['assochost'])>80)?substr($occArr['assochost'],0,80).'...':$occArr['assochost']).'</td>'."\n"; } else{ $recordListHtml .= '<td></td>'."\n"; } } $recordListHtml .= '<td>'.(array_key_exists("elev",$occArr)?$occArr['elev']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("date",$occArr)?$occArr['date']:"").'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['collector'].'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("collnumber",$occArr)?$occArr['collnumber']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("individualCount",$occArr)?$occArr['individualCount']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("lifeStage",$occArr)?$occArr['lifeStage']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("sex",$occArr)?$occArr['sex']:"").'</td>'."\n"; $recordListHtml .= "</tr>\n"; $recCnt++; } $recordListHtml .= '</table>'; $recordListHtml .= '<div style="clear:both;height:5px;"></div>'; $recordListHtml .= '<textarea id="urlPrefixBox" style="position:absolute;left:-9999px;top:-9999px">'.$urlPrefix.$collManager->getSearchResultUrl().'</textarea>'; $recordListHtml .= '<textarea id="urlFullBox" style="position:absolute;left:-9999px;top:-9999px"></textarea>'; if($qryCnt > 1){ $recordListHtml .= '<div style="width:790px;">'.$navStr.'</div>'; } $recordListHtml .= '*Click on the Symbiota identifier in the first column to see Full Record Details.'; } else{ $recordListHtml .= '<div style="font-weight:bold;font-size:120%;">No records found matching the query</div>'; } //output the response echo $recordListHtml; //echo json_encode($recordListHtml); ?>
seltmann/Symbiota
collections/rpc/changetablepage.php
PHP
gpl-2.0
7,873
<?php /** * PEAR_Common, the base class for the PEAR Installer * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Tomas V. V. Cox <cox@idecnet.com> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2008 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Common.php,v 1.1 2010/06/17 11:19:23 soonchoy Exp $ * @link http://pear.php.net/package/PEAR * @since File available since Release 0.1.0 * @deprecated File deprecated since Release 1.4.0a1 */ /** * Include error handling */ require_once 'PEAR.php'; // {{{ constants and globals /** * PEAR_Common error when an invalid PHP file is passed to PEAR_Common::analyzeSourceCode() */ define('PEAR_COMMON_ERROR_INVALIDPHP', 1); define('_PEAR_COMMON_PACKAGE_NAME_PREG', '[A-Za-z][a-zA-Z0-9_]+'); define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^' . _PEAR_COMMON_PACKAGE_NAME_PREG . '\\z/'); // this should allow: 1, 1.0, 1.0RC1, 1.0dev, 1.0dev123234234234, 1.0a1, 1.0b1, 1.0pl1 define('_PEAR_COMMON_PACKAGE_VERSION_PREG', '\d+(?:\.\d+)*(?:[a-zA-Z]+\d*)?'); define('PEAR_COMMON_PACKAGE_VERSION_PREG', '/^' . _PEAR_COMMON_PACKAGE_VERSION_PREG . '\\z/i'); // XXX far from perfect :-) define('_PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?'); define('PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '/^' . _PEAR_COMMON_PACKAGE_DOWNLOAD_PREG . '\\z/'); define('_PEAR_CHANNELS_NAME_PREG', '[A-Za-z][a-zA-Z0-9\.]+'); define('PEAR_CHANNELS_NAME_PREG', '/^' . _PEAR_CHANNELS_NAME_PREG . '\\z/'); // this should allow any dns or IP address, plus a path - NO UNDERSCORES ALLOWED define('_PEAR_CHANNELS_SERVER_PREG', '[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*(\/[a-zA-Z0-9\-]+)*'); define('PEAR_CHANNELS_SERVER_PREG', '/^' . _PEAR_CHANNELS_SERVER_PREG . '\\z/i'); define('_PEAR_CHANNELS_PACKAGE_PREG', '(' ._PEAR_CHANNELS_SERVER_PREG . ')\/(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')'); define('PEAR_CHANNELS_PACKAGE_PREG', '/^' . _PEAR_CHANNELS_PACKAGE_PREG . '\\z/i'); define('_PEAR_COMMON_CHANNEL_DOWNLOAD_PREG', '(' . _PEAR_CHANNELS_NAME_PREG . ')::(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?'); define('PEAR_COMMON_CHANNEL_DOWNLOAD_PREG', '/^' . _PEAR_COMMON_CHANNEL_DOWNLOAD_PREG . '\\z/'); /** * List of temporary files and directories registered by * PEAR_Common::addTempFile(). * @var array */ $GLOBALS['_PEAR_Common_tempfiles'] = array(); /** * Valid maintainer roles * @var array */ $GLOBALS['_PEAR_Common_maintainer_roles'] = array('lead','developer','contributor','helper'); /** * Valid release states * @var array */ $GLOBALS['_PEAR_Common_release_states'] = array('alpha','beta','stable','snapshot','devel'); /** * Valid dependency types * @var array */ $GLOBALS['_PEAR_Common_dependency_types'] = array('pkg','ext','php','prog','ldlib','rtlib','os','websrv','sapi'); /** * Valid dependency relations * @var array */ $GLOBALS['_PEAR_Common_dependency_relations'] = array('has','eq','lt','le','gt','ge','not', 'ne'); /** * Valid file roles * @var array */ $GLOBALS['_PEAR_Common_file_roles'] = array('php','ext','test','doc','data','src','script'); /** * Valid replacement types * @var array */ $GLOBALS['_PEAR_Common_replacement_types'] = array('php-const', 'pear-config', 'package-info'); /** * Valid "provide" types * @var array */ $GLOBALS['_PEAR_Common_provide_types'] = array('ext', 'prog', 'class', 'function', 'feature', 'api'); /** * Valid "provide" types * @var array */ $GLOBALS['_PEAR_Common_script_phases'] = array('pre-install', 'post-install', 'pre-uninstall', 'post-uninstall', 'pre-build', 'post-build', 'pre-configure', 'post-configure', 'pre-setup', 'post-setup'); // }}} /** * Class providing common functionality for PEAR administration classes. * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Tomas V. V. Cox <cox@idecnet.com> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2008 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: 1.7.2 * @link http://pear.php.net/package/PEAR * @since Class available since Release 1.4.0a1 * @deprecated This class will disappear, and its components will be spread * into smaller classes, like the AT&T breakup, as of Release 1.4.0a1 */ class PEAR_Common extends PEAR { // {{{ properties /** stack of elements, gives some sort of XML context */ var $element_stack = array(); /** name of currently parsed XML element */ var $current_element; /** array of attributes of the currently parsed XML element */ var $current_attributes = array(); /** assoc with information about a package */ var $pkginfo = array(); /** * User Interface object (PEAR_Frontend_* class). If null, * the log() method uses print. * @var object */ var $ui = null; /** * Configuration object (PEAR_Config). * @var PEAR_Config */ var $config = null; var $current_path = null; /** * PEAR_SourceAnalyzer instance * @var object */ var $source_analyzer = null; /** * Flag variable used to mark a valid package file * @var boolean * @access private */ var $_validPackageFile; // }}} // {{{ constructor /** * PEAR_Common constructor * * @access public */ function PEAR_Common() { parent::PEAR(); $this->config = &PEAR_Config::singleton(); $this->debug = $this->config->get('verbose'); } // }}} // {{{ destructor /** * PEAR_Common destructor * * @access private */ function _PEAR_Common() { // doesn't work due to bug #14744 //$tempfiles = $this->_tempfiles; $tempfiles =& $GLOBALS['_PEAR_Common_tempfiles']; while ($file = array_shift($tempfiles)) { if (@is_dir($file)) { if (!class_exists('System')) { require_once 'System.php'; } System::rm(array('-rf', $file)); } elseif (file_exists($file)) { unlink($file); } } } // }}} // {{{ addTempFile() /** * Register a temporary file or directory. When the destructor is * executed, all registered temporary files and directories are * removed. * * @param string $file name of file or directory * * @return void * * @access public */ function addTempFile($file) { if (!class_exists('PEAR_Frontend')) { require_once 'PEAR/Frontend.php'; } PEAR_Frontend::addTempFile($file); } // }}} // {{{ mkDirHier() /** * Wrapper to System::mkDir(), creates a directory as well as * any necessary parent directories. * * @param string $dir directory name * * @return bool TRUE on success, or a PEAR error * * @access public */ function mkDirHier($dir) { $this->log(2, "+ create dir $dir"); if (!class_exists('System')) { require_once 'System.php'; } return System::mkDir(array('-p', $dir)); } // }}} // {{{ log() /** * Logging method. * * @param int $level log level (0 is quiet, higher is noisier) * @param string $msg message to write to the log * * @return void * * @access public * @static */ function log($level, $msg, $append_crlf = true) { if ($this->debug >= $level) { if (!class_exists('PEAR_Frontend')) { require_once 'PEAR/Frontend.php'; } $ui = &PEAR_Frontend::singleton(); if (is_a($ui, 'PEAR_Frontend')) { $ui->log($msg, $append_crlf); } else { print "$msg\n"; } } } // }}} // {{{ mkTempDir() /** * Create and register a temporary directory. * * @param string $tmpdir (optional) Directory to use as tmpdir. * Will use system defaults (for example * /tmp or c:\windows\temp) if not specified * * @return string name of created directory * * @access public */ function mkTempDir($tmpdir = '') { if ($tmpdir) { $topt = array('-t', $tmpdir); } else { $topt = array(); } $topt = array_merge($topt, array('-d', 'pear')); if (!class_exists('System')) { require_once 'System.php'; } if (!$tmpdir = System::mktemp($topt)) { return false; } $this->addTempFile($tmpdir); return $tmpdir; } // }}} // {{{ setFrontendObject() /** * Set object that represents the frontend to be used. * * @param object Reference of the frontend object * @return void * @access public */ function setFrontendObject(&$ui) { $this->ui = &$ui; } // }}} // {{{ infoFromTgzFile() /** * Returns information about a package file. Expects the name of * a gzipped tar file as input. * * @param string $file name of .tgz file * * @return array array with package information * * @access public * @deprecated use PEAR_PackageFile->fromTgzFile() instead * */ function infoFromTgzFile($file) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromTgzFile($file, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } // }}} // {{{ infoFromDescriptionFile() /** * Returns information about a package file. Expects the name of * a package xml file as input. * * @param string $descfile name of package xml file * * @return array array with package information * * @access public * @deprecated use PEAR_PackageFile->fromPackageFile() instead * */ function infoFromDescriptionFile($descfile) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } // }}} // {{{ infoFromString() /** * Returns information about a package file. Expects the contents * of a package xml file as input. * * @param string $data contents of package.xml file * * @return array array with package information * * @access public * @deprecated use PEAR_PackageFile->fromXmlstring() instead * */ function infoFromString($data) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromXmlString($data, PEAR_VALIDATE_NORMAL, false); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } // }}} /** * @param PEAR_PackageFile_v1|PEAR_PackageFile_v2 * @return array */ function _postProcessValidPackagexml(&$pf) { if (is_a($pf, 'PEAR_PackageFile_v2')) { // sort of make this into a package.xml 1.0-style array // changelog is not converted to old format. $arr = $pf->toArray(true); $arr = array_merge($arr, $arr['old']); unset($arr['old']); unset($arr['xsdversion']); unset($arr['contents']); unset($arr['compatible']); unset($arr['channel']); unset($arr['uri']); unset($arr['dependencies']); unset($arr['phprelease']); unset($arr['extsrcrelease']); unset($arr['zendextsrcrelease']); unset($arr['extbinrelease']); unset($arr['zendextbinrelease']); unset($arr['bundle']); unset($arr['lead']); unset($arr['developer']); unset($arr['helper']); unset($arr['contributor']); $arr['filelist'] = $pf->getFilelist(); $this->pkginfo = $arr; return $arr; } else { $this->pkginfo = $pf->toArray(); return $this->pkginfo; } } // {{{ infoFromAny() /** * Returns package information from different sources * * This method is able to extract information about a package * from a .tgz archive or from a XML package definition file. * * @access public * @param string Filename of the source ('package.xml', '<package>.tgz') * @return string * @deprecated use PEAR_PackageFile->fromAnyFile() instead */ function infoFromAny($info) { if (is_string($info) && file_exists($info)) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } return $info; } // }}} // {{{ xmlFromInfo() /** * Return an XML document based on the package info (as returned * by the PEAR_Common::infoFrom* methods). * * @param array $pkginfo package info * * @return string XML data * * @access public * @deprecated use a PEAR_PackageFile_v* object's generator instead */ function xmlFromInfo($pkginfo) { $config = &PEAR_Config::singleton(); $packagefile = &new PEAR_PackageFile($config); $pf = &$packagefile->fromArray($pkginfo); $gen = &$pf->getDefaultGenerator(); return $gen->toXml(PEAR_VALIDATE_PACKAGING); } // }}} // {{{ validatePackageInfo() /** * Validate XML package definition file. * * @param string $info Filename of the package archive or of the * package definition file * @param array $errors Array that will contain the errors * @param array $warnings Array that will contain the warnings * @param string $dir_prefix (optional) directory where source files * may be found, or empty if they are not available * @access public * @return boolean * @deprecated use the validation of PEAR_PackageFile objects */ function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '') { $config = &PEAR_Config::singleton(); $packagefile = &new PEAR_PackageFile($config); PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); if (strpos($info, '<?xml') !== false) { $pf = &$packagefile->fromXmlString($info, PEAR_VALIDATE_NORMAL, ''); } else { $pf = &$packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL); } PEAR::staticPopErrorHandling(); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { if ($error['level'] == 'error') { $errors[] = $error['message']; } else { $warnings[] = $error['message']; } } } return false; } return true; } // }}} // {{{ buildProvidesArray() /** * Build a "provides" array from data returned by * analyzeSourceCode(). The format of the built array is like * this: * * array( * 'class;MyClass' => 'array('type' => 'class', 'name' => 'MyClass'), * ... * ) * * * @param array $srcinfo array with information about a source file * as returned by the analyzeSourceCode() method. * * @return void * * @access public * */ function buildProvidesArray($srcinfo) { $file = basename($srcinfo['source_file']); $pn = ''; if (isset($this->_packageName)) { $pn = $this->_packageName; } $pnl = strlen($pn); foreach ($srcinfo['declared_classes'] as $class) { $key = "class;$class"; if (isset($this->pkginfo['provides'][$key])) { continue; } $this->pkginfo['provides'][$key] = array('file'=> $file, 'type' => 'class', 'name' => $class); if (isset($srcinfo['inheritance'][$class])) { $this->pkginfo['provides'][$key]['extends'] = $srcinfo['inheritance'][$class]; } } foreach ($srcinfo['declared_methods'] as $class => $methods) { foreach ($methods as $method) { $function = "$class::$method"; $key = "function;$function"; if ($method{0} == '_' || !strcasecmp($method, $class) || isset($this->pkginfo['provides'][$key])) { continue; } $this->pkginfo['provides'][$key] = array('file'=> $file, 'type' => 'function', 'name' => $function); } } foreach ($srcinfo['declared_functions'] as $function) { $key = "function;$function"; if ($function{0} == '_' || isset($this->pkginfo['provides'][$key])) { continue; } if (!strstr($function, '::') && strncasecmp($function, $pn, $pnl)) { $warnings[] = "in1 " . $file . ": function \"$function\" not prefixed with package name \"$pn\""; } $this->pkginfo['provides'][$key] = array('file'=> $file, 'type' => 'function', 'name' => $function); } } // }}} // {{{ analyzeSourceCode() /** * Analyze the source code of the given PHP file * * @param string Filename of the PHP file * @return mixed * @access public */ function analyzeSourceCode($file) { if (!function_exists("token_get_all")) { return false; } if (!defined('T_DOC_COMMENT')) { define('T_DOC_COMMENT', T_COMMENT); } if (!defined('T_INTERFACE')) { define('T_INTERFACE', -1); } if (!defined('T_IMPLEMENTS')) { define('T_IMPLEMENTS', -1); } if (!$fp = @fopen($file, "r")) { return false; } fclose($fp); $contents = file_get_contents($file); $tokens = token_get_all($contents); /* for ($i = 0; $i < sizeof($tokens); $i++) { @list($token, $data) = $tokens[$i]; if (is_string($token)) { var_dump($token); } else { print token_name($token) . ' '; var_dump(rtrim($data)); } } */ $look_for = 0; $paren_level = 0; $bracket_level = 0; $brace_level = 0; $lastphpdoc = ''; $current_class = ''; $current_interface = ''; $current_class_level = -1; $current_function = ''; $current_function_level = -1; $declared_classes = array(); $declared_interfaces = array(); $declared_functions = array(); $declared_methods = array(); $used_classes = array(); $used_functions = array(); $extends = array(); $implements = array(); $nodeps = array(); $inquote = false; $interface = false; for ($i = 0; $i < sizeof($tokens); $i++) { if (is_array($tokens[$i])) { list($token, $data) = $tokens[$i]; } else { $token = $tokens[$i]; $data = ''; } if ($inquote) { if ($token != '"') { continue; } else { $inquote = false; continue; } } switch ($token) { case T_WHITESPACE: continue; case ';': if ($interface) { $current_function = ''; $current_function_level = -1; } break; case '"': $inquote = true; break; case T_CURLY_OPEN: case T_DOLLAR_OPEN_CURLY_BRACES: case '{': $brace_level++; continue 2; case '}': $brace_level--; if ($current_class_level == $brace_level) { $current_class = ''; $current_class_level = -1; } if ($current_function_level == $brace_level) { $current_function = ''; $current_function_level = -1; } continue 2; case '[': $bracket_level++; continue 2; case ']': $bracket_level--; continue 2; case '(': $paren_level++; continue 2; case ')': $paren_level--; continue 2; case T_INTERFACE: $interface = true; case T_CLASS: if (($current_class_level != -1) || ($current_function_level != -1)) { PEAR::raiseError("Parser error: invalid PHP found in file \"$file\"", PEAR_COMMON_ERROR_INVALIDPHP); return false; } case T_FUNCTION: case T_NEW: case T_EXTENDS: case T_IMPLEMENTS: $look_for = $token; continue 2; case T_STRING: if (version_compare(zend_version(), '2.0', '<')) { if (in_array(strtolower($data), array('public', 'private', 'protected', 'abstract', 'interface', 'implements', 'throw') )) { PEAR::raiseError('Error: PHP5 token encountered in ' . $file . 'packaging should be done in PHP 5'); return false; } } if ($look_for == T_CLASS) { $current_class = $data; $current_class_level = $brace_level; $declared_classes[] = $current_class; } elseif ($look_for == T_INTERFACE) { $current_interface = $data; $current_class_level = $brace_level; $declared_interfaces[] = $current_interface; } elseif ($look_for == T_IMPLEMENTS) { $implements[$current_class] = $data; } elseif ($look_for == T_EXTENDS) { $extends[$current_class] = $data; } elseif ($look_for == T_FUNCTION) { if ($current_class) { $current_function = "$current_class::$data"; $declared_methods[$current_class][] = $data; } elseif ($current_interface) { $current_function = "$current_interface::$data"; $declared_methods[$current_interface][] = $data; } else { $current_function = $data; $declared_functions[] = $current_function; } $current_function_level = $brace_level; $m = array(); } elseif ($look_for == T_NEW) { $used_classes[$data] = true; } $look_for = 0; continue 2; case T_VARIABLE: $look_for = 0; continue 2; case T_DOC_COMMENT: case T_COMMENT: if (preg_match('!^/\*\*\s!', $data)) { $lastphpdoc = $data; if (preg_match_all('/@nodep\s+(\S+)/', $lastphpdoc, $m)) { $nodeps = array_merge($nodeps, $m[1]); } } continue 2; case T_DOUBLE_COLON: if (!($tokens[$i - 1][0] == T_WHITESPACE || $tokens[$i - 1][0] == T_STRING)) { PEAR::raiseError("Parser error: invalid PHP found in file \"$file\"", PEAR_COMMON_ERROR_INVALIDPHP); return false; } $class = $tokens[$i - 1][1]; if (strtolower($class) != 'parent') { $used_classes[$class] = true; } continue 2; } } return array( "source_file" => $file, "declared_classes" => $declared_classes, "declared_interfaces" => $declared_interfaces, "declared_methods" => $declared_methods, "declared_functions" => $declared_functions, "used_classes" => array_diff(array_keys($used_classes), $nodeps), "inheritance" => $extends, "implements" => $implements, ); } // }}} // {{{ betterStates() /** * Return an array containing all of the states that are more stable than * or equal to the passed in state * * @param string Release state * @param boolean Determines whether to include $state in the list * @return false|array False if $state is not a valid release state */ function betterStates($state, $include = false) { static $states = array('snapshot', 'devel', 'alpha', 'beta', 'stable'); $i = array_search($state, $states); if ($i === false) { return false; } if ($include) { $i--; } return array_slice($states, $i + 1); } // }}} // {{{ detectDependencies() function detectDependencies($any, $status_callback = null) { if (!function_exists("token_get_all")) { return false; } if (PEAR::isError($info = $this->infoFromAny($any))) { return $this->raiseError($info); } if (!is_array($info)) { return false; } $deps = array(); $used_c = $decl_c = $decl_f = $decl_m = array(); foreach ($info['filelist'] as $file => $fa) { $tmp = $this->analyzeSourceCode($file); $used_c = @array_merge($used_c, $tmp['used_classes']); $decl_c = @array_merge($decl_c, $tmp['declared_classes']); $decl_f = @array_merge($decl_f, $tmp['declared_functions']); $decl_m = @array_merge($decl_m, $tmp['declared_methods']); $inheri = @array_merge($inheri, $tmp['inheritance']); } $used_c = array_unique($used_c); $decl_c = array_unique($decl_c); $undecl_c = array_diff($used_c, $decl_c); return array('used_classes' => $used_c, 'declared_classes' => $decl_c, 'declared_methods' => $decl_m, 'declared_functions' => $decl_f, 'undeclared_classes' => $undecl_c, 'inheritance' => $inheri, ); } // }}} // {{{ getUserRoles() /** * Get the valid roles for a PEAR package maintainer * * @return array * @static */ function getUserRoles() { return $GLOBALS['_PEAR_Common_maintainer_roles']; } // }}} // {{{ getReleaseStates() /** * Get the valid package release states of packages * * @return array * @static */ function getReleaseStates() { return $GLOBALS['_PEAR_Common_release_states']; } // }}} // {{{ getDependencyTypes() /** * Get the implemented dependency types (php, ext, pkg etc.) * * @return array * @static */ function getDependencyTypes() { return $GLOBALS['_PEAR_Common_dependency_types']; } // }}} // {{{ getDependencyRelations() /** * Get the implemented dependency relations (has, lt, ge etc.) * * @return array * @static */ function getDependencyRelations() { return $GLOBALS['_PEAR_Common_dependency_relations']; } // }}} // {{{ getFileRoles() /** * Get the implemented file roles * * @return array * @static */ function getFileRoles() { return $GLOBALS['_PEAR_Common_file_roles']; } // }}} // {{{ getReplacementTypes() /** * Get the implemented file replacement types in * * @return array * @static */ function getReplacementTypes() { return $GLOBALS['_PEAR_Common_replacement_types']; } // }}} // {{{ getProvideTypes() /** * Get the implemented file replacement types in * * @return array * @static */ function getProvideTypes() { return $GLOBALS['_PEAR_Common_provide_types']; } // }}} // {{{ getScriptPhases() /** * Get the implemented file replacement types in * * @return array * @static */ function getScriptPhases() { return $GLOBALS['_PEAR_Common_script_phases']; } // }}} // {{{ validPackageName() /** * Test whether a string contains a valid package name. * * @param string $name the package name to test * * @return bool * * @access public */ function validPackageName($name) { return (bool)preg_match(PEAR_COMMON_PACKAGE_NAME_PREG, $name); } // }}} // {{{ validPackageVersion() /** * Test whether a string contains a valid package version. * * @param string $ver the package version to test * * @return bool * * @access public */ function validPackageVersion($ver) { return (bool)preg_match(PEAR_COMMON_PACKAGE_VERSION_PREG, $ver); } // }}} // {{{ downloadHttp() /** * Download a file through HTTP. Considers suggested file name in * Content-disposition: header and can run a callback function for * different events. The callback will be called with two * parameters: the callback type, and parameters. The implemented * callback types are: * * 'setup' called at the very beginning, parameter is a UI object * that should be used for all output * 'message' the parameter is a string with an informational message * 'saveas' may be used to save with a different file name, the * parameter is the filename that is about to be used. * If a 'saveas' callback returns a non-empty string, * that file name will be used as the filename instead. * Note that $save_dir will not be affected by this, only * the basename of the file. * 'start' download is starting, parameter is number of bytes * that are expected, or -1 if unknown * 'bytesread' parameter is the number of bytes read so far * 'done' download is complete, parameter is the total number * of bytes read * 'connfailed' if the TCP connection fails, this callback is called * with array(host,port,errno,errmsg) * 'writefailed' if writing to disk fails, this callback is called * with array(destfile,errmsg) * * If an HTTP proxy has been configured (http_proxy PEAR_Config * setting), the proxy will be used. * * @param string $url the URL to download * @param object $ui PEAR_Frontend_* instance * @param object $config PEAR_Config instance * @param string $save_dir (optional) directory to save file in * @param mixed $callback (optional) function/method to call for status * updates * * @return string Returns the full path of the downloaded file or a PEAR * error on failure. If the error is caused by * socket-related errors, the error object will * have the fsockopen error code available through * getCode(). * * @access public * @deprecated in favor of PEAR_Downloader::downloadHttp() */ function downloadHttp($url, &$ui, $save_dir = '.', $callback = null) { if (!class_exists('PEAR_Downloader')) { require_once 'PEAR/Downloader.php'; } return PEAR_Downloader::downloadHttp($url, $ui, $save_dir, $callback); } // }}} /** * @param string $path relative or absolute include path * @return boolean * @static */ function isIncludeable($path) { if (file_exists($path) && is_readable($path)) { return true; } $ipath = explode(PATH_SEPARATOR, ini_get('include_path')); foreach ($ipath as $include) { $test = realpath($include . DIRECTORY_SEPARATOR . $path); if (file_exists($test) && is_readable($test)) { return true; } } return false; } } require_once 'PEAR/Config.php'; require_once 'PEAR/PackageFile.php'; ?>
alucard263096/XMLRPC
DEMO/ta_portal_dev/libs/PEAR/PEAR/Common.php
PHP
gpl-2.0
36,771
/* * Copyright (C) 2011 Google, Inc. All rights reserved. * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ContentSecurityPolicySource.h" #include "ContentSecurityPolicy.h" #include "URL.h" namespace WebCore { ContentSecurityPolicySource::ContentSecurityPolicySource(const ContentSecurityPolicy& policy, const String& scheme, const String& host, int port, const String& path, bool hostHasWildcard, bool portHasWildcard) : m_policy(policy) , m_scheme(scheme) , m_host(host) , m_port(port) , m_path(path) , m_hostHasWildcard(hostHasWildcard) , m_portHasWildcard(portHasWildcard) { } bool ContentSecurityPolicySource::matches(const URL& url) const { if (!schemeMatches(url)) return false; if (isSchemeOnly()) return true; return hostMatches(url) && portMatches(url) && pathMatches(url); } bool ContentSecurityPolicySource::schemeMatches(const URL& url) const { if (m_scheme.isEmpty()) return m_policy.protocolMatchesSelf(url); return equalIgnoringASCIICase(url.protocol(), m_scheme); } bool ContentSecurityPolicySource::hostMatches(const URL& url) const { const String& host = url.host(); if (equalIgnoringASCIICase(host, m_host)) return true; return m_hostHasWildcard && host.endsWith("." + m_host, false); } bool ContentSecurityPolicySource::pathMatches(const URL& url) const { if (m_path.isEmpty()) return true; String path = decodeURLEscapeSequences(url.path()); if (m_path.endsWith("/")) return path.startsWith(m_path); return path == m_path; } bool ContentSecurityPolicySource::portMatches(const URL& url) const { if (m_portHasWildcard) return true; int port = url.port(); if (port == m_port) return true; if (!port) return isDefaultPortForProtocol(m_port, url.protocol()); if (!m_port) return isDefaultPortForProtocol(port, url.protocol()); return false; } bool ContentSecurityPolicySource::isSchemeOnly() const { return m_host.isEmpty(); } } // namespace WebCore
qtproject/qtwebkit
Source/WebCore/page/csp/ContentSecurityPolicySource.cpp
C++
gpl-2.0
3,383
<?php $profile_page = get_option('booked_profile_page'); if ($profile_page): if(!class_exists('booked_profiles')) { class booked_profiles { public function __construct() { add_action('init', array(&$this,'rewrite_add_rewrites')); add_action('the_content', array(&$this,'display_profile_markup')); add_filter('wp_title', array(&$this,'wp_profile_title'),10,2); register_activation_hook( __FILE__, array(&$this, 'rewrite_activation') ); } public function rewrite_add_rewrites(){ $profile_page = get_option('booked_profile_page'); if ($profile_page): $profile_page_data = get_post($profile_page, ARRAY_A); $profile_slug = $profile_page_data['post_name']; else : $profile_slug = 'profile'; endif; add_rewrite_tag( '%profile%', '([^&]+)' ); add_rewrite_rule( '^'.$profile_slug.'/([^/]*)/?', 'index.php?profile=$matches[1]', 'top' ); } public function rewrite_activation(){ $this->rewrite_add_rewrites(); flush_rewrite_rules(); } public function display_profile_markup($content){ $profile_page = get_option('booked_profile_page'); if(is_page($profile_page) || get_query_var('profile')): if (is_user_logged_in() || get_query_var('profile')): ob_start(); $this->display_profile_page_content(); $content = ob_get_clean(); return $content; else : return $content; endif; endif; return $content; } public function display_profile_page_content() { require(BOOKED_PLUGIN_TEMPLATES_DIR . 'profile.php'); } public function wp_profile_title( $title, $sep = false ) { if (get_query_var('profile')): echo get_query_var('profile'); $user_data = get_user_by( 'id', get_query_var('profile') ); $title = sprintf(__("%s's Profile","booked"), $user_data->data->display_name) . ' - '; return $title; endif; return $title; } } new booked_profiles(); } endif;
annegrundhoefer/mark
wp-content/plugins/booked/includes/profiles.php
PHP
gpl-2.0
2,040
/*************************************************************************** kbordercoltextexport.cpp - description ------------------- begin : Sam Aug 30 2003 copyright : (C) 2003 by Friedrich W. H. Kossebau email : Friedrich.W.H@Kossebau.de ***************************************************************************/ /*************************************************************************** * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License version 2 as published by the Free Software Foundation. * * * ***************************************************************************/ // qt specific #include <qstring.h> // lib specific #include "kbordercoltextexport.h" using namespace KHE; static const uint BorderColumnTEWidth = 3; int KBorderColTextExport::charsPerLine() const { return BorderColumnTEWidth; } void KBorderColTextExport::printFirstLine( QString &T, int /*Line*/ ) const { print( T ); } void KBorderColTextExport::printNextLine( QString &T ) const { print( T ); } void KBorderColTextExport::print( QString &T ) const { T.append( " | " ); }
serghei/kde3-kdeutils
khexedit/lib/kbordercoltextexport.cpp
C++
gpl-2.0
1,464
/* Copyright (C) 2012 Samsung Electronics Copyright (C) 2012 Intel Corporation. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "GraphicsContext3DPrivate.h" #include "HostWindow.h" #include "NotImplemented.h" namespace WebCore { PassOwnPtr<GraphicsContext3DPrivate> GraphicsContext3DPrivate::create(GraphicsContext3D* context, HostWindow* hostWindow) { OwnPtr<GraphicsContext3DPrivate> platformLayer = adoptPtr(new GraphicsContext3DPrivate(context, hostWindow)); if (platformLayer && platformLayer->initialize()) return platformLayer.release(); return nullptr; } GraphicsContext3DPrivate::GraphicsContext3DPrivate(GraphicsContext3D* context, HostWindow* hostWindow) : m_context(context) , m_hostWindow(hostWindow) { } bool GraphicsContext3DPrivate::initialize() { if (m_context->m_renderStyle == GraphicsContext3D::RenderDirectlyToHostWindow) return false; if (m_hostWindow && m_hostWindow->platformPageClient()) { // FIXME: Implement this code path for WebKit1. // Get Evas object from platformPageClient and set EvasGL related members. return false; } m_offScreenContext = GLPlatformContext::createContext(m_context->m_renderStyle); if (!m_offScreenContext) return false; if (m_context->m_renderStyle == GraphicsContext3D::RenderOffscreen) { m_offScreenSurface = GLPlatformSurface::createOffScreenSurface(); if (!m_offScreenSurface) return false; if (!m_offScreenContext->initialize(m_offScreenSurface.get())) return false; if (!makeContextCurrent()) return false; #if USE(GRAPHICS_SURFACE) m_surfaceOperation = CreateSurface; #endif } return true; } GraphicsContext3DPrivate::~GraphicsContext3DPrivate() { releaseResources(); } void GraphicsContext3DPrivate::releaseResources() { if (m_context->m_renderStyle == GraphicsContext3D::RenderToCurrentGLContext) return; // Release the current context and drawable only after destroying any associated gl resources. #if USE(GRAPHICS_SURFACE) if (m_previousGraphicsSurface) m_previousGraphicsSurface = nullptr; if (m_graphicsSurface) m_graphicsSurface = nullptr; m_surfaceHandle = GraphicsSurfaceToken(); #endif if (m_offScreenSurface) m_offScreenSurface->destroy(); if (m_offScreenContext) { m_offScreenContext->destroy(); m_offScreenContext->releaseCurrent(); } } void GraphicsContext3DPrivate::setContextLostCallback(PassOwnPtr<GraphicsContext3D::ContextLostCallback> callBack) { m_contextLostCallback = callBack; } PlatformGraphicsContext3D GraphicsContext3DPrivate::platformGraphicsContext3D() const { return m_offScreenContext->handle(); } bool GraphicsContext3DPrivate::makeContextCurrent() const { bool success = m_offScreenContext->makeCurrent(m_offScreenSurface.get()); if (!m_offScreenContext->isValid()) { // FIXME: Restore context if (m_contextLostCallback) m_contextLostCallback->onContextLost(); return false; } return success; } bool GraphicsContext3DPrivate::prepareBuffer() const { if (!makeContextCurrent()) return false; m_context->markLayerComposited(); if (m_context->m_attrs.antialias) { bool enableScissorTest = false; int width = m_context->m_currentWidth; int height = m_context->m_currentHeight; // We should copy the full buffer, and not respect the current scissor bounds. // FIXME: It would be more efficient to track the state of the scissor test. if (m_context->isEnabled(GraphicsContext3D::SCISSOR_TEST)) { enableScissorTest = true; m_context->disable(GraphicsContext3D::SCISSOR_TEST); } glBindFramebuffer(Extensions3D::READ_FRAMEBUFFER, m_context->m_multisampleFBO); glBindFramebuffer(Extensions3D::DRAW_FRAMEBUFFER, m_context->m_fbo); // Use NEAREST as no scale is performed during the blit. m_context->getExtensions()->blitFramebuffer(0, 0, width, height, 0, 0, width, height, GraphicsContext3D::COLOR_BUFFER_BIT, GraphicsContext3D::NEAREST); if (enableScissorTest) m_context->enable(GraphicsContext3D::SCISSOR_TEST); glBindFramebuffer(GL_FRAMEBUFFER, m_context->m_state.boundFBO); } return true; } #if USE(TEXTURE_MAPPER_GL) void GraphicsContext3DPrivate::paintToTextureMapper(TextureMapper*, const FloatRect& /* target */, const TransformationMatrix&, float /* opacity */) { notImplemented(); } #endif #if USE(GRAPHICS_SURFACE) void GraphicsContext3DPrivate::createGraphicsSurface() { static PendingSurfaceOperation pendingOperation = DeletePreviousSurface | Resize | CreateSurface; if (!(m_surfaceOperation & pendingOperation)) return; if (m_surfaceOperation & DeletePreviousSurface) { m_previousGraphicsSurface = nullptr; m_surfaceOperation &= ~DeletePreviousSurface; } if (!(m_surfaceOperation & pendingOperation)) return; // Don't release current graphics surface until we have prepared surface // with requested size. This is to avoid flashing during resize. if (m_surfaceOperation & Resize) { m_previousGraphicsSurface = m_graphicsSurface; m_surfaceOperation &= ~Resize; m_surfaceOperation |= DeletePreviousSurface; m_size = IntSize(m_context->m_currentWidth, m_context->m_currentHeight); } else m_surfaceOperation &= ~CreateSurface; m_targetRect = IntRect(IntPoint(), m_size); if (m_size.isEmpty()) { if (m_graphicsSurface) { m_graphicsSurface = nullptr; m_surfaceHandle = GraphicsSurfaceToken(); makeContextCurrent(); } return; } m_offScreenContext->releaseCurrent(); GraphicsSurface::Flags flags = GraphicsSurface::SupportsTextureTarget | GraphicsSurface::SupportsSharing; if (m_context->m_attrs.alpha) flags |= GraphicsSurface::SupportsAlpha; m_graphicsSurface = GraphicsSurface::create(m_size, flags, m_offScreenContext->handle()); if (!m_graphicsSurface) m_surfaceHandle = GraphicsSurfaceToken(); else m_surfaceHandle = GraphicsSurfaceToken(m_graphicsSurface->exportToken()); makeContextCurrent(); } void GraphicsContext3DPrivate::didResizeCanvas(const IntSize& size) { if (m_surfaceOperation & CreateSurface) { m_size = size; createGraphicsSurface(); return; } m_surfaceOperation |= Resize; } uint32_t GraphicsContext3DPrivate::copyToGraphicsSurface() { createGraphicsSurface(); if (!m_graphicsSurface || m_context->m_layerComposited || !prepareBuffer()) return 0; m_graphicsSurface->copyFromTexture(m_context->m_texture, m_targetRect); makeContextCurrent(); return m_graphicsSurface->frontBuffer(); } GraphicsSurfaceToken GraphicsContext3DPrivate::graphicsSurfaceToken() const { return m_surfaceHandle; } IntSize GraphicsContext3DPrivate::platformLayerSize() const { return m_size; } GraphicsSurface::Flags GraphicsContext3DPrivate::graphicsSurfaceFlags() const { if (m_graphicsSurface) return m_graphicsSurface->flags(); return TextureMapperPlatformLayer::graphicsSurfaceFlags(); } #endif } // namespace WebCore
loveyoupeng/rt
modules/web/src/main/native/Source/WebCore/platform/graphics/efl/GraphicsContext3DPrivate.cpp
C++
gpl-2.0
8,176
#ifndef FONT_HPP #define FONT_HPP #include "renderer/OpenGL.hpp" #include <string> class Texture; class Font { public: Font(const char *texture); ~Font(); void SetColor(const Math::Vector4f &color) { m_color = color; } void SetPosition(const Math::Vector3f &position) { m_position = position; } void SetScale(const Math::Vector2f &scale) { m_scale = scale; } void drawText(const std::string &text); void drawText(const std::string &text, float x, float y, float z, float r, float g, float b, float a); void drawText(const std::string &text, const Math::Vector3f &position, const Math::Vector4f &color=Math::Vector4f(1.f, 1.f, 1.f, 1.f)); void drawText(const std::string &text, float x, float y, float z=-1.0f); private: void renderAt(const Math::Vector3f &pos, int w, int h, int uo, int vo, const Math::Vector4f &color); Texture* m_texture; Math::Vector2f m_scale; Math::Vector3f m_position; Math::Vector4f m_color; // OpenGL thingamabobs GLuint m_fontVertexArray; // VAO GLuint m_vertexBuffer; // VBO GLuint m_indexBuffer; // IBO GLuint m_vertexPosAttr; // attribute location }; #endif
fluffyfreak/oculusvr_samples
common_src/renderer/Font.hpp
C++
gpl-2.0
1,188
#!/usr/bin/env node console.log("Hello World!");
sumeettalwar/develop
node-js/src/week1/hello.js
JavaScript
gpl-2.0
49
$(document).ready(function(){ $("#startDate").datepicker({dateFormat:'yy-mm-dd'}); $("#endDate").datepicker({dateFormat:'yy-mm-dd'}); //$('#startDate').datepicker(); //$('#endDate').datepicker(); })
sorabhv6/mylib
php_lib/google_analytics/js/custom.js
JavaScript
gpl-2.0
211
// /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright © 2011 Marcos Talau * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Marcos Talau (talau@users.sourceforge.net) * * Thanks to: Duy Nguyen<duy@soe.ucsc.edu> by RED efforts in NS3 * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright (c) 1990-1997 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor of the Laboratory may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * PORT NOTE: This code was ported from ns-2 (queue/red.cc). Almost all * comments have also been ported from NS-2 */ #include "ns3/log.h" #include "ns3/enum.h" #include "ns3/uinteger.h" #include "ns3/double.h" #include "ns3/simulator.h" #include "ns3/abort.h" #include "red-queue-disc.h" #include "ns3/drop-tail-queue.h" #include "ns3/net-device-queue-interface.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("RedQueueDisc"); NS_OBJECT_ENSURE_REGISTERED (RedQueueDisc); TypeId RedQueueDisc::GetTypeId (void) { static TypeId tid = TypeId ("ns3::RedQueueDisc") .SetParent<QueueDisc> () .SetGroupName("TrafficControl") .AddConstructor<RedQueueDisc> () .AddAttribute ("MeanPktSize", "Average of packet size", UintegerValue (500), MakeUintegerAccessor (&RedQueueDisc::m_meanPktSize), MakeUintegerChecker<uint32_t> ()) .AddAttribute ("IdlePktSize", "Average packet size used during idle times. Used when m_cautions = 3", UintegerValue (0), MakeUintegerAccessor (&RedQueueDisc::m_idlePktSize), MakeUintegerChecker<uint32_t> ()) .AddAttribute ("Wait", "True for waiting between dropped packets", BooleanValue (true), MakeBooleanAccessor (&RedQueueDisc::m_isWait), MakeBooleanChecker ()) .AddAttribute ("Gentle", "True to increases dropping probability slowly when average queue exceeds maxthresh", BooleanValue (true), MakeBooleanAccessor (&RedQueueDisc::m_isGentle), MakeBooleanChecker ()) .AddAttribute ("ARED", "True to enable ARED", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isARED), MakeBooleanChecker ()) .AddAttribute ("AdaptMaxP", "True to adapt m_curMaxP", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isAdaptMaxP), MakeBooleanChecker ()) .AddAttribute ("FengAdaptive", "True to enable Feng's Adaptive RED", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isFengAdaptive), MakeBooleanChecker ()) .AddAttribute ("NLRED", "True to enable Nonlinear RED", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isNonlinear), MakeBooleanChecker ()) .AddAttribute ("MinTh", "Minimum average length threshold in packets/bytes", DoubleValue (5), MakeDoubleAccessor (&RedQueueDisc::m_minTh), MakeDoubleChecker<double> ()) .AddAttribute ("MaxTh", "Maximum average length threshold in packets/bytes", DoubleValue (15), MakeDoubleAccessor (&RedQueueDisc::m_maxTh), MakeDoubleChecker<double> ()) .AddAttribute ("MaxSize", "The maximum number of packets accepted by this queue disc", QueueSizeValue (QueueSize ("25p")), MakeQueueSizeAccessor (&QueueDisc::SetMaxSize, &QueueDisc::GetMaxSize), MakeQueueSizeChecker ()) .AddAttribute ("QW", "Queue weight related to the exponential weighted moving average (EWMA)", DoubleValue (0.002), MakeDoubleAccessor (&RedQueueDisc::m_qW), MakeDoubleChecker <double> ()) .AddAttribute ("LInterm", "The maximum probability of dropping a packet", DoubleValue (50), MakeDoubleAccessor (&RedQueueDisc::m_lInterm), MakeDoubleChecker <double> ()) .AddAttribute ("TargetDelay", "Target average queuing delay in ARED", TimeValue (Seconds (0.005)), MakeTimeAccessor (&RedQueueDisc::m_targetDelay), MakeTimeChecker ()) .AddAttribute ("Interval", "Time interval to update m_curMaxP", TimeValue (Seconds (0.5)), MakeTimeAccessor (&RedQueueDisc::m_interval), MakeTimeChecker ()) .AddAttribute ("Top", "Upper bound for m_curMaxP in ARED", DoubleValue (0.5), MakeDoubleAccessor (&RedQueueDisc::m_top), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("Bottom", "Lower bound for m_curMaxP in ARED", DoubleValue (0.0), MakeDoubleAccessor (&RedQueueDisc::m_bottom), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("Alpha", "Increment parameter for m_curMaxP in ARED", DoubleValue (0.01), MakeDoubleAccessor (&RedQueueDisc::SetAredAlpha), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("Beta", "Decrement parameter for m_curMaxP in ARED", DoubleValue (0.9), MakeDoubleAccessor (&RedQueueDisc::SetAredBeta), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("FengAlpha", "Decrement parameter for m_curMaxP in Feng's Adaptive RED", DoubleValue (3.0), MakeDoubleAccessor (&RedQueueDisc::SetFengAdaptiveA), MakeDoubleChecker <double> ()) .AddAttribute ("FengBeta", "Increment parameter for m_curMaxP in Feng's Adaptive RED", DoubleValue (2.0), MakeDoubleAccessor (&RedQueueDisc::SetFengAdaptiveB), MakeDoubleChecker <double> ()) .AddAttribute ("LastSet", "Store the last time m_curMaxP was updated", TimeValue (Seconds (0.0)), MakeTimeAccessor (&RedQueueDisc::m_lastSet), MakeTimeChecker ()) .AddAttribute ("Rtt", "Round Trip Time to be considered while automatically setting m_bottom", TimeValue (Seconds (0.1)), MakeTimeAccessor (&RedQueueDisc::m_rtt), MakeTimeChecker ()) .AddAttribute ("Ns1Compat", "NS-1 compatibility", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isNs1Compat), MakeBooleanChecker ()) .AddAttribute ("LinkBandwidth", "The RED link bandwidth", DataRateValue (DataRate ("1.5Mbps")), MakeDataRateAccessor (&RedQueueDisc::m_linkBandwidth), MakeDataRateChecker ()) .AddAttribute ("LinkDelay", "The RED link delay", TimeValue (MilliSeconds (20)), MakeTimeAccessor (&RedQueueDisc::m_linkDelay), MakeTimeChecker ()) .AddAttribute ("UseEcn", "True to use ECN (packets are marked instead of being dropped)", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_useEcn), MakeBooleanChecker ()) .AddAttribute ("UseHardDrop", "True to always drop packets above max threshold", BooleanValue (true), MakeBooleanAccessor (&RedQueueDisc::m_useHardDrop), MakeBooleanChecker ()) ; return tid; } RedQueueDisc::RedQueueDisc () : QueueDisc (QueueDiscSizePolicy::SINGLE_INTERNAL_QUEUE) { NS_LOG_FUNCTION (this); m_uv = CreateObject<UniformRandomVariable> (); } RedQueueDisc::~RedQueueDisc () { NS_LOG_FUNCTION (this); } void RedQueueDisc::DoDispose (void) { NS_LOG_FUNCTION (this); m_uv = 0; QueueDisc::DoDispose (); } void RedQueueDisc::SetAredAlpha (double alpha) { NS_LOG_FUNCTION (this << alpha); m_alpha = alpha; if (m_alpha > 0.01) { NS_LOG_WARN ("Alpha value is above the recommended bound!"); } } double RedQueueDisc::GetAredAlpha (void) { NS_LOG_FUNCTION (this); return m_alpha; } void RedQueueDisc::SetAredBeta (double beta) { NS_LOG_FUNCTION (this << beta); m_beta = beta; if (m_beta < 0.83) { NS_LOG_WARN ("Beta value is below the recommended bound!"); } } double RedQueueDisc::GetAredBeta (void) { NS_LOG_FUNCTION (this); return m_beta; } void RedQueueDisc::SetFengAdaptiveA (double a) { NS_LOG_FUNCTION (this << a); m_a = a; if (m_a != 3) { NS_LOG_WARN ("Alpha value does not follow the recommendations!"); } } double RedQueueDisc::GetFengAdaptiveA (void) { NS_LOG_FUNCTION (this); return m_a; } void RedQueueDisc::SetFengAdaptiveB (double b) { NS_LOG_FUNCTION (this << b); m_b = b; if (m_b != 2) { NS_LOG_WARN ("Beta value does not follow the recommendations!"); } } double RedQueueDisc::GetFengAdaptiveB (void) { NS_LOG_FUNCTION (this); return m_b; } void RedQueueDisc::SetTh (double minTh, double maxTh) { NS_LOG_FUNCTION (this << minTh << maxTh); NS_ASSERT (minTh <= maxTh); m_minTh = minTh; m_maxTh = maxTh; } int64_t RedQueueDisc::AssignStreams (int64_t stream) { NS_LOG_FUNCTION (this << stream); m_uv->SetStream (stream); return 1; } bool RedQueueDisc::DoEnqueue (Ptr<QueueDiscItem> item) { NS_LOG_FUNCTION (this << item); uint32_t nQueued = GetInternalQueue (0)->GetCurrentSize ().GetValue (); // simulate number of packets arrival during idle period uint32_t m = 0; if (m_idle == 1) { NS_LOG_DEBUG ("RED Queue Disc is idle."); Time now = Simulator::Now (); if (m_cautious == 3) { double ptc = m_ptc * m_meanPktSize / m_idlePktSize; m = uint32_t (ptc * (now - m_idleTime).GetSeconds ()); } else { m = uint32_t (m_ptc * (now - m_idleTime).GetSeconds ()); } m_idle = 0; } m_qAvg = Estimator (nQueued, m + 1, m_qAvg, m_qW); NS_LOG_DEBUG ("\t bytesInQueue " << GetInternalQueue (0)->GetNBytes () << "\tQavg " << m_qAvg); NS_LOG_DEBUG ("\t packetsInQueue " << GetInternalQueue (0)->GetNPackets () << "\tQavg " << m_qAvg); m_count++; m_countBytes += item->GetSize (); uint32_t dropType = DTYPE_NONE; if (m_qAvg >= m_minTh && nQueued > 1) { if ((!m_isGentle && m_qAvg >= m_maxTh) || (m_isGentle && m_qAvg >= 2 * m_maxTh)) { NS_LOG_DEBUG ("adding DROP FORCED MARK"); dropType = DTYPE_FORCED; } else if (m_old == 0) { /* * The average queue size has just crossed the * threshold from below to above m_minTh, or * from above m_minTh with an empty queue to * above m_minTh with a nonempty queue. */ m_count = 1; m_countBytes = item->GetSize (); m_old = 1; } else if (DropEarly (item, nQueued)) { NS_LOG_LOGIC ("DropEarly returns 1"); dropType = DTYPE_UNFORCED; } } else { // No packets are being dropped m_vProb = 0.0; m_old = 0; } if (dropType == DTYPE_UNFORCED) { if (!m_useEcn || !Mark (item, UNFORCED_MARK)) { NS_LOG_DEBUG ("\t Dropping due to Prob Mark " << m_qAvg); DropBeforeEnqueue (item, UNFORCED_DROP); return false; } NS_LOG_DEBUG ("\t Marking due to Prob Mark " << m_qAvg); } else if (dropType == DTYPE_FORCED) { if (m_useHardDrop || !m_useEcn || !Mark (item, FORCED_MARK)) { NS_LOG_DEBUG ("\t Dropping due to Hard Mark " << m_qAvg); DropBeforeEnqueue (item, FORCED_DROP); if (m_isNs1Compat) { m_count = 0; m_countBytes = 0; } return false; } NS_LOG_DEBUG ("\t Marking due to Hard Mark " << m_qAvg); } bool retval = GetInternalQueue (0)->Enqueue (item); // If Queue::Enqueue fails, QueueDisc::DropBeforeEnqueue is called by the // internal queue because QueueDisc::AddInternalQueue sets the trace callback NS_LOG_LOGIC ("Number packets " << GetInternalQueue (0)->GetNPackets ()); NS_LOG_LOGIC ("Number bytes " << GetInternalQueue (0)->GetNBytes ()); return retval; } /* * Note: if the link bandwidth changes in the course of the * simulation, the bandwidth-dependent RED parameters do not change. * This should be fixed, but it would require some extra parameters, * and didn't seem worth the trouble... */ void RedQueueDisc::InitializeParams (void) { NS_LOG_FUNCTION (this); NS_LOG_INFO ("Initializing RED params."); m_cautious = 0; m_ptc = m_linkBandwidth.GetBitRate () / (8.0 * m_meanPktSize); if (m_isARED) { // Set m_minTh, m_maxTh and m_qW to zero for automatic setting m_minTh = 0; m_maxTh = 0; m_qW = 0; // Turn on m_isAdaptMaxP to adapt m_curMaxP m_isAdaptMaxP = true; } if (m_isFengAdaptive) { // Initialize m_fengStatus m_fengStatus = Above; } if (m_minTh == 0 && m_maxTh == 0) { m_minTh = 5.0; // set m_minTh to max(m_minTh, targetqueue/2.0) [Ref: http://www.icir.org/floyd/papers/adaptiveRed.pdf] double targetqueue = m_targetDelay.GetSeconds() * m_ptc; if (m_minTh < targetqueue / 2.0 ) { m_minTh = targetqueue / 2.0; } if (GetMaxSize ().GetUnit () == QueueSizeUnit::BYTES) { m_minTh = m_minTh * m_meanPktSize; } // set m_maxTh to three times m_minTh [Ref: http://www.icir.org/floyd/papers/adaptiveRed.pdf] m_maxTh = 3 * m_minTh; } NS_ASSERT (m_minTh <= m_maxTh); m_qAvg = 0.0; m_count = 0; m_countBytes = 0; m_old = 0; m_idle = 1; double th_diff = (m_maxTh - m_minTh); if (th_diff == 0) { th_diff = 1.0; } m_vA = 1.0 / th_diff; m_curMaxP = 1.0 / m_lInterm; m_vB = -m_minTh / th_diff; if (m_isGentle) { m_vC = (1.0 - m_curMaxP) / m_maxTh; m_vD = 2.0 * m_curMaxP - 1.0; } m_idleTime = NanoSeconds (0); /* * If m_qW=0, set it to a reasonable value of 1-exp(-1/C) * This corresponds to choosing m_qW to be of that value for * which the packet time constant -1/ln(1-m)qW) per default RTT * of 100ms is an order of magnitude more than the link capacity, C. * * If m_qW=-1, then the queue weight is set to be a function of * the bandwidth and the link propagation delay. In particular, * the default RTT is assumed to be three times the link delay and * transmission delay, if this gives a default RTT greater than 100 ms. * * If m_qW=-2, set it to a reasonable value of 1-exp(-10/C). */ if (m_qW == 0.0) { m_qW = 1.0 - std::exp (-1.0 / m_ptc); } else if (m_qW == -1.0) { double rtt = 3.0 * (m_linkDelay.GetSeconds () + 1.0 / m_ptc); if (rtt < 0.1) { rtt = 0.1; } m_qW = 1.0 - std::exp (-1.0 / (10 * rtt * m_ptc)); } else if (m_qW == -2.0) { m_qW = 1.0 - std::exp (-10.0 / m_ptc); } if (m_bottom == 0) { m_bottom = 0.01; // Set bottom to at most 1/W, where W is the delay-bandwidth // product in packets for a connection. // So W = m_linkBandwidth.GetBitRate () / (8.0 * m_meanPktSize * m_rtt.GetSeconds()) double bottom1 = (8.0 * m_meanPktSize * m_rtt.GetSeconds()) / m_linkBandwidth.GetBitRate(); if (bottom1 < m_bottom) { m_bottom = bottom1; } } NS_LOG_DEBUG ("\tm_delay " << m_linkDelay.GetSeconds () << "; m_isWait " << m_isWait << "; m_qW " << m_qW << "; m_ptc " << m_ptc << "; m_minTh " << m_minTh << "; m_maxTh " << m_maxTh << "; m_isGentle " << m_isGentle << "; th_diff " << th_diff << "; lInterm " << m_lInterm << "; va " << m_vA << "; cur_max_p " << m_curMaxP << "; v_b " << m_vB << "; m_vC " << m_vC << "; m_vD " << m_vD); } // Updating m_curMaxP, following the pseudocode // from: A Self-Configuring RED Gateway, INFOCOMM '99. // They recommend m_a = 3, and m_b = 2. void RedQueueDisc::UpdateMaxPFeng (double newAve) { NS_LOG_FUNCTION (this << newAve); if (m_minTh < newAve && newAve < m_maxTh) { m_fengStatus = Between; } else if (newAve < m_minTh && m_fengStatus != Below) { m_fengStatus = Below; m_curMaxP = m_curMaxP / m_a; } else if (newAve > m_maxTh && m_fengStatus != Above) { m_fengStatus = Above; m_curMaxP = m_curMaxP * m_b; } } // Update m_curMaxP to keep the average queue length within the target range. void RedQueueDisc::UpdateMaxP (double newAve) { NS_LOG_FUNCTION (this << newAve); Time now = Simulator::Now (); double m_part = 0.4 * (m_maxTh - m_minTh); // AIMD rule to keep target Q~1/2(m_minTh + m_maxTh) if (newAve < m_minTh + m_part && m_curMaxP > m_bottom) { // we should increase the average queue size, so decrease m_curMaxP m_curMaxP = m_curMaxP * m_beta; m_lastSet = now; } else if (newAve > m_maxTh - m_part && m_top > m_curMaxP) { // we should decrease the average queue size, so increase m_curMaxP double alpha = m_alpha; if (alpha > 0.25 * m_curMaxP) { alpha = 0.25 * m_curMaxP; } m_curMaxP = m_curMaxP + alpha; m_lastSet = now; } } // Compute the average queue size double RedQueueDisc::Estimator (uint32_t nQueued, uint32_t m, double qAvg, double qW) { NS_LOG_FUNCTION (this << nQueued << m << qAvg << qW); double newAve = qAvg * std::pow (1.0 - qW, m); newAve += qW * nQueued; Time now = Simulator::Now (); if (m_isAdaptMaxP && now > m_lastSet + m_interval) { UpdateMaxP (newAve); } else if (m_isFengAdaptive) { UpdateMaxPFeng (newAve); // Update m_curMaxP in MIMD fashion. } return newAve; } // Check if packet p needs to be dropped due to probability mark uint32_t RedQueueDisc::DropEarly (Ptr<QueueDiscItem> item, uint32_t qSize) { NS_LOG_FUNCTION (this << item << qSize); double prob1 = CalculatePNew (); m_vProb = ModifyP (prob1, item->GetSize ()); // Drop probability is computed, pick random number and act if (m_cautious == 1) { /* * Don't drop/mark if the instantaneous queue is much below the average. * For experimental purposes only. * pkts: the number of packets arriving in 50 ms */ double pkts = m_ptc * 0.05; double fraction = std::pow ((1 - m_qW), pkts); if ((double) qSize < fraction * m_qAvg) { // Queue could have been empty for 0.05 seconds return 0; } } double u = m_uv->GetValue (); if (m_cautious == 2) { /* * Decrease the drop probability if the instantaneous * queue is much below the average. * For experimental purposes only. * pkts: the number of packets arriving in 50 ms */ double pkts = m_ptc * 0.05; double fraction = std::pow ((1 - m_qW), pkts); double ratio = qSize / (fraction * m_qAvg); if (ratio < 1.0) { u *= 1.0 / ratio; } } if (u <= m_vProb) { NS_LOG_LOGIC ("u <= m_vProb; u " << u << "; m_vProb " << m_vProb); // DROP or MARK m_count = 0; m_countBytes = 0; /// \todo Implement set bit to mark return 1; // drop } return 0; // no drop/mark } // Returns a probability using these function parameters for the DropEarly function double RedQueueDisc::CalculatePNew (void) { NS_LOG_FUNCTION (this); double p; if (m_isGentle && m_qAvg >= m_maxTh) { // p ranges from m_curMaxP to 1 as the average queue // size ranges from m_maxTh to twice m_maxTh p = m_vC * m_qAvg + m_vD; } else if (!m_isGentle && m_qAvg >= m_maxTh) { /* * OLD: p continues to range linearly above m_curMaxP as * the average queue size ranges above m_maxTh. * NEW: p is set to 1.0 */ p = 1.0; } else { /* * p ranges from 0 to m_curMaxP as the average queue size ranges from * m_minTh to m_maxTh */ p = m_vA * m_qAvg + m_vB; if (m_isNonlinear) { p *= p * 1.5; } p *= m_curMaxP; } if (p > 1.0) { p = 1.0; } return p; } // Returns a probability using these function parameters for the DropEarly function double RedQueueDisc::ModifyP (double p, uint32_t size) { NS_LOG_FUNCTION (this << p << size); double count1 = (double) m_count; if (GetMaxSize ().GetUnit () == QueueSizeUnit::BYTES) { count1 = (double) (m_countBytes / m_meanPktSize); } if (m_isWait) { if (count1 * p < 1.0) { p = 0.0; } else if (count1 * p < 2.0) { p /= (2.0 - count1 * p); } else { p = 1.0; } } else { if (count1 * p < 1.0) { p /= (1.0 - count1 * p); } else { p = 1.0; } } if ((GetMaxSize ().GetUnit () == QueueSizeUnit::BYTES) && (p < 1.0)) { p = (p * size) / m_meanPktSize; } if (p > 1.0) { p = 1.0; } return p; } Ptr<QueueDiscItem> RedQueueDisc::DoDequeue (void) { NS_LOG_FUNCTION (this); if (GetInternalQueue (0)->IsEmpty ()) { NS_LOG_LOGIC ("Queue empty"); m_idle = 1; m_idleTime = Simulator::Now (); return 0; } else { m_idle = 0; Ptr<QueueDiscItem> item = GetInternalQueue (0)->Dequeue (); NS_LOG_LOGIC ("Popped " << item); NS_LOG_LOGIC ("Number packets " << GetInternalQueue (0)->GetNPackets ()); NS_LOG_LOGIC ("Number bytes " << GetInternalQueue (0)->GetNBytes ()); return item; } } Ptr<const QueueDiscItem> RedQueueDisc::DoPeek (void) { NS_LOG_FUNCTION (this); if (GetInternalQueue (0)->IsEmpty ()) { NS_LOG_LOGIC ("Queue empty"); return 0; } Ptr<const QueueDiscItem> item = GetInternalQueue (0)->Peek (); NS_LOG_LOGIC ("Number packets " << GetInternalQueue (0)->GetNPackets ()); NS_LOG_LOGIC ("Number bytes " << GetInternalQueue (0)->GetNBytes ()); return item; } bool RedQueueDisc::CheckConfig (void) { NS_LOG_FUNCTION (this); if (GetNQueueDiscClasses () > 0) { NS_LOG_ERROR ("RedQueueDisc cannot have classes"); return false; } if (GetNPacketFilters () > 0) { NS_LOG_ERROR ("RedQueueDisc cannot have packet filters"); return false; } if (GetNInternalQueues () == 0) { // add a DropTail queue AddInternalQueue (CreateObjectWithAttributes<DropTailQueue<QueueDiscItem> > ("MaxSize", QueueSizeValue (GetMaxSize ()))); } if (GetNInternalQueues () != 1) { NS_LOG_ERROR ("RedQueueDisc needs 1 internal queue"); return false; } if ((m_isARED || m_isAdaptMaxP) && m_isFengAdaptive) { NS_LOG_ERROR ("m_isAdaptMaxP and m_isFengAdaptive cannot be simultaneously true"); } return true; } } // namespace ns3
tomhenderson/ns-3-dev-git
src/traffic-control/model/red-queue-disc.cc
C++
gpl-2.0
26,145
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LeagueSharp; using LeagueSharp.Common; using Item = LeagueSharp.Common.Items.Item; namespace Kalista { public class ItemManager { private static Obj_AI_Hero player = ObjectManager.Player; // Offensive items public static readonly Item CUTLASS = ItemData.Bilgewater_Cutlass.GetItem(); public static readonly Item BOTRK = ItemData.Blade_of_the_Ruined_King.GetItem(); public static readonly Item YOUMUU = ItemData.Youmuus_Ghostblade.GetItem(); public static bool UseBotrk(Obj_AI_Hero target) { if (Config.BoolLinks["itemsBotrk"].Value && BOTRK.IsReady() && target.IsValidTarget(BOTRK.Range) && player.Health + player.GetItemDamage(target, Damage.DamageItems.Botrk) < player.MaxHealth) { return BOTRK.Cast(target); } else if (Config.BoolLinks["itemsCutlass"].Value && CUTLASS.IsReady() && target.IsValidTarget(CUTLASS.Range)) { return CUTLASS.Cast(target); } return false; } public static bool UseYoumuu(Obj_AI_Base target) { if (Config.BoolLinks["itemsYoumuu"].Value && YOUMUU.IsReady() && target.IsValidTarget(Orbwalking.GetRealAutoAttackRange(player) + 50)) { return YOUMUU.Cast(); } return false; } } }
onuremix/LeagueSharp
Kalista/ItemManager.cs
C#
gpl-2.0
1,531
<?php /** * RokTwittie Module * * @package RocketTheme * @subpackage roktwittie.tmpl * @version 1.8 September 3, 2012 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2012 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * */ defined('_JEXEC') or die('Restricted access'); $error = (isset($status) && is_string($status)) ? $status : (isset($friends) ? $friends : ''); $error = (is_string($error)) ? $error : ''; ?> <div id="roktwittie" class="roktwittie<?php echo $params->get('moduleclass_sfx'); ?>"> <div class="error"> <?php echo $error; ?> </div> </div>
jntd11/dev2
modules/mod_roktwittie/tmpl/error.php
PHP
gpl-2.0
650