answer
stringlengths
15
1.25M
#ifndef ENGINE_P_H #define ENGINE_P_H #include <QHash> #include <QObject> #include <private/qv4engine_p.h> #include <private/qv4persistent_p.h> class QJSEngine; namespace NodeQml { namespace Heap { struct ModuleObject; } class Engine; struct ModuleObject; class EnginePrivate : public QObject { Q_OBJECT public: static EnginePrivate *get(QV4::ExecutionEngine *v4); explicit EnginePrivate(QJSEngine *jsEngine, Engine *engine = 0); ~EnginePrivate(); void doneCheck(); void exceptionCheck(); bool hasNativeModule(const QString &id) const; QV4::Heap::Object *nativeModule(const QString &id) const; void cacheModule(const QString& id, Heap::ModuleObject *module); bool hasCachedModule(const QString &id) const; Heap::ModuleObject *cachedModule(const QString &id) const; QV4::ReturnedValue require(const QString &id); QV4::ReturnedValue setTimeout(QV4::CallContext *ctx); QV4::ReturnedValue clearTimeout(QV4::CallContext *ctx); QV4::ReturnedValue setInterval(QV4::CallContext *ctx); QV4::ReturnedValue clearInterval(QV4::CallContext *ctx); QV4::ReturnedValue nextTick(QV4::CallContext *ctx); QV4::ReturnedValue throwErrnoException(int errorNo, const QString &syscall); public: QV4::Value bufferCtor; QV4::Value bufferPrototype; QV4::Value <API key>; protected: void customEvent(QEvent *event) override; void timerEvent(QTimerEvent *event) override; private: Engine * const q_ptr; Q_DECLARE_PUBLIC(Engine) void registerTypes(); void registerModules(); QV4::ExecutionEngine *m_v4; QHash<QString, QV4::PersistentValue> m_coreModules; QHash<QString, QV4::PersistentValue> m_cachedModules; QHash<int, QV4::PersistentValue> m_timeoutCallbacks; QHash<int, QV4::PersistentValue> m_intervalCallbacks; static QHash<QV4::ExecutionEngine *, EnginePrivate*> m_nodeEngines; }; } #endif // ENGINE_P_H
// Created file "Lib\src\Uuid\X64\oledbdat" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(DBGUID_ROW, 0xc8b522f7, 0x5cf3, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d);
// For user: you can disable or enable it //#define MEDIAINFO_DEBUG // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "MediaInfo/Setup.h" #if defined(<API key>) #include "MediaInfo/Reader/Reader_libcurl.h" #include "MediaInfo/File__Analyze.h" #if defined <API key> //Copy of cURL include files #include "MediaInfo/Reader/<API key>.h" #else #define CURL_STATICLIB #undef __TEXT #include "curl/curl.h" #endif #include <ctime> #include <algorithm> //For Url #define MEDIAINFO_HMAC 1 #if MEDIAINFO_HMAC #include "hmac.h" #include "base64.h" #endif //MEDIAINFO_HMAC #include "MediaInfo/HashWrapper.h" #include "ZenLib/File.h" #include "tinyxml2.h" using namespace tinyxml2; using namespace ZenLib; using namespace std; #ifdef MEDIAINFO_DEBUG #include <iostream> #endif // MEDIAINFO_DEBUG namespace MediaInfoLib { /* Load library */ /* Load methods */
#include <nuSQuIDS/xsections.h> #include <nuSQuIDS/nuSQuIDS.h> #include <SQuIDS/const.h> #include <SQuIDS/SUNalg.h> std::ostream& operator<<(std::ostream &f, const std::vector<double> &vec) { f << "["; for (const double &v : vec) f << " " << v; f << "]"; return f; } double integrate_xs(double start, double stop, double step, double e0) { using namespace nusquids; if(start>stop){ std::cout << "Integration stop is less than start." << std::endl; return 0; } unsigned int nsteps=(stop-start)/step; double xs = 0; const squids::Const constants; <API key> gr; for (unsigned int i=0; i < nsteps; i++) { double logE = start + step*i; double dE = pow(10., logE+step) - pow(10., logE); xs += gr.<API key>(e0,pow(10., logE)*constants.GeV, <API key>::electron, <API key>::antineutrino, <API key>::GR)*dE; } double scale = xs/gr.TotalCrossSection(e0, <API key>::electron, <API key>::antineutrino, <API key>::GR)/gr.<API key>(<API key>::muon); return scale; } int main (int argc, char const *argv[]) { using namespace nusquids; const squids::Const constants; std::cout << "Checking single-differential cross-section" << std::endl; std::cout << "\\int dsigma/dE / sigma = " << integrate_xs(0, 7, 0.001, 6.3e6*constants.GeV) << std::endl; assert(std::abs(integrate_xs(0, 7, 0.001, 6.3e6*constants.GeV) - 1) < 3e-3); std::cout << "Evolving a nue_bar line spectrum at the Glashow resonance" << std::endl; const unsigned int numneu = 3; const unsigned int num_steps = 201; squids::Const units; auto gr_only = std::make_shared<CrossSectionLibrary>(); gr_only->addTarget(electron,<API key>()); gr_only->addTarget(isoscalar_nucleon, NullCrossSections()); nuSQUIDS squid(logspace(1e4*units.GeV,1e7*units.GeV,num_steps),numneu,both,true,gr_only); std::shared_ptr<ConstantDensity> const_dens = std::make_shared<ConstantDensity>(10.,0.5); std::shared_ptr<ConstantDensity::Track> const_dens_track = std::make_shared<ConstantDensity::Track>(10000.*units.km); squid.Set_Body(const_dens); squid.Set_Track(const_dens_track); squid.<API key>(false); squid.<API key>(true); squid.<API key>(false); squid.Set_TauRegeneration(false); // setup integration settings squid.Set_h_max( 100.0*units.km ); squid.Set_GSL_step(<API key>); squid.Set_rel_error(1.0e-25); squid.Set_abs_error(1.0e-25); // construct the initial state marray<double,3> inistate{num_steps,2,numneu}; std::fill(inistate.begin(), inistate.end(), 0.); marray<double,1> E_range = squid.GetERange(); for(unsigned int ie = 0; ie < E_range.size(); ie++){ inistate[ie][1][0] = 1./(E_range[ie]); } // set the initial state squid.Set_initial_state(inistate,flavor); std::cout << "Propagating. . . " << std::endl; squid.EvolveState(); std::cout << "Propagation done" << std::endl; std::ostream &output = std::cout; // One part in a thousand is a somewhat loose tolerance, but this is necessary because the key area // around the resonance has such a suppression of the (nuebar) flux that it has much higher relative error. output.precision(3); for (auto i=0; i < num_steps-1; i++) { double ee = E_range[i]; double de = (E_range[i+1]-E_range[i])/units.GeV; output << i << " "; output << E_range[i]/units.GeV << " "; output << squid.EvalFlavorAtNode(0,i,0)*ee << " "; output << squid.EvalFlavorAtNode(1,i,0)*ee << " "; output << squid.EvalFlavorAtNode(2,i,0)*ee << " "; output << squid.EvalFlavorAtNode(0,i,1)*ee << " "; output << squid.EvalFlavorAtNode(1,i,1)*ee << " "; output << squid.EvalFlavorAtNode(2,i,1)*ee << " "; output << std::endl; } return 0; }
# About HubTurbo HubTurbo project is based in the [School of Computing](http: and funded by the [Center for Development of Teaching and Learning (CDTL)](http: The HubTurbo project team is listed [here](team.md).
package com.sones; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.datacontract.schemas._2004._07.<API key>.SecurityToken; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "mySecurityToken", "myTransactionToken", "myVertexTypeName" }) @XmlRootElement(name = "TruncateVertexType") public class TruncateVertexType { @XmlElement(nillable = true) protected SecurityToken mySecurityToken; protected Long myTransactionToken; @XmlElement(nillable = true) protected String myVertexTypeName; /** * Gets the value of the mySecurityToken property. * * @return * possible object is * {@link SecurityToken } * */ public Security<API key>() { return mySecurityToken; } /** * Sets the value of the mySecurityToken property. * * @param value * allowed object is * {@link SecurityToken } * */ public void setMySecurityToken(SecurityToken value) { this.mySecurityToken = value; } /** * Gets the value of the myTransactionToken property. * * @return * possible object is * {@link Long } * */ public Long <API key>() { return myTransactionToken; } /** * Sets the value of the myTransactionToken property. * * @param value * allowed object is * {@link Long } * */ public void <API key>(Long value) { this.myTransactionToken = value; } /** * Gets the value of the myVertexTypeName property. * * @return * possible object is * {@link String } * */ public String getMyVertexTypeName() { return myVertexTypeName; } /** * Sets the value of the myVertexTypeName property. * * @param value * allowed object is * {@link String } * */ public void setMyVertexTypeName(String value) { this.myVertexTypeName = value; } }
// This file is part of DOLFIN. // DOLFIN is free software: you can redistribute it and/or modify // (at your option) any later version. // DOLFIN is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // First added: 2010-02-10 // Last changed: 2013-04-26 #include <dolfin/log/dolfin_log.h> #include <dolfin/common/Timer.h> #include <dolfin/common/MPI.h> #include <dolfin/parameter/GlobalParameters.h> #include <dolfin/mesh/LocalMeshData.h> #include "ParMETIS.h" #include "GraphBuilder.h" #ifdef HAS_PARMETIS #include <parmetis.h> #endif using namespace dolfin; #ifdef HAS_PARMETIS namespace dolfin { // This class builds a ParMETIS dual graph class ParMETISDualGraph { public: // Constructor ParMETISDualGraph(MPI_Comm mpi_comm, const LocalMeshData& mesh_data); // Destructor ~ParMETISDualGraph(); // ParMETIS data std::vector<idx_t> elmdist; std::vector<idx_t> eptr; std::vector<idx_t> eind; idx_t numflag; idx_t* xadj; idx_t* adjncy; // Number of partitions (one for each process) idx_t nparts; // Strange weight arrays needed by ParMETIS idx_t ncon; std::vector<real_t> tpwgts; std::vector<real_t> ubvec; // Prepare remaining arguments for ParMETIS idx_t* elmwgt; idx_t wgtflag; idx_t edgecut; }; } void ParMETIS::compute_partition(const MPI_Comm mpi_comm, std::vector<std::size_t>& cell_partition, const LocalMeshData& mesh_data, std::string mode) { // Duplicate MPI communicator (ParMETIS does not take const // arguments, so duplicate communicator to be sure it isn't changed) MPI_Comm comm; MPI_Comm_dup(mpi_comm, &comm); // Build dual graph ParMETISDualGraph g(mpi_comm, mesh_data); dolfin_assert(g.eptr.size() - 1 == mesh_data.cell_vertices.size()); // Partition graph if (mode == "partition") partition(comm, cell_partition, g); else if (mode == "<API key>") <API key>(comm, cell_partition, g); else if (mode == "refine") refine(comm, cell_partition, g); else { dolfin_error("ParMETIS.cpp", "compute mesh partitioning using ParMETIS", "partition model %s is unknown. Must be \"partition\", \"adactive_partition\" or \"refine\"", mode.c_str()); } MPI_Comm_free(&comm); } void ParMETIS::partition(MPI_Comm mpi_comm, std::vector<std::size_t>& cell_partition, ParMETISDualGraph& g) { Timer timer1("PARALLEL 1b: Compute graph partition (calling ParMETIS)"); // Options for ParMETIS idx_t options[3]; options[0] = 1; options[1] = 0; options[2] = 15; // Check that data arrays are not empty dolfin_assert(!g.tpwgts.empty()); dolfin_assert(!g.ubvec.empty()); // Call ParMETIS to partition graph const std::size_t num_local_cells = g.eptr.size() - 1; std::vector<idx_t> part(num_local_cells); dolfin_assert(!part.empty()); int err = <API key>(g.elmdist.data(), g.xadj, g.adjncy, g.elmwgt, NULL, &g.wgtflag, &g.numflag, &g.ncon, &g.nparts, g.tpwgts.data(), g.ubvec.data(), options, &g.edgecut, part.data(), &mpi_comm); dolfin_assert(err == METIS_OK); // Copy cell partition data cell_partition = std::vector<std::size_t>(part.begin(), part.end()); } void ParMETIS::<API key>(MPI_Comm mpi_comm, std::vector<std::size_t>& cell_partition, ParMETISDualGraph& g) { Timer timer1("PARALLEL 1b: Compute graph partition (calling ParMETIS Adaptive Repartition)"); // Options for ParMETIS idx_t options[4]; options[0] = 1; options[1] = 0; options[2] = 15; options[3] = <API key>; // For repartition, <API key> seems to suppress all // migration if already balanced. Try <API key> for // better edge cut. // Check that data arrays are not empty dolfin_assert(!g.tpwgts.empty()); dolfin_assert(!g.ubvec.empty()); // Call ParMETIS to partition graph const double itr = parameters["<API key>"]; real_t _itr = itr; std::vector<idx_t> part(g.eptr.size() - 1); std::vector<idx_t> vsize(part.size(), 1); dolfin_assert(!part.empty()); int err = <API key>(g.elmdist.data(), g.xadj, g.adjncy, g.elmwgt, NULL, vsize.data(), &g.wgtflag, &g.numflag, &g.ncon, &g.nparts, g.tpwgts.data(), g.ubvec.data(), &_itr, options, &g.edgecut, part.data(), &mpi_comm); dolfin_assert(err == METIS_OK); // Copy cell partition data cell_partition = std::vector<std::size_t>(part.begin(), part.end()); } void ParMETIS::refine(MPI_Comm mpi_comm, std::vector<std::size_t>& cell_partition, ParMETISDualGraph& g) { Timer timer1("PARALLEL 1b: Compute graph partition (calling ParMETIS Refine)"); // Get some MPI data const std::size_t process_number = MPI::rank(mpi_comm); // Options for ParMETIS idx_t options[4]; options[0] = 1; options[1] = 0; options[2] = 15; //options[3] = <API key>; // For repartition, <API key> seems to suppress all // migration if already balanced. Try <API key> for // better edge cut. // Check that data arrays are not empty dolfin_assert(!g.tpwgts.empty()); dolfin_assert(!g.ubvec.empty()); // Partitioning array to be computed by ParMETIS. Prefill with // process_number. const std::size_t num_local_cells = g.eptr.size() - 1; std::vector<idx_t> part(num_local_cells, process_number); dolfin_assert(!part.empty()); // Call ParMETIS to partition graph int err = <API key>(g.elmdist.data(), g.xadj, g.adjncy, g.elmwgt, NULL, &g.wgtflag, &g.numflag, &g.ncon, &g.nparts, g.tpwgts.data(), g.ubvec.data(), options, &g.edgecut, part.data(), &mpi_comm); dolfin_assert(err == METIS_OK); // Copy cell partition data cell_partition = std::vector<std::size_t>(part.begin(), part.end()); } ParMETISDualGraph::ParMETISDualGraph(MPI_Comm mpi_comm, const LocalMeshData& mesh_data) { // Get number of processes and process number const std::size_t num_processes = MPI::size(mpi_comm); // Get dimensions of local mesh_data const std::size_t num_local_cells = mesh_data.cell_vertices.size(); const std::size_t num_cell_vertices = mesh_data.<API key>; // Check that number of local graph nodes (cells) is > 0 if (num_local_cells == 0) { dolfin_error("ParMETIS.cpp", "compute mesh partitioning using ParMETIS", "ParMETIS cannot be used if a process has no cells (graph nodes). Use SCOTCH to perform partitioning instead"); } // Communicate number of cells between all processors std::vector<std::size_t> num_cells; MPI::all_gather(mpi_comm, num_local_cells, num_cells); // Build elmdist array with cell offsets for all processors elmdist.assign(num_processes + 1, 0); for (std::size_t i = 1; i < num_processes + 1; ++i) elmdist[i] = elmdist[i - 1] + num_cells[i - 1]; eptr.resize(num_local_cells + 1); eind.assign(num_local_cells*num_cell_vertices, 0); for (std::size_t i = 0; i < num_local_cells; i++) { dolfin_assert(mesh_data.cell_vertices[i].size() == num_cell_vertices); eptr[i] = i*num_cell_vertices; for (std::size_t j = 0; j < num_cell_vertices; j++) eind[eptr[i] + j] = mesh_data.cell_vertices[i][j]; } eptr[num_local_cells] = num_local_cells*num_cell_vertices; dolfin_assert(!eptr.empty()); dolfin_assert(!eind.empty()); // Number of nodes shared for dual graph (partition along facets) idx_t ncommonnodes = num_cell_vertices - 1; numflag = 0; xadj = 0; adjncy = 0; dolfin_assert(!eptr.empty()); dolfin_assert(!eind.empty()); // Could use GraphBuilder::compute_dual_graph() instead int err = <API key>(elmdist.data(), eptr.data(), eind.data(), &numflag, &ncommonnodes, &xadj, &adjncy, &mpi_comm); dolfin_assert(err == METIS_OK); // Number of partitions (one for each process) nparts = num_processes; // Strange weight arrays needed by ParMETIS ncon = 1; tpwgts.assign(ncon*nparts, 1.0/static_cast<real_t>(nparts)); ubvec.assign(ncon, 1.05); // Prepare remaining arguments for ParMETIS elmwgt = NULL; wgtflag = 0; edgecut = 0; } ParMETISDualGraph::~ParMETISDualGraph() { // Free metis data structures METIS_Free(xadj); METIS_Free(adjncy); } #else void ParMETIS::compute_partition(const MPI_Comm mpi_comm, std::vector<std::size_t>& cell_partition, const LocalMeshData& data, std::string mode) { dolfin_error("ParMETIS.cpp", "compute mesh partitioning using ParMETIS", "DOLFIN has been configured without support for ParMETIS"); } #endif
<?php namespace Google\AdsApi\Dfp\v201802; /** * This file was generated from WSDL. DO NOT EDIT. */ class Dimension { const MONTH_AND_YEAR = 'MONTH_AND_YEAR'; const WEEK = 'WEEK'; const DATE = 'DATE'; const DAY = 'DAY'; const HOUR = 'HOUR'; const LINE_ITEM_ID = 'LINE_ITEM_ID'; const LINE_ITEM_NAME = 'LINE_ITEM_NAME'; const LINE_ITEM_TYPE = 'LINE_ITEM_TYPE'; const <API key> = '<API key>'; const ORDER_ID = 'ORDER_ID'; const ORDER_NAME = 'ORDER_NAME'; const <API key> = '<API key>'; const ADVERTISER_ID = 'ADVERTISER_ID'; const ADVERTISER_NAME = 'ADVERTISER_NAME'; const AD_NETWORK_ID = 'AD_NETWORK_ID'; const AD_NETWORK_NAME = 'AD_NETWORK_NAME'; const SALESPERSON_ID = 'SALESPERSON_ID'; const SALESPERSON_NAME = 'SALESPERSON_NAME'; const CREATIVE_ID = 'CREATIVE_ID'; const CREATIVE_NAME = 'CREATIVE_NAME'; const CREATIVE_TYPE = 'CREATIVE_TYPE'; const <API key> = '<API key>'; const CUSTOM_EVENT_ID = 'CUSTOM_EVENT_ID'; const CUSTOM_EVENT_NAME = 'CUSTOM_EVENT_NAME'; const CUSTOM_EVENT_TYPE = 'CUSTOM_EVENT_TYPE'; const CREATIVE_SIZE = 'CREATIVE_SIZE'; const AD_UNIT_ID = 'AD_UNIT_ID'; const AD_UNIT_NAME = 'AD_UNIT_NAME'; const PARENT_AD_UNIT_ID = 'PARENT_AD_UNIT_ID'; const PARENT_AD_UNIT_NAME = 'PARENT_AD_UNIT_NAME'; const PLACEMENT_ID = 'PLACEMENT_ID'; const PLACEMENT_NAME = 'PLACEMENT_NAME'; const PLACEMENT_STATUS = 'PLACEMENT_STATUS'; const TARGETING = 'TARGETING'; const DEVICE_CATEGORY_ID = 'DEVICE_CATEGORY_ID'; const <API key> = '<API key>'; const COUNTRY_CRITERIA_ID = 'COUNTRY_CRITERIA_ID'; const COUNTRY_NAME = 'COUNTRY_NAME'; const REGION_CRITERIA_ID = 'REGION_CRITERIA_ID'; const REGION_NAME = 'REGION_NAME'; const CITY_CRITERIA_ID = 'CITY_CRITERIA_ID'; const CITY_NAME = 'CITY_NAME'; const METRO_CRITERIA_ID = 'METRO_CRITERIA_ID'; const METRO_NAME = 'METRO_NAME'; const <API key> = '<API key>'; const POSTAL_CODE = 'POSTAL_CODE'; const <API key> = '<API key>'; const CUSTOM_CRITERIA = 'CUSTOM_CRITERIA'; const ACTIVITY_ID = 'ACTIVITY_ID'; const ACTIVITY_NAME = 'ACTIVITY_NAME'; const ACTIVITY_GROUP_ID = 'ACTIVITY_GROUP_ID'; const ACTIVITY_GROUP_NAME = 'ACTIVITY_GROUP_NAME'; const CONTENT_ID = 'CONTENT_ID'; const CONTENT_NAME = 'CONTENT_NAME'; const CONTENT_BUNDLE_ID = 'CONTENT_BUNDLE_ID'; const CONTENT_BUNDLE_NAME = 'CONTENT_BUNDLE_NAME'; const CONTENT_HIERARCHY = 'CONTENT_HIERARCHY'; const <API key> = '<API key>'; const POSITION_OF_POD = 'POSITION_OF_POD'; const POSITION_IN_POD = 'POSITION_IN_POD'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const GRP_DEMOGRAPHICS = 'GRP_DEMOGRAPHICS'; const AD_REQUEST_SIZE = 'AD_REQUEST_SIZE'; const <API key> = '<API key>'; const <API key> = '<API key>'; const BUYER_ID = 'BUYER_ID'; const BUYER_NAME = 'BUYER_NAME'; const IS_FIRST_LOOK_DEAL = 'IS_FIRST_LOOK_DEAL'; const MEDIATION_GROUP_ID = 'MEDIATION_GROUP_ID'; const <API key> = '<API key>'; const YIELD_GROUP_ID = 'YIELD_GROUP_ID'; const YIELD_GROUP_NAME = 'YIELD_GROUP_NAME'; const YIELD_PARTNER = 'YIELD_PARTNER'; const YIELD_PARTNER_TAG = 'YIELD_PARTNER_TAG'; const MEDIATION_NETWORK = 'MEDIATION_NETWORK'; const <API key> = '<API key>'; const MEDIATION_TYPE = 'MEDIATION_TYPE'; const NATIVE_TEMPLATE_ID = 'NATIVE_TEMPLATE_ID'; const <API key> = '<API key>'; const NATIVE_STYLE_ID = 'NATIVE_STYLE_ID'; const NATIVE_STYLE_NAME = 'NATIVE_STYLE_NAME'; const MOBILE_APP_NAME = 'MOBILE_APP_NAME'; const MOBILE_DEVICE_NAME = 'MOBILE_DEVICE_NAME'; const <API key> = '<API key>'; const REQUEST_TYPE = 'REQUEST_TYPE'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_UNIT_STATUS = 'AD_UNIT_STATUS'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const PROPOSAL_ID = 'PROPOSAL_ID'; const PROPOSAL_NAME = 'PROPOSAL_NAME'; const ALL_SALESPEOPLE_ID = 'ALL_SALESPEOPLE_ID'; const <API key> = '<API key>'; const SALES_TEAM_ID = 'SALES_TEAM_ID'; const SALES_TEAM_NAME = 'SALES_TEAM_NAME'; const PROPOSAL_AGENCY_ID = 'PROPOSAL_AGENCY_ID'; const <API key> = '<API key>'; const PRODUCT_ID = 'PRODUCT_ID'; const PRODUCT_NAME = 'PRODUCT_NAME'; const PRODUCT_TEMPLATE_ID = 'PRODUCT_TEMPLATE_ID'; const <API key> = '<API key>'; const RATE_CARD_ID = 'RATE_CARD_ID'; const RATE_CARD_NAME = 'RATE_CARD_NAME'; const WORKFLOW_ID = 'WORKFLOW_ID'; const WORKFLOW_NAME = 'WORKFLOW_NAME'; const PACKAGE_ID = 'PACKAGE_ID'; const PACKAGE_NAME = 'PACKAGE_NAME'; const PRODUCT_PACKAGE_ID = 'PRODUCT_PACKAGE_ID'; const <API key> = '<API key>'; const AUDIENCE_SEGMENT_ID = 'AUDIENCE_SEGMENT_ID'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_EXCHANGE_URL = 'AD_EXCHANGE_URL'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_EXCHANGE_AD_TYPE = 'AD_EXCHANGE_AD_TYPE'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_EXCHANGE_AGENCY = 'AD_EXCHANGE_AGENCY'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_EXCHANGE_DATE = 'AD_EXCHANGE_DATE'; const AD_EXCHANGE_DEAL_ID = 'AD_EXCHANGE_DEAL_ID'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_EXCHANGE_MONTH = 'AD_EXCHANGE_MONTH'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_EXCHANGE_URL_ID = 'AD_EXCHANGE_URL_ID'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const AD_EXCHANGE_WEEK = 'AD_EXCHANGE_WEEK'; const <API key> = '<API key>'; const <API key> = '<API key>'; const NIELSEN_SEGMENT = 'NIELSEN_SEGMENT'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const <API key> = '<API key>'; const REQUESTED_AD_SIZES = 'REQUESTED_AD_SIZES'; const <API key> = '<API key>'; const DEMAND_CHANNEL_ID = 'DEMAND_CHANNEL_ID'; const DEMAND_CHANNEL_NAME = 'DEMAND_CHANNEL_NAME'; }
<?php namespace Clearbooks\Labs\Db\Service; use Clearbooks\Labs\Db\Table\Toggle as ToggleTable; use Clearbooks\Labs\Db\Table\UserPolicy as UserPolicyTable; use Clearbooks\Labs\Db\Table\GroupPolicy as GroupPolicyTable; use Clearbooks\Labs\Db\Table\SegmentPolicy as SegmentPolicyTable; use Clearbooks\Labs\Db\Entity\Toggle; use Doctrine\DBAL\Connection; class ToggleStorage implements <API key> { const IDENTITY_TYPE_USER = "user"; const IDENTITY_TYPE_GROUP = "group"; const <API key> = "segment"; /** * @var Connection */ private $connection; /** * @var ToggleTable */ private $toggleTable; /** * @var UserPolicyTable */ private $userPolicyTable; /** * @var GroupPolicyTable */ private $groupPolicyTable; /** * @var SegmentPolicyTable */ private $segmentPolicyTable; /** * @param Connection $connection * @param ToggleTable $toggleTable * @param UserPolicyTable $userPolicyTable * @param GroupPolicyTable $groupPolicyTable * @param SegmentPolicyTable $segmentPolicyTable */ public function __construct( Connection $connection, ToggleTable $toggleTable, UserPolicyTable $userPolicyTable, GroupPolicyTable $groupPolicyTable, SegmentPolicyTable $segmentPolicyTable ) { $this->connection = $connection; $this->toggleTable = $toggleTable; $this->userPolicyTable = $userPolicyTable; $this->groupPolicyTable = $groupPolicyTable; $this->segmentPolicyTable = $segmentPolicyTable; } /** * @param int $toggleId * @return Toggle|null */ public function getToggleById( $toggleId ) { return $this-><API key>( "id", $toggleId ); } /** * @param string $toggleName * @return Toggle|null */ public function getToggleByName( $toggleName ) { return $this-><API key>( "name", $toggleName ); } /** * @param string $columnName * @param mixed $columnValue * @return Toggle|null */ private function <API key>( $columnName, $columnValue ) { $queryBuilder = $this->connection->createQueryBuilder(); $queryBuilder->select( "*" )->from( (string)$this->toggleTable )->where( $columnName . " = ?" ); $queryBuilder->setParameter( 0, $columnValue ); $toggleData = $queryBuilder->execute()->fetch(); return !empty( $toggleData ) ? new Toggle( $toggleData ) : null; } /** * @param Toggle $toggle * @return int */ public function insertToggle( Toggle $toggle ) { $affectedRows = $this->connection->insert( $this->toggleTable, $toggle->toArray() ); return $affectedRows > 0 ? $this->connection->lastInsertId() : 0; } /** * @param int $toggleId * @param string $userId * @param bool|null $policy */ public function setUserPolicy( $toggleId, $userId, $policy ) { $this->setTogglePolicy( $toggleId, $userId, $policy, self::IDENTITY_TYPE_USER ); } /** * @param int $toggleId * @param string $groupId * @param bool|null $policy */ public function setGroupPolicy( $toggleId, $groupId, $policy ) { $this->setTogglePolicy( $toggleId, $groupId, $policy, self::IDENTITY_TYPE_GROUP ); } /** * @param int $toggleId * @param string $groupId * @param bool|null $policy */ public function setSegmentPolicy( $toggleId, $groupId, $policy ) { $this->setTogglePolicy( $toggleId, $groupId, $policy, self::<API key> ); } /** * @param int $toggleId * @param string $identityId * @param bool|null $policy * @param string $typeOfIdentity * @throws \Doctrine\DBAL\Exception\<API key> */ public function setTogglePolicy( $toggleId, $identityId, $policy, $typeOfIdentity ) { $table = $this-><API key>( $typeOfIdentity ); $identityField = $this-><API key>( $typeOfIdentity ); if ( $policy === null ) { $this->removeTogglePolicy( $table, $identityField, $identityId, $toggleId ); return; } $this-><API key>( $toggleId, $identityId, $policy, $typeOfIdentity, $table, $identityField ); } /** * @param string $table * @param string $identityField * @param string $identityId * @param int $toggleId * @throws \Doctrine\DBAL\Exception\<API key> */ private function removeTogglePolicy( $table, $identityField, $identityId, $toggleId ) { $this->connection->delete( $table, [ $identityField => $identityId, "toggle_id" => $toggleId ] ); } /** * @param int $toggleId * @param string $identityId * @param bool $policy * @param string $typeOfIdentity * @param string $table * @param string $identityField */ private function <API key>( $toggleId, $identityId, $policy, $typeOfIdentity, $table, $identityField ) { $currentPolicy = $this-><API key>( $toggleId, $identityId, $typeOfIdentity ); if ( $currentPolicy === null ) { $this->connection->insert( $table, [ $identityField => $identityId, "toggle_id" => $toggleId, "active" => $policy ? 1 : 0 ] ); } $this->connection->update( $table, [ "active" => $policy ? 1 : 0 ], [ $identityField => $identityId, "toggle_id" => $toggleId ] ); } /** * @param string $toggleName * @param string $userId * @return bool|null */ public function <API key>( $toggleName, $userId ) { return $this-><API key>( $toggleName, $userId, self::IDENTITY_TYPE_USER ); } /** * @param string $toggleName * @param string $groupId * @return bool|null */ public function <API key>( $toggleName, $groupId ) { return $this-><API key>( $toggleName, $groupId, self::IDENTITY_TYPE_GROUP ); } /** * @param string $toggleName * @param string $segmentId * @return bool|null */ public function <API key>( $toggleName, $segmentId ) { return $this-><API key>( $toggleName, $segmentId, self::<API key> ); } /** * @param string $toggleName * @param string $identityId * @param string $typeOfIdentity * @return bool|null */ public function <API key>( $toggleName, $identityId, $typeOfIdentity ) { $toggle = $this->getToggleByName( $toggleName ); if ( $toggle == null ) { return null; } return $this-><API key>( $toggle, $identityId, $typeOfIdentity ); } /** * @param int $toggleId * @param string $identityId * @param string $typeOfIdentity * @return bool|null */ public function <API key>( $toggleId, $identityId, $typeOfIdentity ) { $toggle = $this->getToggleById( $toggleId ); if ( $toggle == null ) { return null; } return $this-><API key>( $toggle, $identityId, $typeOfIdentity ); } private function <API key>( Toggle $toggle, $identityId, $typeOfIdentity ) { $table = $this-><API key>( $typeOfIdentity ); $identityField = $this-><API key>( $typeOfIdentity ); $queryBuilder = $this->connection->createQueryBuilder(); $queryBuilder->select( "active" )->from( $table ) ->where( "{$identityField} = ? AND toggle_id = ?" ); $queryBuilder->setParameter( 0, $identityId ); $queryBuilder->setParameter( 1, $toggle->getId() ); $active = $queryBuilder->executeQuery()->fetchOne(); if ( $active === false ) { return null; } return (int)$active !== 0; } /** * @param string $typeOfIdentity * @return string */ private function <API key>( $typeOfIdentity ) { switch ( $typeOfIdentity ) { case self::IDENTITY_TYPE_GROUP: return (string)$this->groupPolicyTable; case self::<API key>: return (string)$this->segmentPolicyTable; default: return (string)$this->userPolicyTable; } } /** * @param string $typeOfIdentity * @return string */ private function <API key>( $typeOfIdentity ) { switch ( $typeOfIdentity ) { case self::IDENTITY_TYPE_GROUP: return "group_id"; case self::<API key>: return "segment_id"; default: return "user_id"; } } }
using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.IO; using System.Threading; using System.Security.Cryptography; using System.Xml; using bedrock.util; using jabber.protocol; using jabber.protocol.stream; using jabber.connection.sasl; using System.Security.Cryptography.X509Certificates; namespace jabber.connection { <summary> Informs the client about events that happen on an ElementStream. </summary> public delegate void StreamHandler(Object sender, ElementStream stream); <summary> Manages option names. These must be well-formed XML element names. </summary> [SVN(@"$Id: XmppStream.cs 724 2008-08-06 18:09:25Z hildjj $")] public abstract class Options { public const string ANONYMOUS = "anonymous"; <summary> Contains the default namespace for this connection. </summary> public const string NAMESPACE = "namespace"; <summary> Contains the network hostname or IP address of the XMPP server to connect to. </summary> public const string NETWORK_HOST = "network_host"; <summary> Contains the identity of the item that the client is connecting to. For components, the component ID. </summary> public const string TO = "to"; <summary> Contains the server identity that is expected on the X.509 certificate from the XMPP server. </summary> public const string SERVER_ID = "tls.cn"; <summary> Determines the keep-alive interval in seconds. </summary> public const string KEEP_ALIVE = "keep_alive"; <summary> Don't start keep-alives until we're fully authenticated. This is what the SocketStanzaStream actually checks. </summary> public const string CURRENT_KEEP_ALIVE = "current_keep_alive"; <summary> Contains the port number to connect to or to listen on. </summary> public const string PORT = "port"; <summary> Uses SSL on connection if set to true. </summary> public const string SSL = "ssl"; <summary> Uses Start-TLS on connection if set to true and the server supports it. </summary> public const string AUTO_TLS = "tls.auto"; <summary> Starts the XMPP stream compression (XEP-138) on connection if set to true. </summary> public const string AUTO_COMPRESS = "compress.auto"; <summary> Allows plaintext authentication for connecting to the XMPP server. </summary> public const string PLAINTEXT = "plaintext"; <summary> Attempts a SASL connection if set to true and the feature is available from the XMPP server. If the server doesn't support SASL, the connection will move to a fallback mechanism. </summary> public const string SASL = "sasl"; <summary> Requires SASL authentication on this connection if set to true. There is no fallback mechanism. If the server doesn't support SASL, the connection attempt will fail. </summary> public const string REQUIRE_SASL = "sasl.require"; <summary> Contains the list of SASL Mechanisms such as Digest-MD5, Plain and so on. </summary> public const string SASL_MECHANISMS = "sasl.mechanisms"; <summary> Contains the username to connect as. </summary> public const string USER = "user"; <summary> Contains the password for the user, or secret for the component. </summary> public const string PASSWORD = "password"; <summary> Contains the connecting resource which is used to identify a unique connection. </summary> public const string RESOURCE = "resource"; <summary> Contains the presence default priority for this connection. </summary> public const string PRIORITY = "priority"; <summary> Contains the DNS Service/Protocol to prepend to domain. Example: _xmpp-client._tcp. </summary> public const string SRV_PREFIX = "srv.prefix"; <summary> Allows auto-login to be used for the connection to the XMPP server if set to true. </summary> public const string AUTO_LOGIN = "auto.login"; <summary> This pass through the login process, can we login? This option is set/reset by the framework. </summary> public const string AUTO_LOGIN_THISPASS = "auto.login.thispass"; <summary> Retrieves the roster items from the XMPP server on connection if set to true. </summary> public const string AUTO_ROSTER = "auto.roster"; <summary> Sends back 501/<API key> to the XMPP server if there are IQs that have not been handled if set to true. </summary> public const string AUTO_IQ_ERRORS = "auto.iq_errors"; <summary> Sends the presence on connection if set to true. </summary> public const string AUTO_PRESENCE = "auto.presence"; <summary> Contains the certificate for our side of the SSL/TLS negotiation. </summary> public const string LOCAL_CERTIFICATE = "certificate.local"; <summary> Contains the remote certificate that the XMPP server sent to the client. </summary> public const string REMOTE_CERTIFICATE = "certificate.remote"; <summary> Uses x509 selection dialog box when a certificate is requested if set to true. </summary> public const string CERTIFICATE_GUI = "certificate.gui"; <summary> Contains the number of seconds to wait before attempting a reconnect. </summary> public const string RECONNECT_TIMEOUT = "reconnect_timeout"; <summary> Determines the connection type (sockets, HTTP polling, or HTTP binding). </summary> public const string CONNECTION_TYPE = "connection"; <summary> Contains the URL to poll on, or bind to. </summary> public const string POLL_URL = "poll.url"; <summary> Connects to the XMPP server or listen for connections. </summary> public const string COMPONENT_DIRECTION = "component.dir"; <summary> Contains the logical JID associated with this connection. </summary> public const string JID = "jid"; <summary> Contains the proxy type, such as none, SOCKS5 and so on. </summary> public const string PROXY_TYPE = "proxy.type"; <summary> Contains the hostname or IP address of the proxy. </summary> public const string PROXY_HOST = "proxy.host"; <summary> Contains the port number for the proxy. </summary> public const string PROXY_PORT = "proxy.port"; <summary> Contains the username for the proxy server. </summary> public const string PROXY_USER = "proxy.user"; <summary> Contains the password for the proxy server. </summary> public const string PROXY_PW = "proxy.password"; <summary> Override the from address, in a component/service connection. </summary> public const string OVERRIDE_FROM = "override_from"; } <summary> Manages the XMPP stream of the connection. </summary> [SVN(@"$Id: XmppStream.cs 724 2008-08-06 18:09:25Z hildjj $")] abstract public class XmppStream : System.ComponentModel.Component, <API key> { private static readonly object[][] DEFAULTS = new object[][] { new object[] {Options.TO, "jabber.com"}, new object[] {Options.KEEP_ALIVE, 30000}, new object[] {Options.CURRENT_KEEP_ALIVE, -1}, new object[] {Options.PORT, 5222}, new object[] {Options.RECONNECT_TIMEOUT, 30000}, new object[] {Options.PROXY_PORT, 1080}, new object[] {Options.SSL, false}, new object[] {Options.SASL, true}, new object[] {Options.REQUIRE_SASL, false}, new object[] {Options.PLAINTEXT, false}, new object[] {Options.AUTO_TLS, true}, new object[] {Options.AUTO_COMPRESS, true}, #if __MonoCS__ new object[] {Options.CERTIFICATE_GUI, false}, #else new object[] {Options.CERTIFICATE_GUI, true}, #endif new object[] {Options.PROXY_TYPE, ProxyType.None}, new object[] {Options.CONNECTION_TYPE, ConnectionType.Socket}, }; <summary> Contains the character encoding for the XMPP stream. Currently, it is set to UTF-8. </summary> protected static readonly System.Text.Encoding ENC = System.Text.Encoding.UTF8; private StanzaStream m_stanzas = null; private IQTracker m_tracker = null; private XmlDocument m_doc = new XmlDocument(); private BaseState m_state = ClosedState.Instance; private IDictionary m_properties = new Hashtable(); private string m_streamID = null; private object m_stateLock = new object(); private ArrayList m_callbacks = new ArrayList(); private Timer m_reconnectTimer = null; private bool m_reconnect = false; private bool m_sslOn = false; private bool m_compressionOn = false; private XmlNamespaceManager m_ns; private ISynchronizeInvoke m_invoker = null; // XMPP v1 stuff private string m_serverVersion = null; private SASLProcessor m_saslProc = null; private Features m_features = null; // the last features tag received. <summary> Required designer variable. </summary> #pragma warning disable 0414 private System.ComponentModel.Container components = new System.ComponentModel.Container(); #pragma warning restore 0414 <summary> Creates a new XMPP stream and associates it with the parent control. </summary> <param name="container">Parent control.</param> public XmppStream(System.ComponentModel.IContainer container) : this() { container.Add(this); } <summary> Sets defaults in bulk. </summary> <param name="defaults">Array of objects to replace to defaults with.</param> protected void SetDefaults(object[][] defaults) { foreach (object[] def in defaults) { this[(string)def[0]] = def[1]; } } <summary> Creates a new SocketElementStream. </summary> public XmppStream() { m_ns = new XmlNamespaceManager(m_doc.NameTable); m_tracker = new IQTracker(this); SetDefaults(DEFAULTS); } <summary> Sets or retrieves a connection property. You have to know the type of the property based on the name. For example, PORT is an integer. </summary> <param name="prop">The property to get or set.</param> <returns></returns> public object this[string prop] { get { if (!m_properties.Contains(prop)) return null; return m_properties[prop]; } set { m_properties[prop] = value; if (PropertyChanged != null) { PropertyChanged(this, new <API key>(prop)); } } } <summary> Informs the client that a property changed on the instance. </summary> public event <API key> PropertyChanged; /* <summary> Create a SocketElementStream out of an accepted socket. </summary> <param name="aso"></param> public XmppStream(BaseSocket aso) { m_accept = m_sock = null; if (aso is AsyncSocket) { m_watcher = ((AsyncSocket)aso).SocketWatcher; } m_ns = new XmlNamespaceManager(m_doc.NameTable); m_timer = new Timer(new TimerCallback(DoKeepAlive), null, Timeout.Infinite, Timeout.Infinite); InitializeStream(); m_state = jabber.connection.AcceptingState.Instance; } <summary> Create a SocketElementStream with an existing SocketWatcher, so that you can do lots of concurrent connections. </summary> <param name="watcher"></param> public XmppStream(SocketWatcher watcher) { m_watcher = watcher; m_ns = new XmlNamespaceManager(m_doc.NameTable); m_timer = new Timer(new TimerCallback(DoKeepAlive), null, Timeout.Infinite, Timeout.Infinite); } */ <summary> Informs the client when text has been written to the XMPP server. Use for debugging only. Will NOT be complete nodes at a time. </summary> [Category("Debug")] public event bedrock.TextHandler OnWriteText; <summary> Informs the client that text was read from the server. Use for debugging only. Will NOT be complete nodes at a time. </summary> [Category("Debug")] public event bedrock.TextHandler OnReadText; <summary> Informs the client that a new stream has been inialized. You can add your packet factories to the new stream. NOTE: You may NOT make calls to the GUI in this callback, unless you call Invoke. Make sure you add your packet factories before calling Invoke, however. </summary> [Category("Stream")] public event StreamHandler OnStreamInit; <summary> Informs the client that an error occurred when processing. The connection has been closed. </summary> [Category("Stream")] public event bedrock.ExceptionHandler OnError; <summary> Notifies the client about every jabber packet. This is a union of the OnPresence, OnMessage, and OnIQ methods. Use this *or* the other 3 methods, but not both, as a matter of style. </summary> [Category("Stream")] public event ProtocolHandler OnProtocol; <summary> Notifies the client that the stream header, as a packet, has been received. Can be called multiple times for a single session, with XMPP. </summary> [Category("Stream")] public event ProtocolHandler OnStreamHeader; <summary> Notifies the client that the SASL handshake has started. </summary> protected event <API key> OnSASLStart; <summary> Gets notified of the end of a SASL handshake. </summary> protected event FeaturesHandler OnSASLEnd; <summary> Gets notified when SASL login fails. </summary> protected event ProtocolHandler OnSASLError; <summary> Informs the client that it received a stream:error packet. </summary> [Category("Stream")] [Description("We received stream:error packet.")] public event ProtocolHandler OnStreamError; <summary> Informs the client that the connection is complete and the user is authenticated. </summary> [Category("Stream")] public event bedrock.ObjectHandler OnAuthenticate; <summary> Informs the client that the connection is connected, but no stream:stream has been sent yet. </summary> [Category("Stream")] public event StanzaStreamHandler OnConnect; <summary> Informs the client that the connection is disconnected. </summary> [Category("Stream")] public event bedrock.ObjectHandler OnDisconnect; <summary> An invalid cert was received from the other side. Set this event and return true to use the cert anyway. If the event is not set, an ugly user interface will be displayed. </summary> [Category("Stream")] public event System.Net.Security.<API key> <API key>; public bool UseAnonymous { get { return (bool)this[Options.ANONYMOUS]; } set { this[Options.ANONYMOUS] = value; } } <summary> Gets the tracker for sending IQ packets. </summary> [Browsable(false)] public IIQTracker Tracker { get { return m_tracker; } } <summary> Gets or sets the name of the XMPP server to connect to. </summary> [Description("Gets or sets the name of the XMPP server to connect to.")] [DefaultValue("jabber.com")] [Category("Jabber")] public virtual string Server { get { return this[Options.TO] as string; } set { this[Options.TO] = value; } } <summary> Gets or sets the network host address to use on the "to" attribute of the stream:stream. You can put the network hostname or IP address of the XMPP server to connect to. If none is specified, the Server will be used. Eventually, when SRV is supported, this will be deprecated. </summary> [Description("")] [DefaultValue(null)] [Category("Jabber")] public string NetworkHost { get { return this[Options.NETWORK_HOST] as string; } set { this[Options.NETWORK_HOST] = value; } } <summary> Specifies the TCP port to connect to. </summary> [Description("Specifies the TCP port to connect to.")] [DefaultValue(5222)] [Category("Jabber")] public int Port { get { return (int)this[Options.PORT]; } set { this[Options.PORT] = value; } } <summary> Specifies whether plaintext authentication is used for connecting to the XMPP server. </summary> [Description("Allow plaintext authentication?")] [DefaultValue(false)] [Category("Jabber")] public bool PlaintextAuth { get { return (bool)this[Options.PLAINTEXT]; } set { this[Options.PLAINTEXT] = value; } } <summary> Determines whether or not the current connection is secured with SSL/TLS. </summary> [Browsable(false)] public bool SSLon { get { return m_sslOn; } } <summary> Gets the JID from the connection. </summary> [Browsable(false)] public JID JID { // Make sure to set this option in subclasses. get { object j = this[Options.JID]; if (j == null) return null; if (j is JID) return (JID)j; if (j is string) return new JID((string)j); Debug.Assert(false, "Unknown JID type", j.GetType().ToString()); return null; } } <summary> Determines whether or not the current connection uses XMPP stream compression (XEP-138). </summary> [Browsable(false)] public bool CompressionOn { get { return m_compressionOn; } } <summary> Determines whether SSL3/TLS1 authentication is used when a user connects to the XMPP server. </summary> [Description("Do SSL3/TLS1 on startup.")] [DefaultValue(false)] [Category("Jabber")] public bool SSL { get { return (bool)this[Options.SSL]; } set { this[Options.SSL] = value; } } <summary> Allows Start-TLS on connection if the server supports it and if set to true. </summary> [Browsable(false)] public bool AutoStartTLS { get { return (bool)this[Options.AUTO_TLS]; } set { this[Options.AUTO_TLS] = value; } } <summary> Allows start compression on connection if the server supports it and is set to true. </summary> [Browsable(false)] public bool <API key> { get { return (bool)this[Options.AUTO_COMPRESS]; } set { this[Options.AUTO_COMPRESS] = value; } } <summary> Gets or sets the certificate to be used for the local side of sockets when SSL is enabled. </summary> [Browsable(false)] public X509Certificate LocalCertificate { get { return this[Options.LOCAL_CERTIFICATE] as X509Certificate; } set { this[Options.LOCAL_CERTIFICATE] = value; } } <summary> Sets the certificate to be used for accept sockets. To generate a test .pfx file using OpenSSL, add this to openssl.conf: <blockquote> [ serverex ] extendedKeyUsage=1.3.6.1.5.5.7.3.1 </blockquote> and run the following commands: <blockquote> openssl req -new -x509 -newkey rsa:1024 -keyout privkey.pem -out key.pem -extensions serverex openssl pkcs12 -export -in key.pem -inkey privkey.pem -name localhost -out localhost.pfx </blockquote> If you leave the certificate null, and you are doing Accept, the SSL class will try to find a default server certificate on your box. </summary> <param name="filename">A .pfx or .cer file.</param> <param name="password">The password, if this is a .pfx file, null if .cer file.</param> public void SetCertificateFile(string filename, string password) { this[Options.LOCAL_CERTIFICATE] = new X509Certificate2(filename, password); } <summary> Calls Invoke() for all callbacks on this control. </summary> [Description("Invoke all callbacks on this control")] [DefaultValue(null)] [Category("Jabber")] public ISynchronizeInvoke InvokeControl { get { // If we are running in the designer, let's try to get // an invoke control from the environment. VB // programmers can't seem to follow directions. if ((this.m_invoker == null) && DesignMode) { IDesignerHost host = (IDesignerHost)base.GetService(typeof(IDesignerHost)); if (host != null) { object root = host.RootComponent; if ((root != null) && (root is ISynchronizeInvoke)) { m_invoker = (ISynchronizeInvoke)root; // TODO: fire some sort of propertyChanged event, // so that old code gets cleaned up correctly. } } } return m_invoker; } set { m_invoker = value; } } <summary> Gets or sets the keep-alive interval in seconds. </summary> [Description("Gets or sets the keep-alive interval in seconds")] [Category("Jabber")] [DefaultValue(20f)] public float KeepAlive { get { return ((int)this[Options.KEEP_ALIVE]) / 1000f; } set { this[Options.KEEP_ALIVE] = (int)(value * 1000f); } } <summary> Gets or sets the number of seconds before automatically reconnecting if the connection drops. -1 to disable, 0 for immediate. </summary> [Description("Automatically reconnect a connection.")] [DefaultValue(30)] [Category("Automation")] public float AutoReconnect { get { return ((int)this[Options.RECONNECT_TIMEOUT]) / 1000f; } set { this[Options.RECONNECT_TIMEOUT] = (int)(value * 1000f); } } <summary> Gets or sets the proxy type, such as none, SOCKS5 and so on. </summary> [Description("Gets or sets the proxy type, such as none, SOCKS5 and so on.")] [DefaultValue(ProxyType.None)] [Category("Proxy")] public ProxyType Proxy { get { return (ProxyType)this[Options.PROXY_TYPE]; } set { this[Options.PROXY_TYPE] = value; } } <summary> Gets or sets the connection type, such as Socket, HTTP polling and so on. </summary> [Description("Gets or sets the connection type, such as Socket, HTTP polling and so on.")] [DefaultValue(ConnectionType.Socket)] [Category("Proxy")] public ConnectionType Connection { get { return (ConnectionType)this[Options.CONNECTION_TYPE]; } set { this[Options.CONNECTION_TYPE] = value; } } <summary> Gets or sets the hostname running the proxy. </summary> [Description("Gets or sets the hostname running the proxy.")] [DefaultValue(null)] [Category("Proxy")] public string ProxyHost { get { return this[Options.PROXY_HOST] as string; } set { this[Options.PROXY_HOST] = value; } } <summary> Gets or sets the port number of the proxy host. </summary> [Description("Gets or sets the port number of the proxy host.")] [DefaultValue(1080)] [Category("Proxy")] public int ProxyPort { get { return (int)this[Options.PROXY_PORT]; } set { this[Options.PROXY_PORT] = value; } } <summary> Gets or sets the authentication username for the SOCKS5 proxy. </summary> [Description("Gets or sets the authentication username for the SOCKS5 proxy.")] [DefaultValue(null)] [Category("Proxy")] public string ProxyUsername { get { return this[Options.PROXY_USER] as string; } set { this[Options.PROXY_USER] = value; } } <summary> Gets or sets the authentication password for the SOCKS5 proxy. </summary> [Description("the auth password for the socks5 proxy")] [DefaultValue(null)] [Category("Proxy")] public string ProxyPassword { get { return this[Options.PROXY_PW] as string; } set { this[Options.PROXY_PW] = value; } } <summary> Gets or sets the ID attribute from the stream:stream element sent by the XMPP server. </summary> [Browsable(false)] [DefaultValue(null)] public string StreamID { get { return m_streamID; } set { m_streamID = value; } } <summary> Retrieves the outbound document. </summary> [Browsable(false)] public XmlDocument Document { get { return m_doc; } } <summary> Gets or sets the current state of the connection. Lock on StateLock before accessing. </summary> [Browsable(false)] protected virtual BaseState State { get { return m_state; } set { m_state = value; // Debug.WriteLine("New state: " + m_state.ToString()); } } <summary> Gets the lock for the state information. </summary> [Browsable(false)] protected object StateLock { get { return m_stateLock; } } <summary> Gets or sets the state to authenticated. Locks on StateLock </summary> [Browsable(false)] [DefaultValue(false)] public virtual bool IsAuthenticated { get { lock (StateLock) { return (State == RunningState.Instance); } } set { bool close = false; lock (StateLock) { if (value) { State = RunningState.Instance; } else close = true; } if (close) Close(); if (value && (OnAuthenticate != null)) { if (InvokeRequired) CheckedInvoke(OnAuthenticate, new object[] { this }); else OnAuthenticate(this); } this[Options.CURRENT_KEEP_ALIVE] = this[Options.KEEP_ALIVE]; } } <summary> Returns the namespace for this connection. </summary> [Browsable(false)] protected abstract string NS { get; } <summary> Determines whether or not SASL is required for connecting to the XMPP server. </summary> [Description("Determines if SASL is required for connecting to the XMPP server.")] [DefaultValue(false)] public bool RequiresSASL { get { return (bool)this[Options.REQUIRE_SASL]; } set { this[Options.REQUIRE_SASL] = value; } } <summary> Gets the version number of the XMPP server. </summary> [Description("Gets the version number of the XMPP server.")] [DefaultValue(null)] public string ServerVersion { get { return m_serverVersion; } } <summary> Writes just the start tag of the given XML element. Typically only used for &lt;stream:stream&gt;. </summary> <param name="elem">&lt;stream:stream%gt; XML element.</param> public void WriteStartTag(jabber.protocol.stream.Stream elem) { m_stanzas.WriteStartTag(elem); } <summary> Sends the given packet to the server. </summary> <param name="elem">The XML element to send.</param> public virtual void Write(XmlElement elem) { m_stanzas.Write(elem); } <summary> Sends a raw string. </summary> <param name="str">The string to send.</param> public void Write(string str) { m_stanzas.Write(str); } <summary> Starts connecting to the XMPP server. This is done asyncronously. </summary> public virtual void Connect() { this[Options.CURRENT_KEEP_ALIVE] = -1; m_stanzas = StanzaStream.Create(this.Connection, this); lock (StateLock) { State = ConnectingState.Instance; m_reconnect = ((int)this[Options.RECONNECT_TIMEOUT] >= 0); } m_stanzas.Connect(); } <summary> Listens for connections from the XMPP server and is used for components only. </summary> protected virtual void Accept() { if ((m_stanzas == null) || (!m_stanzas.Acceptable)) m_stanzas = StanzaStream.Create(this.Connection, this); lock (StateLock) { this.State = AcceptingState.Instance; m_reconnect = ((int)this[Options.RECONNECT_TIMEOUT] >= 0); } m_stanzas.Accept(); } <summary> If autoReconnect is on, start the timer for reconnect now. </summary> private void TryReconnect() { // close was not requested, or autoreconnect turned on. if (m_reconnect) { if (m_reconnectTimer != null) m_reconnectTimer.Dispose(); m_reconnectTimer = new System.Threading.Timer( new System.Threading.TimerCallback(Reconnect), null, (int)this[Options.RECONNECT_TIMEOUT], System.Threading.Timeout.Infinite); } } <summary> Closes down the connection with the XMPP server with a clean shutdown. </summary> public virtual void Close() { Close(true); } <summary> Closes down the connection. </summary> <param name="clean">True for graceful shutdown</param> public virtual void Close(bool clean) { bool doClose = false; bool doStream = false; lock (StateLock) { // if close is called, never try to reconnect. m_reconnect = false; if ((State == RunningState.Instance) && (clean)) { doStream = true; } if (m_state != ClosedState.Instance) { State = ClosingState.Instance; doClose = true; } } if ((m_stanzas != null) && m_stanzas.Connected && doClose) { m_stanzas.Close(doStream); } else { Debug.WriteLine("Cannot close a socket before it is open"); //FireOnError(new <API key>("Cannot close a socket before it is open")); } } <summary> Invokes the given method on the Invoker, and does some exception handling. </summary> <param name="method">Method to call on the invoker thread.</param> <param name="args">Arguments to pass to the method.</param> protected void CheckedInvoke(MulticastDelegate method, object[] args) { try { Debug.Assert(m_invoker != null, "Check for this.InvokeControl == null before calling CheckedInvoke"); Debug.Assert(m_invoker.InvokeRequired, "Check for InvokeRequired before calling CheckedInvoke"); m_invoker.BeginInvoke(method, args); } catch (System.Reflection.<API key> e) { Debug.WriteLine("Exception passed along by XmppStream: " + e.ToString()); throw e.InnerException; } catch (Exception e) { Debug.WriteLine("Exception in XmppStream: " + e.ToString()); throw; } } <summary> Determines whether or not a callback needs to be on the GUI thread. </summary> <returns> True if the invoke control is set and the current thread is not the GUI thread. </returns> protected bool InvokeRequired { get { if (m_invoker == null) return false; return m_invoker.InvokeRequired; } } <summary> Informs the client that the first tag of the XML document has been received. </summary> <param name="sender">Caller of this function.</param> <param name="elem">The XML element that was received.</param> protected virtual void OnDocumentStart(object sender, System.Xml.XmlElement elem) { bool hack = false; if (elem is jabber.protocol.stream.Stream) { jabber.protocol.stream.Stream str = elem as jabber.protocol.stream.Stream; m_streamID = str.ID; m_serverVersion = str.Version; // See XMPP-core section 4.4.1. We'll accept 1.x if (m_serverVersion.StartsWith("1.")) { lock (m_stateLock) { if (State == SASLState.Instance) // already authed. last stream restart. State = SASLAuthedState.Instance; else State = jabber.connection.ServerFeaturesState.Instance; } } else { lock (m_stateLock) { State = NonSASLAuthState.Instance; } hack = true; } if (OnStreamHeader != null) { if (InvokeRequired) CheckedInvoke(OnStreamHeader, new object[] { this, elem }); else OnStreamHeader(this, elem); } CheckAll(elem); if (hack && (OnSASLStart != null)) { OnSASLStart(this, null); // Hack. Old-style auth for jabberclient. } } } <summary> Handle the last set of stream:features we have received, based on the current state. </summary> protected virtual void ProcessFeatures() { // don't do starttls if we're already on an SSL socket. // bad server setup, but no skin off our teeth, we're already // SSL'd. Also, start-tls won't work when polling. if ((bool)this[Options.AUTO_TLS] && (m_features.StartTLS != null) && (!m_sslOn) && m_stanzas.SupportsTLS) { // start-tls lock (m_stateLock) { State = StartTLSState.Instance; } this.Write(new StartTLS(m_doc)); return; } Compression comp = m_features.Compression; if ((bool)this[Options.AUTO_COMPRESS] && (comp != null) && comp.HasMethod("zlib") && (!m_compressionOn) && m_stanzas.SupportsCompression) { // start compression lock (m_stateLock) { State = CompressionState.Instance; } Compress c = new Compress(m_doc); c.Method = "zlib"; this.Write(c); return; } // not authenticated yet. Note: we'll get a stream:features // after the last sasl restart, so we shouldn't try to iq:auth // at that point. if (!IsAuthenticated) { Mechanisms ms = m_features.Mechanisms; m_saslProc = null; MechanismType types = MechanismType.NONE; if (ms != null) { // if SASL_MECHANISMS is set in the options, it is the limited set // of mechanisms we're willing to try. Mask them off of the offered set. object smt = this[Options.SASL_MECHANISMS]; if (smt != null) types = (MechanismType)smt & ms.Types; else types = ms.Types; } // If we're doing SASL, and there are mechanisms implemented by both // client and server. if ((types != MechanismType.NONE) && ((bool)this[Options.SASL])) { lock (m_stateLock) { State = SASLState.Instance; } m_saslProc = SASLProcessor.createProcessor(types , m_sslOn || (bool)this[Options.PLAINTEXT] , ms , (bool)this[Options.ANONYMOUS]); if (m_saslProc == null) { FireOnError(new <API key>("No implemented mechanisms in: " + types.ToString())); return; } if (OnSASLStart != null) OnSASLStart(this, m_saslProc); lock (m_stateLock) { // probably manual authentication if (State != SASLState.Instance) return; } try { Step s = m_saslProc.step(null, this.Document); if (s != null) this.Write(s); } catch (Exception e) { FireOnError(new SASLException(e.Message)); return; } } if (m_saslProc == null) { // no SASL mechanisms. Try iq:auth. if ((bool)this[Options.REQUIRE_SASL]) { FireOnError(new SASLException("No SASL mechanisms available")); return; } lock (m_stateLock) { State = NonSASLAuthState.Instance; } if (OnSASLStart != null) OnSASLStart(this, null); // HACK: old-style auth for jabberclient. } } } <summary> Informs the client that an XML element was received and invokes the OnProtocol event. </summary> <param name="sender">The object that called this method.</param> <param name="tag">XML element that contains the new tag.</param> protected virtual void OnElement(object sender, System.Xml.XmlElement tag) { //Debug.WriteLine(tag.OuterXml); if (tag is jabber.protocol.stream.Error) { // Stream error. Race condition! Two cases: // 1) OnClose has already fired, in which case we are in ClosedState, and the reconnect timer is pending. // 2) OnClose hasn't fired, in which case we trick it into not starting the reconnect timer. lock (m_stateLock) { if (m_state != ClosedState.Instance) { State = ClosingState.Instance; } else if (m_reconnectTimer != null) { Debug.WriteLine("Disposing of timer"); m_reconnectTimer.Dispose(); } } if (OnStreamError != null) { if (InvokeRequired) CheckedInvoke(OnStreamError, new object[] { this, tag }); else OnStreamError(this, tag); } return; } if (State == ServerFeaturesState.Instance) { Features f = tag as Features; if (f == null) { FireOnError(new <API key>("Expecting stream:features from a version='1.0' server")); return; } m_features = f; ProcessFeatures(); return; } else if (State == SASLState.Instance) { if (tag is Success) { // restart the stream again SendNewStreamHeader(); } else if (tag is SASLFailure) { m_saslProc = null; lock (m_stateLock) { State = SASLFailedState.Instance; } SASLFailure sf = tag as SASLFailure; // TODO: I18N if (OnSASLError != null) { m_reconnect = false; OnSASLError(this, sf); } else FireOnError(new SASLException("SASL failure: " + sf.InnerXml)); return; } else if (tag is Step) { try { Step s = m_saslProc.step(tag as Step, this.Document); if (s != null) Write(s); } catch (Exception e) { FireOnError(new SASLException(e.Message)); return; } } else { m_saslProc = null; FireOnError(new SASLException("Invalid SASL protocol")); return; } } else if (State == StartTLSState.Instance) { switch (tag.Name) { case "proceed": if (!StartTLS()) return; SendNewStreamHeader(); break; case "failure": FireOnError(new <API key>()); return; } } else if (State == CompressionState.Instance) { switch (tag.Name) { case "compressed": if (!StartCompression()) return; SendNewStreamHeader(); break; case "failure": CompressionFailure fail = tag as CompressionFailure; FireOnError(new bedrock.io.<API key>(fail.Error)); return; } } else if (State == SASLAuthedState.Instance) { Features f = tag as Features; if (f == null) { FireOnError(new <API key>("Expecting stream:features from a version='1.0' server")); return; } if (OnSASLEnd != null) OnSASLEnd(this, f); m_saslProc = null; } else { if (OnProtocol != null) { if (InvokeRequired) CheckedInvoke(OnProtocol, new object[] { this, tag }); else OnProtocol(this, tag); } } CheckAll(tag); } <summary> Begins the TLS handshake, either client-side or server-side. </summary> <returns>True if StartTLS worked.</returns> protected bool StartTLS() { try { m_stanzas.StartTLS(); } catch (Exception e) { m_reconnect = false; if (e.InnerException != null) FireOnError(e.InnerException); else FireOnError(e); return false; } m_sslOn = true; return true; } <summary> Begins compressing the XMPP stream. </summary> <returns>If True, compression was successful, otherwise False.</returns> protected bool StartCompression() { try { m_stanzas.StartCompression(); } catch (Exception e) { m_reconnect = false; FireOnError(e); return false; } m_compressionOn = true; return true; } <summary> Gets ready for a new stream:stream by starting a new XML document. Needed after Start-TLS or compression, for example. </summary> protected void InitializeStream() { try { m_stanzas.InitializeStream(); } catch (Exception e) { FireOnError(e); } } <summary> Sends a new XMPP stream header. </summary> protected void SendNewStreamHeader() { jabber.protocol.stream.Stream str = new jabber.protocol.stream.Stream(m_doc, NS); str.To = new JID((string)this[Options.TO]); str.Version = "1.0"; m_stanzas.WriteStartTag(str); InitializeStream(); } <summary> Informs the client of XMPP stream errors through the OnError event. </summary> <param name="e">Error that occurred.</param> protected void FireOnError(Exception e) { m_reconnect = false; // ignore spurious IO errors on shutdown. if (((State == ClosingState.Instance) || (State == ClosedState.Instance)) && ((e is System.IO.IOException) || (e.InnerException is System.IO.IOException))) return; if (OnError != null) { if (InvokeRequired) CheckedInvoke(OnError, new object[] { this, e }); else OnError(this, e); } if ((State != ClosingState.Instance) && (State == ClosedState.Instance)) Close(false); } private void Reconnect(object state) { // prevent double-connects if (this.State == ClosedState.Instance) Connect(); } <summary> Registers a callback, so that if a packet arrives that matches the given xpath expression, the callback fires. Use <see cref="AddNamespace"/> to add namespace prefixes. </summary> <example>jc.AddCallback("self::iq[@type='result']/roster:query", new ProtocolHandler(GotRoster));</example> <param name="xpath">The xpath expression to search for</param> <param name="cb">The callback to call when the xpath matches</param> <returns>A guid that can be used to unregister the callback</returns> public Guid AddCallback(string xpath, ProtocolHandler cb) { CallbackData cbd = new CallbackData(xpath, cb); m_callbacks.Add(cbd); return cbd.Guid; } <summary> Removes a callback added with <see cref="AddCallback"/>. </summary> <param name="guid">GUID representing the callback to remove.</param> public void RemoveCallback(Guid guid) { int count = 0; foreach (CallbackData cbd in m_callbacks) { if (cbd.Guid == guid) { m_callbacks.RemoveAt(count); return; } count++; } throw new ArgumentException("Unknown Guid", "guid"); } <summary> Adds a namespace prefix, for use with callback xpath expressions added with <see cref="AddCallback"/>. </summary> <param name="prefix">The prefix to use.</param> <param name="uri">The URI associated with the prefix.</param> public void AddNamespace(string prefix, string uri) { m_ns.AddNamespace(prefix, uri); } private void CheckAll(XmlElement elem) { foreach (CallbackData cbd in m_callbacks) { cbd.Check(this, elem); } } private class CallbackData { private Guid m_guid = Guid.NewGuid(); private ProtocolHandler m_cb; private string m_xpath; public CallbackData(string xpath, ProtocolHandler cb) { Debug.Assert(cb != null); m_cb = cb; m_xpath = xpath; } public Guid Guid { get { return m_guid; } } public string XPath { get { return m_xpath; } } public void Check(XmppStream sender, XmlElement elem) { try { XmlNode n = elem.SelectSingleNode(m_xpath, sender.m_ns); if (n != null) { if (sender.InvokeRequired) sender.CheckedInvoke(m_cb, new object[] { sender, elem }); else m_cb(sender, elem); } } catch (Exception e) { sender.FireOnError(e); } } } #region <API key> Members void <API key>.Connected() { lock (m_stateLock) { this.State = ConnectedState.Instance; if ((bool)this[Options.SSL]) m_sslOn = true; } if (OnConnect != null) { if (InvokeRequired) CheckedInvoke(OnConnect, new Object[] { this, m_stanzas }); else OnConnect(this, m_stanzas); } SendNewStreamHeader(); } void <API key>.Accepted() { lock (StateLock) { Debug.Assert(this.State == AcceptingState.Instance, this.State.GetType().ToString()); this.State = ConnectedState.Instance; } if (OnConnect != null) { if (InvokeRequired) CheckedInvoke(OnConnect, new object[] { this, m_stanzas }); else { // Um. This cast might not be right, but I don't want to break backward compatibility // if I don't have to by changing the delegate interface. OnConnect(this, m_stanzas); } } } void <API key>.BytesRead(byte[] buf, int offset, int count) { if (OnReadText != null) { if (InvokeRequired) CheckedInvoke(OnReadText, new object[] { this, ENC.GetString(buf, offset, count) }); else OnReadText(this, ENC.GetString(buf, offset, count)); } } void <API key>.BytesWritten(byte[] buf, int offset, int count) { if (OnWriteText != null) { if (InvokeRequired) CheckedInvoke(OnWriteText, new object[] { this, ENC.GetString(buf, offset, count) }); else OnWriteText(this, ENC.GetString(buf, offset, count)); } } void <API key>.StreamInit(ElementStream stream) { if (OnStreamInit != null) { // Race condition. Make sure not to make GUI calls in OnStreamInit /* if (InvokeRequired) CheckedInvoke(OnStreamInit, new object[] { this, stream }); else */ OnStreamInit(this, stream); } } void <API key>.Errored(Exception ex) { m_reconnect = false; lock (m_stateLock) { State = ClosedState.Instance; if ((m_stanzas != null) && (!m_stanzas.Acceptable)) m_stanzas = null; } if (OnError != null) { if (InvokeRequired) CheckedInvoke(OnError, new object[] { this, ex }); else OnError(this, ex); } // TODO: Figure out what the "good" errors are, and try to // reconnect. There are too many "bad" errors to just let this fly. //TryReconnect(); } void <API key>.Closed() { lock (StateLock) { State = ClosedState.Instance; if ((m_stanzas != null) && (!m_stanzas.Acceptable)) m_stanzas = null; m_sslOn = false; m_compressionOn = false; } if (OnDisconnect != null) { if (InvokeRequired) CheckedInvoke(OnDisconnect, new object[] { this }); else OnDisconnect(this); } TryReconnect(); } void <API key>.DocumentStarted(XmlElement elem) { // The OnDocumentStart logic stays outside the listener, so that it can be // more easily overriden by subclasses. OnDocumentStart(m_stanzas, elem); } void <API key>.DocumentEnded() { lock (StateLock) { State = ClosingState.Instance; // TODO: Validate this, with current parser: // No need to close stream any more. AElfred does this for us, even though // the docs say it doesn't. //if (m_sock != null) //m_sock.Close(); } } void <API key>.StanzaReceived(XmlElement elem) { // The OnElement logic stays outside the listener, so that it can be // more easily overriden by subclasses. OnElement(m_stanzas, elem); } private bool <API key>(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { #if !__MonoCS__ CertificatePrompt cp = new CertificatePrompt((X509Certificate2)certificate, chain, sslPolicyErrors); return (cp.ShowDialog() == System.Windows.Forms.DialogResult.OK); #else return false; #endif } bool <API key>.<API key>(bedrock.net.BaseSocket sock, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { if (<API key> != null) { if ((m_invoker == null) || (!m_invoker.InvokeRequired)) return <API key>(sock, certificate, chain, sslPolicyErrors); try { // Note: can't use CheckedInvoke here, since we need the return value. We'll wait for the response. return (bool)m_invoker.Invoke(<API key>, new object[] { sock, certificate, chain, sslPolicyErrors }); } catch (Exception e) { Debug.WriteLine("Exception passed along by XmppStream: " + e.ToString()); return false; } } if ((m_invoker == null) || (!m_invoker.InvokeRequired)) return <API key>(sock, certificate, chain, sslPolicyErrors); return (bool)m_invoker.Invoke(new System.Net.Security.<API key>(<API key>), new object[]{ sock, certificate, chain, sslPolicyErrors }); } #endregion } }
package com.github.thiagotgm.modular_commands.annotation; import com.github.thiagotgm.modular_commands.api.CommandRegistry; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.modules.IModule; /** * SubModule for testing annotated commands. * * @version 1.0 * @author ThiagoTGM * @since 2017-07-21 */ public class AnnotationSubModule implements IModule { @Override public boolean enable( IDiscordClient client ) { CommandRegistry parent = CommandRegistry.getRegistry( client ) .getSubRegistry( IModule.class, AnnotationModule.NAME ); CommandRegistry reg = parent.getSubRegistry( this ); reg.<API key>( new <API key>() ); parent = CommandRegistry.getRegistry( client ) .getSubRegistry( IModule.class, "Inexistent module" ); reg = parent.getSubRegistry( this ); reg.<API key>( new InexistentCommand() ); IModule inexistent = new AnnotationSubModule() { @Override public String getName() { return "Inexistent module"; } }; CommandRegistry root = CommandRegistry.getRegistry( client ); root.getSubRegistry( inexistent ); root.removeSubRegistry( inexistent ); root.removeSubRegistry( inexistent ); root.getSubRegistry( IModule.class, "Inexistent module" ).removeSubRegistry( this ); return true; } @Override public void disable() { // TODO Auto-generated method stub } @Override public String getName() { return "Annotation submodule"; } @Override public String getAuthor() { return "ThiagoTGM"; } @Override public String getVersion() { return "1.0.0"; } @Override public String <API key>() { return "2.8.4"; } }
#ifndef <API key> #define <API key> #include "s3request.h" namespace QtAws { namespace S3 { class <API key>; class QTAWSS3_EXPORT <API key> : public S3Request { public: <API key>(const <API key> &other); <API key>(); virtual bool isValid() const Q_DECL_OVERRIDE; protected: virtual QtAws::Core::AwsAbstractResponse * response(QNetworkReply * const reply) const Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(<API key>) }; } // namespace S3 } // namespace QtAws #endif
<?php namespace Psc\CMS; /** * @group class:Psc\CMS\SearchPanel */ class SearchPanelTest extends \Psc\Code\Test\HTMLTestCase { protected $searchPanel; public function setUp() { $this->chainClass = 'Psc\CMS\SearchPanel'; parent::setUp(); } public function testAcceptance() { $searchPanel = new SearchPanel((object) array('label'=>'Sprecher', 'genitiv'=>'eines Sprechers', 'fields'=>'Namen oder <API key>', 'url'=>'/autocomplete/go/search' ) ); $this->html = $searchPanel->html(); $this->test->css('fieldset.psc-cms-ui-group',$this->html) ->count(1) ->test('legend') ->count(1) ->hasText('Sprecher-Suche') ->end() ->test('div.content input.autocomplete[type="text"][name="identifier"]') ->count(1) ->end() ->test('small.hint') ->count(2) ; } } ?>
// Includes #include "<API key>.h" #include "<API key>.h" // Code <API key>::<API key>(const XnChar* strType, const XnChar* strName) : XnDeviceStream(strType, strName), m_pLastData(NULL), <API key>(0) {} <API key>::~<API key>() { <API key>::Free(); } XnStatus <API key>::Init() { XnStatus nRetVal = XN_STATUS_OK; nRetVal = XnDeviceStream::Init(); XN_IS_STATUS_OK(nRetVal); // register for size change (so we can realloc stream data) nRetVal = <API key>().OnChangeEvent().Register(<API key>, this); XN_IS_STATUS_OK(nRetVal); // and create stream data nRetVal = XnStreamDataCreate(&m_pLastData, GetName(), GetRequiredDataSize()); XN_IS_STATUS_OK(nRetVal); return (XN_STATUS_OK); } XnStatus <API key>::Free() { if (m_pLastData != NULL) { XnStreamDataDestroy(&m_pLastData); m_pLastData = NULL; } return (XN_STATUS_OK); } XnStatus <API key>::ReadImpl(XnStreamData* pStreamData) { XnStatus nRetVal = XN_STATUS_OK; pStreamData->nFrameID = m_pLastData->nFrameID; pStreamData->nTimestamp = m_pLastData->nTimestamp; if (pStreamData->pInternal->bAllocated) { // don't take more than required size pStreamData->nDataSize = XN_MIN(m_pLastData->nDataSize, GetRequiredDataSize()); xnOSMemCopy(pStreamData->pData, m_pLastData->pData, pStreamData->nDataSize); } else { pStreamData->nDataSize = m_pLastData->nDataSize; pStreamData->pData = m_pLastData->pData; } return (XN_STATUS_OK); } XnStatus <API key>::CalcRequiredSize(XnUInt32* pnRequiredSize) const { // we use the same size we have now *pnRequiredSize = GetRequiredDataSize(); return XN_STATUS_OK; } void <API key>::NewDataAvailable(XnUInt64 nTimestamp, XnUInt32 nFrameID) { m_pLastData->nFrameID = ++<API key>; XnDeviceStream::NewDataAvailable(m_pLastData->nTimestamp, m_pLastData->nFrameID); } void <API key>::ReMarkDataAsNew() { XnDeviceStream::NewDataAvailable(m_pLastData->nTimestamp, m_pLastData->nFrameID); } void <API key>::Reset() { <API key> = 0; xnOSMemSet(m_pLastData->pData, 0, m_pLastData->pInternal->nAllocSize); m_pLastData->nDataSize = 0; m_pLastData->nFrameID = 0; m_pLastData->nTimestamp = 0; m_pLastData->bIsNew = FALSE; XnDeviceStream::<API key>(); } XnStatus <API key>::<API key>() { XnStatus nRetVal = XN_STATUS_OK; nRetVal = <API key>(m_pLastData, GetRequiredDataSize()); XN_IS_STATUS_OK(nRetVal); return (XN_STATUS_OK); } XnStatus <API key>::<API key>(const XnProperty* pSender, void* pCookie) { <API key>* pThis = (<API key>*)pCookie; return pThis-><API key>(); }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> <meta name="generator" content="LibreOffice 5.4.5.1 (Linux)"/> <meta name="author" content="Jean-Louis PASTUREL"/> <meta name="created" content="2017-04-08T00:00:00.009383251"/> <meta name="changed" content="2018-03-28T08:35:51.282826049"/> <style type="text/css"> h2.cjk { font-family: "SimSun" } h2.ctl { font-family: "Lucida Sans" } </style> </head> <body lang="en-GB" dir="ltr"> <h1 lang="fr-FR" style="page-break-before: always">Whatido&nbsp;: Présentation du produit</h1> <h2 lang="fr-FR" class="western">Généralités</h2> <p lang="fr-FR">Il s'agit d'un utilitaire qui permet de visualiser sur l'écran, les actions que l'on fait sur la souris ( clic / droit/gauche/milieu et les actions avant / arrière sur la roulettes) ainsi que les actions sur le clavier ( hors pavé numérique).</p> <p lang="fr-FR">La visualisation se fait à travers 2 images transparentes de la souris et du clavier qui reste en fenêtre toujours visible ( sauf pour quelques menus contextuel où Windows est prioritaire, mais ce n'est pas très gênant).</p> <p lang="fr-FR">Le logiciel fonctionne aussi sur Linux et à priori aussi sur OS X ( non testé par moi sur OS X, mapping du clavier à faire), voir dans les annexes de ce document comment réaliser un mapping complet si ce logiciel ne fonctionne pas correctement avec votre micro/os/clavier. Il se peut qu'il y ait des écarts avec le mapping Windows/AZERTY .</p> <p style="margin-bottom: 0cm">Cette application est basée sur la Bibliothèque <b>JNativeHook</b> disponible sur le site Github : <a href="https: <p style="margin-bottom: 0cm"><br/> </p> <p style="margin-bottom: 0cm">Le code binaire est disponible dans le dépot Maven , j'ai utilisé la Version 2.1.0 : </p> <p><a href="https: <p>Une vidéo montrant whatido au travail : <a href="https: <h2 class="western">Un aperçu du produit sur ce document</h2> <p>L'écran de lancement qui sera expliqué en détail plus loin dans le document.</p> <p align="center"><img src="<API key>.jpg" name="images1" align="bottom" width="603" height="377" border="0"/> </p> <p><br/> <br/> </p> <p style="page-break-before: always">Une image du produit en action&nbsp;:</p> <p align="center"><img src="<API key>.jpg" name="images2" align="bottom" width="642" height="366" border="0"/> </p> <p lang="fr-FR">On voit un rond bleu sur la touche Print-Screen quand j'ai fait la copie d'écran&nbsp;!</p> <p lang="fr-FR">On peut choisir l'affichage ou non du clavier, on peut activer le son qui décrit les actions faites sur la souris et le clavier. Pour le clavier on dispose de 3 tailles ( Normal, Medium, Small), utile pour l'apprentissage du clavier aux débutants .</p> <p lang="fr-FR">Pour ce qui concerne la souris, on a 4 tailles au choix ( Large, Medium, Small, Tiny) et le fait d’être mobile pour les 3 plus petites tailles et d'être fixe pour les 3 plus grandes tailles.</p> <p lang="fr-FR">Pour les souris de type fixe, le bouton noir au milieu permet de la déplacer dans une autre partie de l'écran quand elle gène.</p> <h2 class="western">Exemples d'utilisation du produit</h2> <p><b>Whatido </b>fonctionne correctement avec des vidéo-projecteurs.</p> <p>Les utilisations possibles sont :</p> <ul> <li/> <p>initiation à l'informatique pour la présentation des actions souris et le clavier</p> <li/> <p>présentation en direct de logiciel en visualisant toutes les actions souris et clavier</p> <ul> <ul> <li/> <p>ex : navigation dans l'explorateur de fichier, mécanismes du copier/coller, utilisation des outils bureautiques ...</p> </ul> </ul> <li/> <p>création de tutoriels vidéo par enregistrement de l'écran avec <b>whatido</b> activé.</p> </ul> <p>Astuce : on peut lancer 2 fois le produit :</p> <ul> <ul> <li/> <p>une fois avec une souris fixe de taille Large ou Médium</p> <li/> <p>l'autre fois avec la souris Tiny/Mobile qui va suivre le curseur Windows au cours de ses déplacements. </p> </ul> </ul> <p>Les 2 souris montreront les actions faites.</p> <p>Limitation avec <b>Powerpoint</b> en mode Diaporama, le produit (image souris et/ou image clavier) n’apparaît pas en premier plan et ne peut être utiliser dans ce cas, il faut rester en mode édition.</p> <h1>Installation</h1> <h2 class="western">Pré-requis</h2> <p><b>Whatido</b> nécessite la présence d'une machine virtuelle <b>Java </b>récente version supérieure à <b>1.8.0_121</b>.</p> <p>On pourra installer la version <b>JRE 32 bits</b> depuis le site de <b>Oracle</b>&nbsp;:</p> <p><a href="http: <p align="center"><img src="<API key>.jpg" name="images3" align="bottom" width="465" height="214" border="0"/> </p> <p><br/> <br/> </p> <p>Cocher l'acceptation de licence.</p> <p align="center"><img src="<API key>.jpg" name="images4" align="bottom" width="571" height="358" border="0"/> </p> <p lang="fr-FR">Choisir le téléchargement de la version 32 bits ( i586) . La version à télécharger sur le site de Oracle doit être la plus récente.</p> <p><span lang="fr-FR">Après téléchargement, il faudra lancer le </span><span lang="fr-FR"><b>fichier .exe correspondant en mode administrateur</b></span> <span lang="fr-FR">( clic droit sur le fichier, et choisir lancement en mode administrateur).</span></p> <p lang="fr-FR">Une fois installé, vous devez pouvoir voir votre JRE comme montré ci-dessous&nbsp;:</p> <p align="center"><img src="<API key>.jpg" name="images5" align="bottom" width="645" height="408" border="0"/> </p> <p><br/> <br/> </p> <h2 class="western">Installation de Whatido</h2> <p>Le produit se présente sous la forme d'une archive zip <b>whatido&lt;Version&gt;Exe.zip</b> ex <b>whatido3Exe.zip </b><span style="font-weight: normal">. Une archive au format zip est disponible sous la racine de :</span></p> <p><a href="https: <p><span style="font-weight: normal">On va supposer pour la suite de l'installation qu'il existe un répertoire </span><b>C:\opt</b> <span style="font-weight: normal">sur votre ordinateur, sinon vous le créez ou bien vous adapterez la procédure décrite ci-dessous.</span></p> <ul> <li/> <p><span style="font-weight: normal">Positionner l'archive </span><b>whatido3Exe.zip</b> <span style="font-weight: normal">sous </span><b>C:\opt</b> <span style="font-weight: normal">et dézipper</span></p> <li/> <p><span style="font-weight: normal">Ouvrir le fichier C:\opt\whatido\script\</span><b>whatido.cmd</b> <span style="font-weight: normal">et adapter les chemins en rouge </span> </p> </ul> <p style="margin-left: 1.25cm; background: #ccffff"><font face="Consolas, monospace"><font size="2" style="font-size: 10pt"><span style="font-weight: normal">Set PROJECT_HOME=</span><font color="#ff0000"><b>C:\opt\whatido</b></font></font></font></p> <p style="margin-left: 1.25cm; font-weight: normal; background: #ccffff"> <font face="Consolas, monospace"><font size="2" style="font-size: 10pt">Set CLASSPATH=%PROJECT_HOME%\lib\jnativehook-2.1.0.jar;.;%PROJECT_HOME%\lib\whatido-3.0.0.jar;</font></font></p> <p style="margin-left: 1.25cm; background: #ccffff"><font face="Consolas, monospace"><font size="2" style="font-size: 10pt"><span style="font-weight: normal">Set JAVA_HOME=C:\Program Files (x86)\Java\</span><font color="#ff0000"><b>jre1.8.0_121</b></font><span style="font-weight: normal">\bin</span></font></font></p> <p style="margin-left: 1.25cm; font-weight: normal; background: #ccffff"> <font face="Consolas, monospace"><font size="2" style="font-size: 10pt">start &quot;&quot; &quot;%JAVA_HOME%\javaw&quot; -Droot=%PROJECT_HOME% -Dhome=%PROJECT_HOME% -cp %CLASSPATH% com.jlp.whatido.Main </font></font> </p> <p style="margin-left: 1.25cm; font-weight: normal; background: #ccffff"> <font face="Consolas, monospace"><font size="2" style="font-size: 10pt">Exit</font></font></p> <ul> <li/> <p><span style="font-weight: normal">Ouvrir le fichier C:\opt\whatido\script\</span><b><API key>.cmd</b> <span style="font-weight: normal">et adapter les chemins en rouge </span> </p> </ul> <p style="margin-left: 2.5cm; background: #ccffff; page-break-before: always"> <font face="Consolas, monospace"><font size="2" style="font-size: 10pt"><span style="font-weight: normal">Set PROJECT_HOME=</span><font color="#ff0000"><b>C:\opt\whatido</b></font></font></font></p> <p style="margin-left: 2.5cm; font-weight: normal; background: #ccffff"> <font face="Consolas, monospace"><font size="2" style="font-size: 10pt">Set CLASSPATH=%PROJECT_HOME%\lib\jnativehook-2.1.0.jar;.;%PROJECT_HOME%\lib\whatido-3.0.0.jar;</font></font></p> <p style="margin-left: 2.5cm; background: #ccffff"><font face="Consolas, monospace"><font size="2" style="font-size: 10pt"><span style="font-weight: normal">Set JAVA_HOME=C:\Program Files (x86)\Java\</span><font color="#ff0000"><b>jre1.8.0_121</b></font><span style="font-weight: normal">\bin</span></font></font></p> <p style="margin-left: 2.5cm; font-weight: normal; background: #ccffff"> <font face="Consolas, monospace"><font size="2" style="font-size: 10pt">&quot;%JAVA_HOME%\java&quot; -Droot=%PROJECT_HOME% -Dhome=%PROJECT_HOME% -cp %CLASSPATH% com.jlp.whatido.<API key> </font></font> </p> <ul> <li/> <p style="background: transparent"><font face="Times New Roman, serif"><font size="3" style="font-size: 12pt"><span style="font-weight: normal">Faire un raccourci sur le bureau pour le fichier C:\opt\whatido\script\</span><b>whatido.cmd</b></font></font></p> <li/> <p style="font-weight: normal; background: transparent"><font face="Times New Roman, serif"><font size="3" style="font-size: 12pt">Une icône <b>whatidoIco.ico</b> est fournie dans le répertoire <b>C:\opt\whatido\script\ </b>pour illustrer le raccourci.</font></font></p> <li/> <p style="background: transparent"><font face="Times New Roman, serif"><font size="3" style="font-size: 12pt"><span style="font-weight: normal">Cliquer sur le raccourci pour lancer</span> <b>whatido.</b></font></font></p> </ul> <p style="background: transparent"><br/> <br/> </p> </body> </html>
#ifndef <API key> #define <API key> #include "IMVPPlayerDialog.hpp" #include <mvp-player-core/MVPPlayerEngine.hpp> #include <mvp-player-core/MVPPlayerPresenter.hpp> namespace mvpplayer { namespace gui { /** * @brief Setup music player's behavior (connect signals between the model/view/presenter) */ void setupMainBehavior( mvpplayer::MVPPlayerEngine & m, mvpplayer::gui::IMVPPlayerDialog & v, mvpplayer::logic::MVPPlayerPresenter & p ); void <API key>( mvpplayer::gui::IMVPPlayerDialog & v, mvpplayer::logic::MVPPlayerPresenter & p ); void <API key>( mvpplayer::logic::MVPPlayerPresenter & p, mvpplayer::MVPPlayerEngine & m ); } } #endif
#ifndef <API key> #define <API key> namespace cocaine { namespace error { enum decode_errors { parse_error = 1, frame_format_error, insufficient_bytes }; namespace aux { class decode_category_t: public std::error_category { virtual auto name() const throw() -> const char* { return "cocaine.rpc.asio"; } virtual auto message(int code) const -> std::string { switch(code) { case decode_errors::parse_error: return "unable to parse the incoming data"; case decode_errors::frame_format_error: return "message has an unexpected framing"; case decode_errors::insufficient_bytes: return "insufficient bytes provided to decode the message"; } return "cocaine.rpc.asio error"; } }; } // namespace aux inline auto decode_category() -> const std::error_category& { static aux::decode_category_t instance; return instance; } inline auto make_error_code(decode_errors code) -> std::error_code { return std::error_code(static_cast<int>(code), decode_category()); } }} // namespace cocaine::error namespace std { template<> struct is_error_code_enum<cocaine::error::decode_errors>: public true_type { }; } // std #endif
#include "depscanner.h" #include "artifact.h" #include "projectbuilddata.h" #include "buildgraph.h" #include "transformer.h" #include <tools/error.h> #include <logging/translator.h> #include <language/language.h> #include <language/propertymapinternal.h> #include <language/resolvedfilecontext.h> #include <language/scriptengine.h> #include <jsextensions/moduleproperties.h> #include <plugins/scanner/scanner.h> #include <tools/fileinfo.h> #include <tools/stringconstants.h> #include <QtCore/qvariant.h> #include <QtScript/qscriptcontext.h> namespace qbs { namespace Internal { QString DependencyScanner::id() const { if (m_id.isEmpty()) m_id = createId(); return m_id; } static QStringList <API key>(const QVariantMap &modules) { QStringList result; const QVariantMap cpp = modules.value(StringConstants::cppModule()).toMap(); if (cpp.empty()) return result; result << cpp.value(QStringLiteral("includePaths")).toStringList(); const bool useSystemHeaders = cpp.value(QStringLiteral("<API key>")).toBool(); if (useSystemHeaders) { result << cpp.value(QStringLiteral("systemIncludePaths")).toStringList() << cpp.value(QStringLiteral("<API key>")).toStringList() << cpp.value(QStringLiteral("<API key>")).toStringList(); } result.removeDuplicates(); return result; } <API key>::<API key>(ScannerPlugin *plugin) : m_plugin(plugin) { } QStringList <API key>::collectSearchPaths(Artifact *artifact) { if (m_plugin->flags & <API key>) return <API key>(artifact->properties->value()); return QStringList(); } QStringList <API key>::collectDependencies(FileResourceBase *file, const char *fileTags) { Set<QString> result; QString baseDirOfInFilePath = file->dirPath(); const QString &filepath = file->filePath(); void *scannerHandle = m_plugin->open(filepath.utf16(), fileTags, <API key>); if (!scannerHandle) return QStringList(); forever { int flags = 0; int length = 0; const char *szOutFilePath = m_plugin->next(scannerHandle, &length, &flags); if (szOutFilePath == nullptr) break; QString outFilePath = QString::fromLocal8Bit(szOutFilePath, length); if (outFilePath.isEmpty()) continue; if (flags & <API key>) { QString localFilePath = FileInfo::resolvePath(baseDirOfInFilePath, outFilePath); if (FileInfo::exists(localFilePath)) outFilePath = localFilePath; } result += outFilePath; } m_plugin->close(scannerHandle); return QStringList(result.toList()); } bool <API key>::recursive() const { return m_plugin->flags & <API key>; } const void *<API key>::key() const { return m_plugin; } QString <API key>::createId() const { return QString::fromLatin1(m_plugin->name); } bool <API key>::<API key>(const PropertyMapConstPtr &m1, const PropertyMapConstPtr &m2) const { // This changes when our C++ scanner starts taking defines into account. Q_UNUSED(m1); Q_UNUSED(m2); return true; } <API key>::<API key>(const <API key> &scanner, ScriptEngine *engine) : m_scanner(scanner), m_engine(engine), m_product(nullptr) { m_global = m_engine->newObject(); m_global.setPrototype(m_engine->globalObject()); <API key>(m_engine, m_scanner->scanScript.fileContext(), m_global, ObserveMode::Disabled); // TODO: QBS-1092 } QStringList <API key>::collectSearchPaths(Artifact *artifact) { return evaluate(artifact, m_scanner->searchPathsScript); } QStringList <API key>::collectDependencies(FileResourceBase *file, const char *fileTags) { Q_UNUSED(fileTags); // ### support user dependency scanners for file deps if (file->fileType() != FileResourceBase::FileTypeArtifact) return QStringList(); return evaluate(static_cast<Artifact *>(file), m_scanner->scanScript); } bool <API key>::recursive() const { return m_scanner->recursive; } const void *<API key>::key() const { return m_scanner.get(); } QString <API key>::createId() const { return m_scanner->scanScript.sourceCode(); } bool <API key>::<API key>(const PropertyMapConstPtr &m1, const PropertyMapConstPtr &m2) const { // TODO: This should probably be made more fine-grained. Perhaps the Scanner item // could declare the relevant properties, or we could figure them out automatically // somehow. return m1 == m2 || *m1 == *m2; } class <API key> { ScriptEngine *m_engine; public: <API key>(ScriptEngine *engine) : m_engine(engine) { m_engine->setActive(true); } ~<API key>() { m_engine->setActive(false); } }; QStringList <API key>::evaluate(Artifact *artifact, const <API key> &script) { <API key> guard(m_engine); if (artifact->product.get() != m_product) { m_product = artifact->product.get(); <API key>(m_engine, artifact->product.get(), m_scanner->module.get(), m_global, true); } QScriptValueList args; args.reserve(3); args.push_back(m_global.property(StringConstants::projectVar())); args.push_back(m_global.property(StringConstants::productVar())); args.push_back(Transformer::translateFileConfig(m_engine, artifact, m_scanner->module->name)); m_engine->setGlobalObject(m_global); QScriptValue &function = script.scriptFunction; if (!function.isValid() || function.engine() != m_engine) { function = m_engine->evaluate(script.sourceCode()); if (Q_UNLIKELY(!function.isFunction())) throw ErrorInfo(Tr::tr("Invalid scan script."), script.location()); } QScriptValue result = function.call(QScriptValue(), args); m_engine->setGlobalObject(m_global.prototype()); m_engine-><API key>(); if (Q_UNLIKELY(m_engine->hasErrorOrException(result))) { QString msg = Tr::tr("evaluating scan script: ") + m_engine->lastErrorString(result); const CodeLocation loc = m_engine->lastErrorLocation(result, script.location()); m_engine->clearExceptions(); throw ErrorInfo(msg, loc); } QStringList list; if (result.isArray()) { const int count = result.property(StringConstants::lengthProperty()).toInt32(); list.reserve(count); for (qint32 i = 0; i < count; ++i) { QScriptValue item = result.property(i); if (item.isValid() && !item.isUndefined()) list.push_back(item.toString()); } } return list; } } // namespace Internal } // namespace qbs
# This file is part of RBniCS. # <API key>: LGPL-3.0-or-later import os import re import sys import importlib import pytest import pytest_flake8 from nbconvert.exporters import PythonExporter import nbconvert.filters from mpi4py import MPI try: import dolfin # otherwise the next import from rbnics would disable dolfin as a required backend # noqa: F401 except ImportError: pass from rbnics.utils.test import ( add_gold_options, disable_matplotlib, enable_matplotlib, <API key>, <API key>) def pytest_addoption(parser): add_gold_options(parser) def pytest_configure(config): <API key>(config) def <API key>(path, config): if path.ext == ".py" and path.new(ext=".ipynb").exists(): # ignore .py files obtained from previous runs return True else: return False def pytest_collect_file(path, parent): """ Collect tutorial files. """ if path.ext == ".ipynb": # Convert .ipynb notebooks to plain .py files def comment_lines(text, prefix=" regex = re.compile(r".{1,80}(?:\s+|$)") input_lines = text.split("\n") output_lines = [split_line.rstrip() for line in input_lines for split_line in regex.findall(line)] output = prefix + ("\n" + prefix).join(output_lines) return output.replace(prefix + "\n", prefix.rstrip(" ") + "\n") def ipython2python(code): return nbconvert.filters.ipython2python(code).rstrip("\n") + "\n" filters = { "comment_lines": comment_lines, "ipython2python": ipython2python } exporter = PythonExporter(filters=filters) exporter.<API key> = True code, _ = exporter.from_filename(path) code = code.rstrip("\n") + "\n" if MPI.COMM_WORLD.Get_rank() == 0: with open(path.new(ext=".py"), "w", encoding="utf-8") as f: f.write(code) MPI.COMM_WORLD.Barrier() # Collect the corresponding .py file config = parent.config if config.getoption("--flake8"): return pytest_flake8.pytest_collect_file(path.new(ext=".py"), parent) else: if "data" not in path.dirname: # skip running mesh generation notebooks if not path.basename.startswith("x"): return TutorialFile.from_parent(parent=parent, fspath=path.new(ext=".py")) else: return DoNothingFile.from_parent(parent=parent, fspath=path.new(ext=".py")) elif path.ext == ".py": # TODO remove after transition to ipynb is complete? assert never py files? if (path.basename not in "conftest.py" # do not run pytest configuration file or "data" not in path.dirname): # skip running mesh generation notebooks if not path.basename.startswith("x"): return TutorialFile.from_parent(parent=parent, fspath=path) else: return DoNothingFile.from_parent(parent=parent, fspath=path) def <API key>(path, parent): """ Disable running .py files produced by previous runs, as they may get out of sync with the corresponding .ipynb file. """ if path.ext == ".py": assert not path.new(ext=".ipynb").exists(), "Please run pytest on jupyter notebooks, not plain python files." return DoNothingFile.from_parent( parent=parent, fspath=path) # TODO remove after transition to ipynb is complete? def <API key>(item, nextitem): # Do the normal teardown item.teardown() # Add a MPI barrier in parallel MPI.COMM_WORLD.Barrier() class TutorialFile(pytest.File): """ Custom file handler for tutorial files. """ def collect(self): yield TutorialItem.from_parent(parent=self, name=os.path.relpath(str(self.fspath), str(self.parent.fspath))) class TutorialItem(pytest.Item): """ Handle the execution of the tutorial. """ @<API key>() def runtest(self): disable_matplotlib() os.chdir(self.parent.fspath.dirname) sys.path.append(self.parent.fspath.dirname) spec = importlib.util.<API key>(self.name, str(self.parent.fspath)) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) enable_matplotlib() def reportinfo(self): return self.fspath, 0, self.name class DoNothingFile(pytest.File): """ Custom file handler to avoid running twice python files explicitly provided on the command line. """ def collect(self): return []
#include <common.h> #include <memory.h> #include <types.h> #include "<API key>.h" #include "pyvshadow_libbfio.h" #include "pyvshadow_libcerror.h" #include "<API key>.h" #include "pyvshadow_python.h" /* Creates a file object IO handle * Make sure the value <API key> is referencing, is set to NULL * Returns 1 if successful or -1 on error */ int <API key>( <API key> **<API key>, PyObject *file_object, libcerror_error_t **error ) { static char *function = "<API key>"; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } if( *<API key> != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle value already set.", function ); return( -1 ); } if( file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object.", function ); return( -1 ); } *<API key> = (<API key> *) PyMem_Malloc( sizeof( <API key> ) ); if( *<API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to create file object IO handle.", function ); goto on_error; } if( memory_set( *<API key>, 0, sizeof( <API key> ) ) == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to clear file object IO handle.", function ); goto on_error; } ( *<API key> )->file_object = file_object; Py_IncRef( ( *<API key> )->file_object ); return( 1 ); on_error: if( *<API key> != NULL ) { PyMem_Free( *<API key> ); *<API key> = NULL; } return( -1 ); } /* Initializes the file object IO handle * Returns 1 if successful or -1 on error */ int <API key>( libbfio_handle_t **handle, PyObject *file_object, libcerror_error_t **error ) { <API key> *<API key> = NULL; static char *function = "<API key>"; if( handle == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid handle.", function ); return( -1 ); } if( *handle != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid handle value already set.", function ); return( -1 ); } if( <API key>( &<API key>, file_object, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to create file object IO handle.", function ); goto on_error; } if( <API key>( handle, (intptr_t *) <API key>, (int (*)(intptr_t **, libcerror_error_t **)) <API key>, (int (*)(intptr_t **, intptr_t *, libcerror_error_t **)) <API key>, (int (*)(intptr_t *, int, libcerror_error_t **)) <API key>, (int (*)(intptr_t *, libcerror_error_t **)) <API key>, (ssize_t (*)(intptr_t *, uint8_t *, size_t, libcerror_error_t **)) <API key>, (ssize_t (*)(intptr_t *, const uint8_t *, size_t, libcerror_error_t **)) <API key>, (off64_t (*)(intptr_t *, off64_t, int, libcerror_error_t **)) <API key>, (int (*)(intptr_t *, libcerror_error_t **)) <API key>, (int (*)(intptr_t *, libcerror_error_t **)) <API key>, (int (*)(intptr_t *, size64_t *, libcerror_error_t **)) <API key>, <API key> | <API key>, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to create handle.", function ); goto on_error; } return( 1 ); on_error: if( <API key> != NULL ) { <API key>( &<API key>, NULL ); } return( -1 ); } /* Frees a file object IO handle * Returns 1 if succesful or -1 on error */ int <API key>( <API key> **<API key>, libcerror_error_t **error ) { static char *function = "<API key>"; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } if( *<API key> != NULL ) { Py_DecRef( ( *<API key> )->file_object ); PyMem_Free( *<API key> ); *<API key> = NULL; } return( 1 ); } /* Clones (duplicates) the file object IO handle and its attributes * Returns 1 if succesful or -1 on error */ int <API key>( <API key> **<API key>, <API key> *<API key>, libcerror_error_t **error ) { static char *function = "<API key>"; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid destination file object IO handle.", function ); return( -1 ); } if( *<API key> != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: destination file object IO handle already set.", function ); return( -1 ); } if( <API key> == NULL ) { *<API key> = NULL; return( 1 ); } if( <API key>( <API key>, <API key>->file_object, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to create file object IO handle.", function ); return( -1 ); } if( *<API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: missing destination file object IO handle.", function ); return( -1 ); } return( 1 ); } /* Opens the file object IO handle * Returns 1 if successful or -1 on error */ int <API key>( <API key> *<API key>, int access_flags, libcerror_error_t **error ) { static char *function = "<API key>"; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } if( <API key>->file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle - missing file object.", function ); return( -1 ); } if( ( ( access_flags & <API key> ) != 0 ) && ( ( access_flags & <API key> ) != 0 ) ) { libcerror_error_set( error, <API key>, <API key>, "%s: unsupported access flags.", function ); return( -1 ); } if( ( access_flags & <API key> ) != 0 ) { libcerror_error_set( error, <API key>, <API key>, "%s: write access currently not supported.", function ); return( -1 ); } /* No need to do anything here, because the file object is already open */ <API key>->access_flags = access_flags; return( 1 ); } /* Closes the file object IO handle * Returns 0 if successful or -1 on error */ int <API key>( <API key> *<API key>, libcerror_error_t **error ) { static char *function = "<API key>"; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } if( <API key>->file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle - missing file object.", function ); return( -1 ); } /* Do not close the file object, have Python deal with it */ <API key>->access_flags = 0; return( 0 ); } /* Reads a buffer from the file object * Make sure to hold the GIL state before calling this function * Returns the number of bytes read if successful, or -1 on error */ ssize_t <API key>( PyObject *file_object, uint8_t *buffer, size_t size, libcerror_error_t **error ) { PyObject *argument_size = NULL; PyObject *exception_string = NULL; PyObject *exception_traceback = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; char *error_string = NULL; char *safe_buffer = NULL; static char *function = "<API key>"; Py_ssize_t safe_read_count = 0; ssize_t read_count = 0; int result = 0; if( file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object.", function ); return( -1 ); } if( buffer == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid buffer.", function ); return( -1 ); } if( size > (size_t) SSIZE_MAX ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid size value exceeds maximum.", function ); return( -1 ); } if( size > 0 ) { method_name = PyString_FromString( "read" ); argument_size = PyLong_FromSize_t( size ); PyErr_Clear(); method_result = <API key>( file_object, method_name, argument_size, NULL ); if( PyErr_Occurred() ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to read from file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to read from file object.", function ); } Py_DecRef( exception_string ); goto on_error; } result = <API key>( method_result, &safe_buffer, &safe_read_count ); if( result == -1 ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to read from file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to read from file object.", function ); } Py_DecRef( exception_string ); goto on_error; } if( safe_read_count > (Py_ssize_t) SSIZE_MAX ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid read count value exceeds maximum.", function ); goto on_error; } read_count = (ssize_t) safe_read_count; if( memory_copy( buffer, safe_buffer, read_count ) == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to data to buffer.", function ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( argument_size ); Py_DecRef( method_name ); } return( read_count ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( argument_size != NULL ) { Py_DecRef( argument_size ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); } /* Reads a buffer from the file object IO handle * Returns the number of bytes read if successful, or -1 on error */ ssize_t <API key>( <API key> *<API key>, uint8_t *buffer, size_t size, libcerror_error_t **error ) { static char *function = "<API key>"; PyGILState_STATE gil_state = 0; ssize_t read_count = 0; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } gil_state = PyGILState_Ensure(); read_count = <API key>( <API key>->file_object, buffer, size, error ); if( read_count == -1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to read from file object.", function ); goto on_error; } PyGILState_Release( gil_state ); return( read_count ); on_error: PyGILState_Release( gil_state ); return( -1 ); } /* Writes a buffer to the file object * Make sure to hold the GIL state before calling this function * Returns the number of bytes written if successful, or -1 on error */ ssize_t <API key>( PyObject *file_object, const uint8_t *buffer, size_t size, libcerror_error_t **error ) { PyObject *argument_string = NULL; PyObject *exception_string = NULL; PyObject *exception_traceback = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; char *error_string = NULL; static char *function = "<API key>"; ssize_t write_count = 0; if( file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object.", function ); return( -1 ); } if( buffer == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid buffer.", function ); return( -1 ); } if( size > (size_t) SSIZE_MAX ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid size value exceeds maximum.", function ); return( -1 ); } if( size > 0 ) { method_name = PyString_FromString( "write" ); /* TODO set up argument_string */ write_count = (ssize_t) size; PyErr_Clear(); method_result = <API key>( file_object, method_name, argument_string, NULL ); if( PyErr_Occurred() ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to write from file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to write from file object.", function ); } Py_DecRef( exception_string ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( argument_string ); Py_DecRef( method_name ); } return( write_count ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( argument_string != NULL ) { Py_DecRef( argument_string ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); } /* Writes a buffer to the file object IO handle * Returns the number of bytes written if successful, or -1 on error */ ssize_t <API key>( <API key> *<API key>, const uint8_t *buffer, size_t size, libcerror_error_t **error ) { static char *function = "<API key>"; PyGILState_STATE gil_state = 0; ssize_t write_count = 0; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } gil_state = PyGILState_Ensure(); write_count = <API key>( <API key>->file_object, buffer, size, error ); if( write_count == -1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to write from file object.", function ); goto on_error; } PyGILState_Release( gil_state ); return( write_count ); on_error: PyGILState_Release( gil_state ); return( -1 ); } /* Seeks a certain offset within the file object * Make sure to hold the GIL state before calling this function * Returns 1 if successful or -1 on error */ int <API key>( PyObject *file_object, off64_t offset, int whence, libcerror_error_t **error ) { PyObject *argument_offset = NULL; PyObject *argument_whence = NULL; PyObject *exception_string = NULL; PyObject *exception_traceback = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; char *error_string = NULL; static char *function = "<API key>"; if( file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object.", function ); return( -1 ); } #if defined( HAVE_LONG_LONG ) if( offset > (off64_t) INT64_MAX ) #else if( offset > (off64_t) LONG_MAX ) #endif { libcerror_error_set( error, <API key>, <API key>, "%s: invalid offset value exceeds maximum.", function ); return( -1 ); } if( ( whence != SEEK_CUR ) && ( whence != SEEK_END ) && ( whence != SEEK_SET ) ) { libcerror_error_set( error, <API key>, <API key>, "%s: unsupported whence.", function ); return( -1 ); } method_name = PyString_FromString( "seek" ); #if defined( HAVE_LONG_LONG ) argument_offset = PyLong_FromLongLong( (PY_LONG_LONG) offset ); #else argument_offset = PyLong_FromLongLong( (long) offset ); #endif argument_whence = PyInt_FromLong( (long) whence ); PyErr_Clear(); method_result = <API key>( file_object, method_name, argument_offset, argument_whence, NULL ); if( PyErr_Occurred() ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to seek in file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to seek in file object.", function ); } Py_DecRef( exception_string ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( argument_whence ); Py_DecRef( argument_offset ); Py_DecRef( method_name ); return( 1 ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( argument_whence != NULL ) { Py_DecRef( argument_whence ); } if( argument_offset != NULL ) { Py_DecRef( argument_offset ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); } /* Retrieves the current offset within the file object * Make sure to hold the GIL state before calling this function * Returns 1 if successful or -1 on error */ int <API key>( PyObject *file_object, off64_t *offset, libcerror_error_t **error ) { PyObject *exception_string = NULL; PyObject *exception_traceback = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; char *error_string = NULL; static char *function = "<API key>"; #if defined( HAVE_LONG_LONG ) PY_LONG_LONG safe_offset = 0; #else long safe_offset = 0; #endif int result = 0; if( file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object.", function ); return( -1 ); } if( offset == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid offset.", function ); return( -1 ); } method_name = PyString_FromString( "get_offset" ); PyErr_Clear(); /* Determine if the file object has the get_offset method */ result = PyObject_HasAttr( file_object, method_name ); if( result == 0 ) { Py_DecRef( method_name ); /* Fall back to the tell method */ method_name = PyString_FromString( "tell" ); } PyErr_Clear(); method_result = <API key>( file_object, method_name, NULL ); if( PyErr_Occurred() ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve current offset in file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve current offset in file object.", function ); } Py_DecRef( exception_string ); goto on_error; } PyErr_Clear(); #if defined( HAVE_LONG_LONG ) safe_offset = PyLong_AsLongLong( method_result ); #else safe_offset = PyLong_AsLong( method_result ); #endif if( safe_offset == -1 ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve current offset in file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve current offset in file object.", function ); } Py_DecRef( exception_string ); goto on_error; } #if defined( HAVE_LONG_LONG ) if( safe_offset > (PY_LONG_LONG) INT64_MAX ) #else if( (off64_t) safe_offset > (off64_t) INT64_MAX ) #endif { libcerror_error_set( error, <API key>, <API key>, "%s: invalid offset value exceeds maximum.", function ); goto on_error; } *offset = (off64_t) safe_offset; Py_DecRef( method_result ); Py_DecRef( method_name ); return( 1 ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); } /* Seeks a certain offset within the file object IO handle * Returns the offset if the seek is successful or -1 on error */ off64_t <API key>( <API key> *<API key>, off64_t offset, int whence, libcerror_error_t **error ) { static char *function = "<API key>"; PyGILState_STATE gil_state = 0; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } gil_state = PyGILState_Ensure(); if( <API key>( <API key>->file_object, offset, whence, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to seek in file object.", function ); goto on_error; } if( <API key>( <API key>->file_object, &offset, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve current offset in file object.", function ); goto on_error; } PyGILState_Release( gil_state ); return( offset ); on_error: PyGILState_Release( gil_state ); return( -1 ); } /* Function to determine if a file exists * Returns 1 if file exists, 0 if not or -1 on error */ int <API key>( <API key> *<API key>, libcerror_error_t **error ) { static char *function = "<API key>"; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } if( <API key>->file_object == NULL ) { return( 0 ); } return( 1 ); } /* Check if the file is open * Returns 1 if open, 0 if not or -1 on error */ int <API key>( <API key> *<API key>, libcerror_error_t **error ) { static char *function = "<API key>"; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } if( <API key>->file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle - missing file object.", function ); return( -1 ); } /* As far as BFIO is concerned the file object is always open */ return( 1 ); } /* Retrieves the size of the file object * Make sure to hold the GIL state before calling this function * Returns 1 if successful or -1 on error */ int <API key>( PyObject *file_object, size64_t *size, libcerror_error_t **error ) { PyObject *exception_string = NULL; PyObject *exception_traceback = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; char *error_string = NULL; static char *function = "<API key>"; #if defined( HAVE_LONG_LONG ) PY_LONG_LONG safe_size = 0; #else long safe_size = 0; #endif if( file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object.", function ); return( -1 ); } if( size == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid size.", function ); return( -1 ); } method_name = PyString_FromString( "get_size" ); PyErr_Clear(); method_result = <API key>( file_object, method_name, NULL ); if( PyErr_Occurred() ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve size of file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve size of file object.", function ); } Py_DecRef( exception_string ); goto on_error; } PyErr_Clear(); #if defined( HAVE_LONG_LONG ) safe_size = <API key>( method_result ); #else safe_size = <API key>( method_result ); #endif if( safe_size == -1 ) { PyErr_Fetch( &exception_type, &exception_value, &exception_traceback ); exception_string = PyObject_Repr( exception_value ); error_string = PyString_AsString( exception_string ); if( error_string != NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve size of file object with error: %s.", function, error_string ); } else { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve size of in file object.", function ); } Py_DecRef( exception_string ); goto on_error; } #if defined( HAVE_LONG_LONG ) if( safe_size > (PY_LONG_LONG) INT64_MAX ) #else if( (size64_t) safe_size > (size64_t) INT64_MAX ) #endif { libcerror_error_set( error, <API key>, <API key>, "%s: invalid size value exceeds maximum.", function ); goto on_error; } *size = (size64_t) safe_size; Py_DecRef( method_result ); Py_DecRef( method_name ); return( 1 ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); } /* Retrieves the file size * Returns 1 if successful or -1 on error */ int <API key>( <API key> *<API key>, size64_t *size, libcerror_error_t **error ) { PyObject *method_name = NULL; static char *function = "<API key>"; off64_t current_offset = 0; PyGILState_STATE gil_state = 0; int result = 0; if( <API key> == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle.", function ); return( -1 ); } if( <API key>->file_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid file object IO handle - missing file object.", function ); return( -1 ); } gil_state = PyGILState_Ensure(); method_name = PyString_FromString( "get_size" ); PyErr_Clear(); /* Determine if the file object has the get_size method */ result = PyObject_HasAttr( <API key>->file_object, method_name ); if( result != 0 ) { if( <API key>( <API key>->file_object, size, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve size of file object.", function ); goto on_error; } } else { if( <API key>( <API key>->file_object, &current_offset, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve current offset in file object.", function ); goto on_error; } if( <API key>( <API key>->file_object, 0, SEEK_END, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to seek end of file object.", function ); goto on_error; } if( <API key>( <API key>->file_object, (off64_t *) size, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to retrieve end offset in file object.", function ); <API key>( <API key>->file_object, current_offset, SEEK_SET, NULL ); goto on_error; } if( <API key>( <API key>->file_object, current_offset, SEEK_SET, error ) != 1 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unable to seek current offset in file object.", function ); goto on_error; } } Py_DecRef( method_name ); PyGILState_Release( gil_state ); return( 1 ); on_error: if( method_name != NULL ) { Py_DecRef( method_name ); } PyGILState_Release( gil_state ); return( 1 ); }
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* at Thu Dec 02 08:28:27 2004 */ /* Compiler settings for .\OpcEnum.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef <API key> #define <API key> 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef <API key> #error this stub requires an updated version of <rpcndr.h> #endif // <API key> #ifndef __OpcEnum_h__ #define __OpcEnum_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef <API key> #define <API key> #ifdef __cplusplus typedef class OpcServerList OpcServerList; #else typedef struct OpcServerList OpcServerList; #endif /* __cplusplus */ #endif /* <API key> */ /* header files for imported files */ #include "opccomn.h" #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); #ifndef <API key> #define <API key> /* library OpcEnumLib */ /* [helpstring][version][uuid] */ EXTERN_C const IID LIBID_OpcEnumLib; EXTERN_C const CLSID CLSID_OpcServerList; #ifdef __cplusplus class DECLSPEC_UUID("<API key>") OpcServerList; #endif #endif /* <API key> */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
#include <common.h> #include <types.h> #include "pycreg_error.h" #include "pycreg_libcerror.h" #include "pycreg_integer.h" #include "pycreg_python.h" /* Creates a new signed integer object from a 64-bit value * Returns a Python object if successful or NULL on error */ PyObject *<API key>( int64_t value_64bit ) { PyObject *integer_object = NULL; static char *function = "<API key>"; #if defined( HAVE_LONG_LONG ) if( ( value_64bit < (int64_t) LLONG_MIN ) || ( value_64bit > (int64_t) LLONG_MAX ) ) { PyErr_Format( PyExc_OverflowError, "%s: 64-bit value out of bounds.", function ); return( NULL ); } integer_object = PyLong_FromLongLong( (long long) value_64bit ); #else if( current_offset > (off64_t) LONG_MAX ) { PyErr_Format( PyExc_OverflowError, "%s: 64-bit value out of bounds.", function ); return( NULL ); } integer_object = PyLong_FromLong( (long) value_64bit ); #endif return( integer_object ); } /* Creates a new unsigned integer object from a 64-bit value * Returns a Python object if successful or NULL on error */ PyObject *<API key>( uint64_t value_64bit ) { PyObject *integer_object = NULL; static char *function = "<API key>"; #if defined( HAVE_LONG_LONG ) if( value_64bit > (uint64_t) ULLONG_MAX ) { PyErr_Format( PyExc_OverflowError, "%s: 64-bit value exceeds maximum.", function ); return( NULL ); } integer_object = <API key>( (long long) value_64bit ); #else if( value_64bit > (uint64_t) ULONG_MAX ) { PyErr_Format( PyExc_OverflowError, "%s: 64-bit value exceeds maximum.", function ); return( NULL ); } integer_object = <API key>( (long) value_64bit ); #endif return( integer_object ); } /* Copies a Python int or long object to a signed 64-bit value * Returns 1 if successful or -1 on error */ int <API key>( PyObject *integer_object, int64_t *value_64bit, libcerror_error_t **error ) { static char *function = "<API key>"; int result = 0; #if defined( HAVE_LONG_LONG ) PY_LONG_LONG long_value = 0; #else long long_value = 0; #endif if( integer_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid integer object.", function ); return( -1 ); } PyErr_Clear(); result = PyObject_IsInstance( integer_object, (PyObject *) &PyLong_Type ); if( result == -1 ) { pycreg_error_fetch( error, <API key>, <API key>, "%s: unable to determine if integer object is of type long.", function ); return( -1 ); } else if( result != 0 ) { PyErr_Clear(); #if defined( HAVE_LONG_LONG ) long_value = PyLong_AsLongLong( integer_object ); #else long_value = PyLong_AsLong( integer_object ); #endif } #if PY_MAJOR_VERSION < 3 if( result == 0 ) { PyErr_Clear(); result = PyObject_IsInstance( integer_object, (PyObject *) &PyInt_Type ); if( result == -1 ) { pycreg_error_fetch( error, <API key>, <API key>, "%s: unable to determine if integer object is of type int.", function ); return( -1 ); } else if( result != 0 ) { PyErr_Clear(); long_value = PyInt_AsLong( integer_object ); } } #endif /* PY_MAJOR_VERSION < 3 */ if( result == 0 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unsupported integer object type.", function ); return( -1 ); } if( PyErr_Occurred() ) { pycreg_error_fetch( error, <API key>, <API key>, "%s: unable to convert integer object to long.", function ); return( -1 ); } #if defined( HAVE_LONG_LONG ) && ( SIZEOF_LONG_LONG > 8 ) if( ( long_value < (PY_LONG_LONG) INT64_MIN ) || ( long_value > (PY_LONG_LONG) INT64_MAX ) ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid long value out of bounds.", function ); return( -1 ); } #elif ( SIZEOF_LONG > 8 ) if( ( long_value > (long) INT64_MIN ) || ( long_value > (long) INT64_MAX ) ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid long value out of bounds.", function ); return( -1 ); } #endif *value_64bit = (int64_t) long_value; return( 1 ); } /* Copies a Python int or long object to an unsigned 64-bit value * Returns 1 if successful or -1 on error */ int <API key>( PyObject *integer_object, uint64_t *value_64bit, libcerror_error_t **error ) { static char *function = "<API key>"; int result = 0; #if defined( HAVE_LONG_LONG ) PY_LONG_LONG long_value = 0; #else long long_value = 0; #endif if( integer_object == NULL ) { libcerror_error_set( error, <API key>, <API key>, "%s: invalid integer object.", function ); return( -1 ); } PyErr_Clear(); result = PyObject_IsInstance( integer_object, (PyObject *) &PyLong_Type ); if( result == -1 ) { pycreg_error_fetch( error, <API key>, <API key>, "%s: unable to determine if integer object is of type long.", function ); return( -1 ); } else if( result != 0 ) { PyErr_Clear(); #if defined( HAVE_LONG_LONG ) long_value = <API key>( integer_object ); #else long_value = <API key>( integer_object ); #endif } #if PY_MAJOR_VERSION < 3 if( result == 0 ) { PyErr_Clear(); result = PyObject_IsInstance( integer_object, (PyObject *) &PyInt_Type ); if( result == -1 ) { pycreg_error_fetch( error, <API key>, <API key>, "%s: unable to determine if integer object is of type int.", function ); return( -1 ); } else if( result != 0 ) { PyErr_Clear(); #if defined( HAVE_LONG_LONG ) long_value = <API key>( integer_object ); #else long_value = <API key>( integer_object ); #endif } } #endif /* PY_MAJOR_VERSION < 3 */ if( result == 0 ) { libcerror_error_set( error, <API key>, <API key>, "%s: unsupported integer object type.", function ); return( -1 ); } if( PyErr_Occurred() ) { pycreg_error_fetch( error, <API key>, <API key>, "%s: unable to convert integer object to long.", function ); return( -1 ); } #if defined( HAVE_LONG_LONG ) #if ( SIZEOF_LONG_LONG > 8 ) if( ( long_value < (PY_LONG_LONG) 0 ) || ( long_value > (PY_LONG_LONG) UINT64_MAX ) ) #else if( long_value < (PY_LONG_LONG) 0 ) #endif { libcerror_error_set( error, <API key>, <API key>, "%s: invalid long value out of bounds.", function ); return( -1 ); } #else #if ( SIZEOF_LONG > 8 ) if( ( long_value < (long) 0 ) || ( long_value > (long) UINT64_MAX ) ) #else if( long_value < (PY_LONG_LONG) 0 ) #endif { libcerror_error_set( error, <API key>, <API key>, "%s: invalid long value out of bounds.", function ); return( -1 ); } #endif *value_64bit = (uint64_t) long_value; return( 1 ); }
#include "tool.h" using namespace oi; /*! * \brief Tool::Tool * \param parent */ Tool::Tool(QWidget *parent) : QWidget(parent){ } /*! * \brief Tool::~Tool */ Tool::~Tool(){ } /*! * \brief Tool::getMetaData * \return */ const PluginMetaData &Tool::getMetaData() const{ return this->metaData; } /*! * \brief Tool::getToolType * \return */ const ToolTypes &Tool::getToolType() const{ return this->toolType; } /*! * \brief Tool::getJob * \return */ const QPointer<OiJob> &Tool::getJob() const{ return this->job; } /*! * \brief Tool::setJob * \param job */ void Tool::setJob(const QPointer<OiJob> &job){ this->job = job; } /*! * \brief Tool::closeEvent * \param event */ void Tool::closeEvent(QCloseEvent *event){ event->accept(); } /*! * \brief Tool::customXmlRequest * \param request */ void Tool::customXmlRequest(const QPointer<OiRequestResponse> &request){ emit this->sendMessage(QString("No custom XML request implementation"), eCriticalMessage, eMessageBoxMessage); } /*! * \brief Tool::<API key> * \param key */ void Tool::<API key>(const Qt::Key &key){ emit this->sendMessage(QString("No watch window key pressed implementation"), eCriticalMessage, eMessageBoxMessage); } void Tool::setCurrentJob(const QPointer<OiJob> &job) { } /*! * \brief Tool::init */ void Tool::init(){ this->toolType = eUnknownTool; } bool Tool::saveProjectEnabled() { return true; }
package org.sonar.jpa.session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.persistence.Database; import org.sonar.core.persistence.DatabaseVersion; import org.sonar.core.persistence.dialect.Dialect; import javax.persistence.EntityManager; import javax.persistence.<API key>; import javax.persistence.Persistence; import java.util.Map; import java.util.Properties; public abstract class <API key> implements DatabaseConnector { protected static final Logger LOG = LoggerFactory.getLogger(<API key>.class); protected Database database; private <API key> factory = null; protected <API key>(Database database) { this.database = database; } public void start() { LOG.info("Initializing Hibernate"); factory = <API key>(); } public void stop() { if (factory != null && factory.isOpen()) { factory.close(); factory = null; } database = null; } public <API key> <API key>() { return factory; } protected <API key> <API key>() { // other settings are stored into /META-INF/persistence.xml Properties props = database.<API key>(); <API key>(props); return Persistence.<API key>("sonar", props); } private void <API key>(Properties props) { if (LOG.isDebugEnabled()) { for (Map.Entry<Object, Object> entry : props.entrySet()) { LOG.debug(entry.getKey() + ": " + entry.getValue()); } } } public EntityManager createEntityManager() { return factory.createEntityManager(); } public final int getDatabaseVersion() { throw new <API key>("Moved to " + DatabaseVersion.class.getCanonicalName()); } public final Dialect getDialect() { return database.getDialect(); } }
/** * @fileoverview SugarCrm module field. */ goog.provide('ydn.crm.su.ui.field.<API key>'); goog.require('ydn.crm.su.ui.field.FieldRenderer'); /** * Create a new module record field. * @constructor * @struct * @extends {ydn.crm.su.ui.field.FieldRenderer} */ ydn.crm.su.ui.field.<API key> = function() { goog.base(this); }; goog.inherits(ydn.crm.su.ui.field.<API key>, ydn.crm.su.ui.field.FieldRenderer); goog.addSingletonGetter(ydn.crm.su.ui.field.<API key>); /** * @define {boolean} debug flag. */ ydn.crm.su.ui.field.<API key>.DEBUG = false; /** * @inheritDoc */ ydn.crm.su.ui.field.<API key>.prototype.createDom = function(field) { var el = goog.base(this, 'createDom', field); /** * @type {ydn.crm.su.model.Field} */ var model = field.getModel(); var dom = field.getDomHelper(); var label = model.getLabel(); var calculated = model.isCalculated(); // console.log(label, type, calculated); var id = goog.ui.IdGenerator.getInstance().getNextUniqueId(); var ele_value = dom.createDom('input', { 'type': 'checkbox', 'id': id }); var ele_label = dom.createDom('label', {'for': id}, label); if (calculated) { ele_value.setAttribute('disabled', 'true'); } ele_value.classList.add(ydn.crm.su.ui.field.FieldRenderer.CSS_CLASS_VALUE); // ele_value.setAttribute('disabled', '1'); el.appendChild(ele_value); el.appendChild(ele_label); return el; }; /** * @inheritDoc */ ydn.crm.su.ui.field.<API key>.prototype.refresh = function(ctrl) { var ele_field = ctrl.getElement(); var model = ctrl.getModel(); goog.style.setElementShown(ele_field, !!model); if (!model) { return; } var value = model.getField(); var is_def = goog.isString(value) ? !goog.string.isEmpty(value) : goog.isDefAndNotNull(value); // console.log(model.getFieldName() + ' ' + value); var ele_value = ele_field.querySelector('.' + ydn.crm.su.ui.field.FieldRenderer.CSS_CLASS_VALUE); if (model.getType() == 'bool' && !goog.isBoolean(value)) { if (value == '1' || value == 'on' || value == 'true') { value = true; } else { value = false; } } ele_value.checked = value; if (ydn.crm.su.ui.field.<API key>.DEBUG) { window.console.log(model.getFieldName(), model.getType(), value); } if (is_def) { ele_field.classList.remove(ydn.crm.su.ui.field.FieldRenderer.CSS_CLASS_EMPTY); } else { ele_field.classList.add(ydn.crm.su.ui.field.FieldRenderer.CSS_CLASS_EMPTY); } if (!model.getGroupName() && ctrl.getSetting().getNormallyHide()) { ele_field.classList.add(ydn.crm.ui.<API key>); } }; /** * Collect data. * @param {ydn.crm.su.ui.field.Field} ctrl * @return {*} return value of the element. */ ydn.crm.su.ui.field.<API key>.prototype.collectValue = function(ctrl) { var ele = ctrl.getContentElement(); var ele_value = ele.querySelector('.' + ydn.crm.su.ui.field.FieldRenderer.CSS_CLASS_VALUE); return ele_value.checked; // goog.dom.forms get value incorrect. }; /** * Simulate user edit. * @param {ydn.crm.su.ui.field.Field} ctrl * @param {ydn.crm.su.RecordValue} value value to set. */ ydn.crm.su.ui.field.<API key>.prototype.simulateEdit = function(ctrl, value) { var ele = ctrl.getContentElement(); var ele_value = ele.querySelector('.' + ydn.crm.su.ui.field.FieldRenderer.CSS_CLASS_VALUE); var model = ctrl.getModel(); if (model.getType() == 'bool' && !goog.isBoolean(value)) { if (value == '1' || value == 'on' || value == 'true') { value = true; } else { value = false; } } ele_value.checked = value; };
package io.github.agentsoz.abmjadex.central_organizer; import io.github.agentsoz.abmjadex.agent.StepManagerPlan; import io.github.agentsoz.abmjadex.central_organizer.<API key>.Methods; import io.github.agentsoz.abmjadex.miscellaneous.ABMBDILoggerSetter; import io.github.agentsoz.abmjadex.super_central.<API key>; import io.github.agentsoz.bdiabm.<API key>; import io.github.agentsoz.bdiabm.<API key>; import io.github.agentsoz.bdiabm.data.ActionContainer; import io.github.agentsoz.bdiabm.data.<API key>; import io.github.agentsoz.bdiabm.data.AgentDataContainer; import io.github.agentsoz.bdiabm.data.AgentState; import io.github.agentsoz.bdiabm.data.AgentStateList; import io.github.agentsoz.bdiabm.data.PerceptContainer; import jadex.bdi.runtime.IBDIExternalAccess; import jadex.bdi.runtime.IBDIInternalAccess; import jadex.bdi.runtime.Plan; import jadex.bridge.IComponentStep; import jadex.bridge.IInternalAccess; import jadex.bridge.service.RequiredServiceInfo; import jadex.bridge.service.search.SServiceProvider; import jadex.bridge.service.types.cms.<API key>; import jadex.bridge.service.types.cms.<API key>; import jadex.commons.future.IFuture; import jadex.commons.future.IResultListener; import jadex.commons.future.ISuspendable; import jadex.commons.transformation.annotations.Classname; import jadex.extension.envsupport.environment.IEnvironmentSpace; import jadex.extension.envsupport.environment.ISpaceObject; import java.net.<API key>; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.logging.Logger; public class StartPlan extends Plan { /** *This is the plan to start a CentralOrganizer(CO). *This holds an instance of CO's server. *It will create and also register the server to RMIRegistry. */ private static final long serialVersionUID = -<API key>; private final static Logger LOGGER = Logger.getLogger(StartPlan.class.getName()); BDIServer server; IEnvironmentSpace envSpace; private String superCentralAddress; private String address; private int co_port = 1099; private int sc_port = 1099; private String sc_host = "localhost"; private String sc_name = "supercentral"; public StartPlan () { super(); ABMBDILoggerSetter.setup(LOGGER); //Get the super central organizer address //all of this data are written in properties file, and parsed into xml by //<API key> IEnvironmentSpace space = (IEnvironmentSpace)getBeliefbase().getBelief("environment").getFact(); co_port = (Integer) space.getProperty("co_port"); sc_port = (Integer) space.getProperty("sc_port"); sc_host = (String) space.getProperty("sc_host"); sc_name = (String) space.getProperty("sc_name"); superCentralAddress = "rmi://"+sc_host+":"+sc_port+"/SuperCentralJadex/"+sc_name; //Creation of this CO address String uniqueID = <API key>().toString(); uniqueID = uniqueID.split("\\.")[1]; address = "rmi://localhost:"+co_port+"/CentralJadex/"+uniqueID; } @Override public void body() { try { server = new BDIServer(); IEnvironmentSpace space = (IEnvironmentSpace)getBeliefbase().getBelief("environment").getFact(); space.setProperty("server", server); //Register CentralOrganizer in rmiregistry Naming.rebind(address, server); LOGGER.info("Central Server created and registered :" + address); //Register CentralOrganizer to SuperCentral server.<API key>(); } catch (RemoteException e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } catch (<API key> e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } } public class BDIServer extends UnicastRemoteObject implements <API key>, Runnable, ISuspendable { /** * This is the server instance of a CO. * It is the gate for external entities to communicate with a CO. */ private static final long serialVersionUID = -<API key>; private boolean isInControl = false; private boolean isRegistered = false; private String thisAddress; public final static int SUPER_CENTRAL = 1; public final static int REPAST = 2; public final static int MINE = 3; private <API key> abmServer; private <API key> thisServer = this; private <API key> scServer = null; public BDIServer () throws RemoteException { super(); thisAddress = address; } @Override public boolean equals (Object o) { boolean isEquals = false; if (o.getClass().equals(this.getClass())) { BDIServer x = (BDIServer)o; if (x.thisAddress.equals(this.thisAddress)) isEquals = true; } return isEquals; } public boolean isInControl() { return isInControl; } public void setControlStatus (final boolean isInControlState) { getExternalAccess().scheduleStep(new IComponentStep<Void>() { @Classname("StartCentral") public IFuture<Void> execute(IInternalAccess ia) { isInControl = isInControlState; return IFuture.DONE; } }); } // public String getAddress (int type) // String value = null; // if (type == SUPER_CENTRAL) // value = superCentralAddress; // else if(type == REPAST) // value = repastAddress; // else if(type == MINE) // value = address; // return value; public boolean start (final AgentDataContainer ADContainer, final AgentStateList agentList, final <API key> abmServerInstance) throws RemoteException { LOGGER.info("CO started"); getExternalAccess().scheduleStep(new IComponentStep<Void>() { @Classname("StartCentral") public IFuture<Void> execute(IInternalAccess ia) { isInControl = true; IBDIInternalAccess scope = (IBDIInternalAccess)ia; IEnvironmentSpace space = (IEnvironmentSpace)scope.getBeliefbase().getBelief("environment").getFact(); // //Set up address info setAbmServer(abmServerInstance); // repastAddress = abmAddress; //copy the BDIAPContainer with the data from ABM APContainer space.setProperty("agentDataContainer", ADContainer); //Set the space property up space.setProperty("agentStateList", agentList); <API key>(space, "agentStateList"); //If there are no agents being born, then we need to check by ourself this fact. checkAllIdle(space); return IFuture.DONE; } }); return true; } /** * Procedures to create the BDI agent * @param space */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void <API key>(IEnvironmentSpace space, String source) { AgentDataContainer ADContainer = (AgentDataContainer)space.getProperty("agentDataContainer"); AgentStateList agentList = (AgentStateList)space.getProperty(source); ArrayList agentTypeList = (ArrayList)space.getProperty("agentTypeList"); //For each agent listed from ABM create a corresponding agent in BDI, with initial percept and action for (AgentState agentState: agentList) { //Extracting the agent type String agentID = agentState.getID(); String agentType = ((agentID.split("@"))[0]).split("\\.")[1]; //Collecting agentType data if (!agentTypeList.contains(agentType)) { agentTypeList.add(agentType); } //Creating and initializing the corresponding BDI agent ISpaceObject agent = space.createSpaceObject(agentType, null, null); agent.setProperty("agentID", agentID); agent.setProperty("actionContainer", ADContainer.getOrCreate(agentID).getActionContainer()); agent.setProperty("perceptContainer", ADContainer.getOrCreate(agentID).getPerceptContainer()); } } public void takeControl (final AgentDataContainer agentDataContainer) throws RemoteException { //<API key>.println(); LOGGER.info(" getExternalAccess().scheduleStep(new IComponentStep<Void>() { @SuppressWarnings("rawtypes") @Classname("translate") public IFuture<Void> execute(IInternalAccess ia) { isInControl = true; IBDIInternalAccess scope = (IBDIInternalAccess)ia; IEnvironmentSpace space = (IEnvironmentSpace)scope.getBeliefbase().getBelief("environment").getFact(); //Update BDI APContainer space.setProperty("agentDataContainer", agentDataContainer); /* * Create New Agent * First : Update the central agentStateList, as if the agent being born * is directly going to idle, then the availability of it is being registered * to the central data before that happens is crucial */ AgentStateList agentToBeBornList = (AgentStateList)space.getProperty("agentToBeBornList"); AgentStateList <API key> = (AgentStateList)space.getProperty("agentStateList"); for (AgentState agentState : agentToBeBornList) { <API key>.add(agentState); } space.setProperty("agentStateList", <API key>); <API key>(space,"agentToBeBornList"); //Per Object ArrayList agentTypeList = (ArrayList)space.getProperty("agentTypeList"); for (Object agentType : agentTypeList) { ISpaceObject[] objects = space.<API key>((String)agentType); for(ISpaceObject object : objects) { String agentID = (String)object.getProperty("agentID"); //Only those who is not being born in this step that gets to be examined if (!agentToBeBornList.contains(new AgentState(agentID))) { <API key> <API key> = agentDataContainer.get(agentID); //Compare new and old value before updating value ActionContainer newActionContainer = <API key>.getActionContainer(); ActionContainer oldActionContainer = (ActionContainer)object.getProperty("actionContainer"); boolean isActionEqual = <API key>(newActionContainer, oldActionContainer); PerceptContainer newPerceptContainer = <API key>.getPerceptContainer(); boolean isNewPerceptEmpty = newPerceptContainer.isEmpty(); //Update to new value object.setProperty("actionContainer", newActionContainer); object.setProperty("perceptContainer", newPerceptContainer); //Decide to wake or let agent still idle, using the previous comparison int agentRunningState; if (isActionEqual && isNewPerceptEmpty) { //don't wake the agent } else { if(isActionEqual && !isNewPerceptEmpty) { agentRunningState = StepManagerPlan.<API key>; } else if (!isActionEqual && !isNewPerceptEmpty) { agentRunningState = StepManagerPlan.RUN_ACTION_PERCEPT; } else { agentRunningState = StepManagerPlan.<API key>; } //Update central state into awake AgentStateList agentStateList = (AgentStateList)space.getProperty("agentStateList"); //An Exception could be thrown because the agentID is not //exist anymore in the list but still exist as an object in Space. //The reason is the destroySpaceObject(Obj) function not working. try { agentStateList.setState(agentID, false); wakeAgent(space, (<API key>) object.getProperty(ISpaceObject.PROPERTY_OWNER), agentRunningState); } catch (Exception e) {}; } } } } //Emptied up the request of new agent creation from Repast's latest turn of control. agentToBeBornList.clear(); space.setProperty("agentToBeBornList", agentToBeBornList); checkAllIdle(space); return IFuture.DONE; } }); } /** * Whether actionContainer a and b are equals * @param a * @param b * @return */ private boolean <API key>(ActionContainer a, ActionContainer b) { boolean isEqual = true; if(a.size() == b.size()) { Set<String> aIDSet = a.actionIDSet(); Set<String> bIDSet = b.actionIDSet(); for(String aID : aIDSet) { boolean isFound = false; for(String bID : bIDSet) { boolean isIDEqual = aID.equals(bID); if(isIDEqual) { boolean isStateEqual = (a.get(aID).getState() == (b.get(bID).getState())); if (isStateEqual) { isFound = true; break; } } } if (!isFound) { isEqual = false; break; } } } return isEqual; } /** * The procedures to unidled an Agent * @param space * @param agent * @param agentState * The state of when the agent awaken */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void wakeAgent (final IEnvironmentSpace space, final <API key> agent, final int agentState) { SServiceProvider.getService(space.getExternalAccess().getServiceProvider(), <API key>.class, RequiredServiceInfo.SCOPE_PLATFORM) .addResultListener(new IResultListener() { public void exceptionOccurred(Exception exception) { exception.printStackTrace(); } public void resultAvailable(Object result) { IFuture fut = ((<API key>)result).getExternalAccess(agent.getName()); fut.addResultListener(new IResultListener() { public void exceptionOccurred(Exception exception) { } public void resultAvailable(Object result) { final IBDIExternalAccess exta = (IBDIExternalAccess)result; exta.scheduleStep(new IComponentStep<Void>() { @Classname("set") public IFuture<Void> execute(IInternalAccess ia) { IBDIInternalAccess scope = (IBDIInternalAccess)ia; Object fact = scope.getBeliefbase().getBelief("agentState").getFact(); if (fact.equals(StepManagerPlan.IDLE)) { scope.getBeliefbase().getBelief("agentState").setFact(agentState); } return IFuture.DONE; } }); } }); } }); } @Override public void createAgents (final String[] agentIDs) throws RemoteException { getExternalAccess().scheduleStep(new IComponentStep<Void>() { @Classname("createAgents") public IFuture<Void> execute(IInternalAccess ia) { IBDIInternalAccess scope = (IBDIInternalAccess)ia; IEnvironmentSpace space = (IEnvironmentSpace)scope.getBeliefbase().getBelief("environment").getFact(); AgentStateList agentToBeBornList = (AgentStateList)space.getProperty("agentToBeBornList"); for (int i = 0; i < agentIDs.length; i++) { AgentState newAgent = new AgentState(agentIDs[i]); agentToBeBornList.add(newAgent); } space.setProperty("agentToBeBornList", agentToBeBornList); return IFuture.DONE; } }); } /** * Procedures to check whether all of * the agent in the EnvironmentSpace are idle * @param space */ private void checkAllIdle (IEnvironmentSpace space) { /* * Server need to monitor its own condition whether in Control or not. * This is to prevent if there is a race condition and resulted in multiple calls * to Repast's server. * (This flag method works as long as there are no interruption point, we * utilize Jadex's schedule. This is also works while the racing we are prevent from * shall all be in the same platform / no networks delay effect..) */ if (isInControl) { AgentStateList agentStateList = (AgentStateList)space.getProperty("agentStateList"); boolean allIdle = true; for (AgentState agentState : agentStateList) { if (!agentState.isIdle()) { allIdle = false; } } if (allIdle) { isInControl = false; envSpace = space; <API key> myServer = (<API key>) thisServer; <API key> superCentral = scServer; <API key> extComm = new <API key>(superCentral, myServer, Methods.INFORM, null); extComm.start(); } } } @Override public void run() { if (!isRegistered) { this.<API key>(); } } @Override public void confirm(<API key> callerServer, Events eventType, boolean isSuccessful, final Object[] parameters) throws RemoteException { if (eventType.equals(Events.REGISTER)) { if (callerServer.equals(scServer)) { isRegistered = isSuccessful; if (isRegistered == false) { Thread x = new Thread (this); x.start(); } } } //TODO: UNREGISTER event confirmation procedure } /** * Method for searching on super central */ public void <API key> () { if (isRegistered == false) { superCentralAddress = "rmi://"+sc_host+":"+sc_port+"/SuperCentralJadex/"+sc_name; // Scanner keyboard = new Scanner(System.in); // try // String[] list; // String[] rawList = Naming.list("rmi://"+SC_HOST+":"+SC_PORT+"/SuperCentralJadex/"); // String[] tempList = new String[rawList.length]; // int x = 0; // for (int j = 0; j < rawList.length; j++) // if (rawList[j].contains("SuperCentralJadex")) // tempList[x] = (rawList[j]); // list = new String[x]; // for (;x > 0;x--) // list[x-1] = tempList[x-1]; // if (list.length > 0) // System.out.println("Choose SuperCentral to register in :"); // for(int i = 0; i < list.length; i++) // System.out.println(i +". "+list[i]); // System.out.print("Choose the available Super Central to be registered to: "); // if (keyboard.hasNextInt()) // int choice = keyboard.nextInt(); // if (choice >= 0 && choice < list.length) // superCentralAddress = list[choice]; // this.<API key>(); // else // System.out.println("Choice is out of bound. Press Enter to Search again..."); // keyboard.hasNext(); // else // System.out.println("Invalid input. Press Enter to Search again..."); // keyboard.hasNext(); // else // System.out.println("SuperCentral not Exists. Press Enter to Search again..."); // keyboard.hasNext(); // } while (list.length == 0); // } catch (<API key> e) { // e.printStackTrace(); // } catch (RemoteException e) { // e.printStackTrace(); } } private void <API key> () { if (isRegistered == false) { try { scServer = (<API key>)Naming.lookup(superCentralAddress); scServer.<API key>(<API key>.REGISTER, this); LOGGER.info("Register to " + superCentralAddress); } catch (<API key> e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } catch (RemoteException e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } catch (NotBoundException e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } } } @Override public Object[] retrieveData(final <API key> confirmator) throws RemoteException { getExternalAccess().scheduleStep(new IComponentStep<Void>() { @Classname("retrieveData") public IFuture<Void> execute(IInternalAccess ia) { IBDIInternalAccess scope = (IBDIInternalAccess)ia; IEnvironmentSpace space = (IEnvironmentSpace)scope.getBeliefbase().getBelief("environment").getFact(); Object[] params = new Object[1]; params[0] = space.getProperty("agentDataContainer"); try { LOGGER.info("--SENDING DATA TO SC confirmator.confirm((<API key>)thisServer, Events.RETRIEVE, true, params); } catch (RemoteException e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } return IFuture.DONE; } }); return null; } @Override public void killAgents(final String[] agentIDs) throws RemoteException { IFuture<Void> fut = getExternalAccess().scheduleStep(new IComponentStep<Void>() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Classname("killAgents") public IFuture<Void> execute(IInternalAccess ia) { IBDIInternalAccess scope = (IBDIInternalAccess)ia; IEnvironmentSpace space = (IEnvironmentSpace)scope.getBeliefbase().getBelief("environment").getFact(); Map mParameters = new HashMap(); mParameters.put("agentIDs", agentIDs); KillAgentsAction action = new KillAgentsAction (); action.perform(mParameters, space); return IFuture.DONE; } }); fut.get(this); } @Override public Object getMonitor() { return null; } public <API key> getAbmServer() { return abmServer; } public void setAbmServer(<API key> abmServer) { this.abmServer = abmServer; } public <API key> getSCServer() { return scServer; } public void setSCServer(<API key> scServer) { this.scServer = scServer; } @Override public void terminateProgram() throws RemoteException { try { //UnRegister CentralOrganizer in rmiregistry Naming.unbind(address); LOGGER.info("Central Server unbinding :" + address); } catch (RemoteException e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } catch (<API key> e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } catch (NotBoundException e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } } @Override public void resume(IFuture<?> arg0) { this.notify(); } @Override public void suspend(IFuture<?> arg0, long arg1) { synchronized (this) { try { this.wait(); } catch (<API key> e) { e.printStackTrace(); LOGGER.severe(e.getMessage()); } } } } }
package org.sonar.server.qualitygate.notification; import javax.annotation.CheckForNull; import org.sonar.api.notifications.Notification; public class <API key> extends Notification { public <API key>() { super("alerts"); } @CheckForNull public String getProjectKey() { return getFieldValue("projectKey"); } }
#ifndef _Ltas_h_ #define _Ltas_h_ #include "Spectrum.h" #include "Sound.h" #include "PointProcess.h" #include "Collection.h" Thing_define (Ltas, Vector) { // overridden methods: protected: virtual void v_info (); virtual int v_domainQuantity () { return <API key>; } virtual double <API key> (double value, long ilevel, int unit); virtual double <API key> (double value, long ilevel, int unit); }; /* Attributes: xmin // Minimum frequency (Hz). xmax > xmin // Maximum frequency (Hz). nx >= 1 // Number of bands. dx > 0.0 // Band width (Hz). x1 // Centre of first band (Hz). ymin, ymax, ny, dy, y1 = 1 z [1] [1..nx] // The intensity per band, in db/Hz. */ Ltas Ltas_create (long nx, double dx); /* Function: create an Ltas, or NULL if out of memory. Preconditions: nx >= 1; dx > 0.0; Postconditions: my xmin == 0; my ymin == 1; my xmax == nx * dx; my ymax == 1; my nx == nx; my ny == 1; my dx == dx; my dy == 1; my x1 == 0.5 * dx; my y1 == 1; my z [1] [1..nx] == 1e-4; // straight tube, area 1 cm2. */ void Ltas_draw (Ltas me, Graphics g, double fmin, double fmax, double minimum, double maximum, int garnish, const wchar_t *method); Matrix Ltas_to_Matrix (Ltas me); Ltas Matrix_to_Ltas (Matrix me); Ltas Ltases_merge (Collection ltases); Ltas Ltases_average (Collection ltases); Ltas <API key> (Ltas me, double fmin, double fmax); Ltas <API key> (Ltas me, double fmin, double fmax); /* Direct computations. */ Ltas Spectrum_to_Ltas (Spectrum me, double bandwidth); Ltas <API key> (Spectrum me); Ltas <API key> (PointProcess pulses, Sound sound, double maximumFrequency, double bandWidth, double shortestPeriod, double longestPeriod, double maximumPeriodFactor); Ltas <API key> (PointProcess pulses, Sound sound, long maximumHarmonic, double shortestPeriod, double longestPeriod, double maximumPeriodFactor); /* Shortcuts. */ Ltas Sound_to_Ltas (Sound me, double bandwidth); Ltas <API key> (Sound sound, double minimumPitch, double maximumPitch, double maximumFrequency, double bandWidth, double shortestPeriod, double longestPeriod, double maximumPeriodFactor); double Ltas_getSlope (Ltas me, double f1min, double f1max, double f2min, double f2max, int averagingUnits); double <API key> (Ltas me, double environmentMin, double environmentMax, double peakMin, double peakMax, int averagingUnits); /* End of file Ltas.h */ #endif
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Core3: /Users/victor/git/Core3Mda/MMOCoreORB/src/server/zone/objects/creature/aigroup/<API key>.cpp Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Core3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="<API key>.html">src</a></li><li class="navelem"><a class="el" href="<API key>.html">server</a></li><li class="navelem"><a class="el" href="<API key>.html">zone</a></li><li class="navelem"><a class="el" href="<API key>.html">objects</a></li><li class="navelem"><a class="el" href="<API key>.html">creature</a></li><li class="navelem"><a class="el" href="<API key>.html">aigroup</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title"><API key>.cpp</div> </div> </div><!--header <div class="contents"> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;</div> <div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="_lair_group_8h.html">LairGroup.h</a>&quot;</span></div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 15 2013 17:28:47 for Core3 by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
package com.liferay.adaptive.media.demo.data.creator; import com.liferay.adaptive.media.image.configuration.<API key>; import java.io.IOException; import java.util.Collection; public interface <API key> { /** * Creates a collection of {@link <API key>} * configurations based on the * {@link <API key>} enum * * @param companyId ID of the company where the configurations will be * created * @return a list of the configurations */ public Collection<<API key>> create( long companyId) throws IOException; /** * Creates a {@link <API key>} for a company * * @param companyId ID of the company where the configuration will be * created * @param <API key> the configuration to * create * @return the configuration */ public <API key> create( long companyId, <API key> <API key>) throws IOException; public void delete() throws IOException; }
/** * Provides some function to use complex queries with item list * * @module complex_queries */ // define([module_name], [dependencies], module); (function (dependencies, module) { "use strict"; if (typeof define === 'function' && define.amd) { return define(dependencies, module); } if (typeof exports === 'object') { return module(exports); } window.complex_queries = {}; module(window.complex_queries); }(['exports'], function (to_export) { "use strict"; function _export(key, value) { Object.defineProperty(to_export, key, { "configurable": false, "enumerable": true, "writable": false, "value": value }); } /** * Parse a text request to a json query object tree * * @param {String} string The string to parse * @return {Object} The json query tree */ function parseStringToObject(string) { /* Default template driver for JS/CC generated parsers running as browser-based JavaScript/ECMAScript applications. WARNING: This parser template will not run as console and has lesser features for debugging than the console derivates for the various JavaScript platforms. Features: - Parser trace messages - Integrated panic-mode error recovery Written 2007, 2008 by Jan Max Meyer, J.M.K S.F. Software Technologies This is in the public domain. */ var <API key> = false; var NODEJS__dbg_string = new String(); function __NODEJS_dbg_print( text ) { NODEJS__dbg_string += text + "\n"; } function __NODEJS_lex( info ) { var state = 0; var match = -1; var match_pos = 0; var start = 0; var pos = info.offset + 1; do { pos state = 0; match = -2; start = pos; if( info.src.length <= start ) return 19; do { switch( state ) { case 0: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 8 ) || ( info.src.charCodeAt( pos ) >= 10 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || info.src.charCodeAt( pos ) == 59 || ( info.src.charCodeAt( pos ) >= 63 && info.src.charCodeAt( pos ) <= 64 ) || ( info.src.charCodeAt( pos ) >= 66 && info.src.charCodeAt( pos ) <= 77 ) || ( info.src.charCodeAt( pos ) >= 80 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 9 ) state = 2; else if( info.src.charCodeAt( pos ) == 40 ) state = 3; else if( info.src.charCodeAt( pos ) == 41 ) state = 4; else if( info.src.charCodeAt( pos ) == 60 || info.src.charCodeAt( pos ) == 62 ) state = 5; else if( info.src.charCodeAt( pos ) == 34 ) state = 11; else if( info.src.charCodeAt( pos ) == 79 ) state = 12; else if( info.src.charCodeAt( pos ) == 32 ) state = 13; else if( info.src.charCodeAt( pos ) == 61 ) state = 14; else if( info.src.charCodeAt( pos ) == 65 ) state = 18; else if( info.src.charCodeAt( pos ) == 78 ) state = 19; else state = -1; break; case 1: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else state = -1; match = 10; match_pos = pos; break; case 2: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else state = -1; match = 1; match_pos = pos; break; case 3: state = -1; match = 3; match_pos = pos; break; case 4: state = -1; match = 4; match_pos = pos; break; case 5: if( info.src.charCodeAt( pos ) == 61 ) state = 14; else state = -1; match = 11; match_pos = pos; break; case 6: state = -1; match = 8; match_pos = pos; break; case 7: state = -1; match = 9; match_pos = pos; break; case 8: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else state = -1; match = 6; match_pos = pos; break; case 9: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else state = -1; match = 5; match_pos = pos; break; case 10: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else state = -1; match = 7; match_pos = pos; break; case 11: if( info.src.charCodeAt( pos ) == 34 ) state = 7; else if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 33 ) || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 91 ) || ( info.src.charCodeAt( pos ) >= 93 && info.src.charCodeAt( pos ) <= 254 ) ) state = 11; else if( info.src.charCodeAt( pos ) == 92 ) state = 15; else state = -1; break; case 12: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 81 ) || ( info.src.charCodeAt( pos ) >= 83 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else if( info.src.charCodeAt( pos ) == 82 ) state = 8; else state = -1; match = 10; match_pos = pos; break; case 13: state = -1; match = 1; match_pos = pos; break; case 14: state = -1; match = 11; match_pos = pos; break; case 15: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 254 ) ) state = 11; else state = -1; break; case 16: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 67 ) || ( info.src.charCodeAt( pos ) >= 69 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else if( info.src.charCodeAt( pos ) == 68 ) state = 9; else state = -1; match = 10; match_pos = pos; break; case 17: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 83 ) || ( info.src.charCodeAt( pos ) >= 85 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else if( info.src.charCodeAt( pos ) == 84 ) state = 10; else state = -1; match = 10; match_pos = pos; break; case 18: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 77 ) || ( info.src.charCodeAt( pos ) >= 79 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else if( info.src.charCodeAt( pos ) == 78 ) state = 16; else state = -1; match = 10; match_pos = pos; break; case 19: if( ( info.src.charCodeAt( pos ) >= 0 && info.src.charCodeAt( pos ) <= 31 ) || info.src.charCodeAt( pos ) == 33 || ( info.src.charCodeAt( pos ) >= 35 && info.src.charCodeAt( pos ) <= 39 ) || ( info.src.charCodeAt( pos ) >= 42 && info.src.charCodeAt( pos ) <= 57 ) || ( info.src.charCodeAt( pos ) >= 59 && info.src.charCodeAt( pos ) <= 78 ) || ( info.src.charCodeAt( pos ) >= 80 && info.src.charCodeAt( pos ) <= 254 ) ) state = 1; else if( info.src.charCodeAt( pos ) == 58 ) state = 6; else if( info.src.charCodeAt( pos ) == 79 ) state = 17; else state = -1; match = 10; match_pos = pos; break; } pos++; } while( state > -1 ); } while( 1 > -1 && match == 1 ); if( match > -1 ) { info.att = info.src.substr( start, match_pos - start ); info.offset = match_pos; } else { info.att = new String(); match = -1; } return match; } function __NODEJS_parse( src, err_off, err_la ) { var sstack = new Array(); var vstack = new Array(); var err_cnt = 0; var act; var go; var la; var rval; var parseinfo = new Function( "", "var offset; var src; var att;" ); var info = new parseinfo(); /* Pop-Table */ var pop_tab = new Array( new Array( 0/* begin' */, 1 ), new Array( 13/* begin */, 1 ), new Array( 12/* search_text */, 1 ), new Array( 12/* search_text */, 2 ), new Array( 12/* search_text */, 3 ), new Array( 14/* and_expression */, 1 ), new Array( 14/* and_expression */, 3 ), new Array( 15/* boolean_expression */, 2 ), new Array( 15/* boolean_expression */, 1 ), new Array( 16/* expression */, 3 ), new Array( 16/* expression */, 2 ), new Array( 16/* expression */, 1 ), new Array( 17/* value */, 2 ), new Array( 17/* value */, 1 ), new Array( 18/* string */, 1 ), new Array( 18/* string */, 1 ) ); /* Action-Table */ var act_tab = new Array( /* State 0 */ new Array( 7/* "NOT" */,5 , 3/* "LEFT_PARENTHESE" */,7 , 8/* "COLUMN" */,8 , 11/* "OPERATOR" */,10 , 10/* "WORD" */,12 , 9/* "STRING" */,13 ), /* State 1 */ new Array( 19/* "$" */,0 ), /* State 2 */ new Array( 19/* "$" */,-1 ), /* State 3 */ new Array( 6/* "OR" */,14 , 7/* "NOT" */,5 , 3/* "LEFT_PARENTHESE" */,7 , 8/* "COLUMN" */,8 , 11/* "OPERATOR" */,10 , 10/* "WORD" */,12 , 9/* "STRING" */,13 , 19/* "$" */,-2 , 4/* "RIGHT_PARENTHESE" */,-2 ), /* State 4 */ new Array( 5/* "AND" */,16 , 19/* "$" */,-5 , 7/* "NOT" */,-5 , 3/* "LEFT_PARENTHESE" */,-5 , 8/* "COLUMN" */,-5 , 11/* "OPERATOR" */,-5 , 10/* "WORD" */,-5 , 9/* "STRING" */,-5 , 6/* "OR" */,-5 , 4/* "RIGHT_PARENTHESE" */,-5 ), /* State 5 */ new Array( 3/* "LEFT_PARENTHESE" */,7 , 8/* "COLUMN" */,8 , 11/* "OPERATOR" */,10 , 10/* "WORD" */,12 , 9/* "STRING" */,13 ), /* State 6 */ new Array( 19/* "$" */,-8 , 7/* "NOT" */,-8 , 3/* "LEFT_PARENTHESE" */,-8 , 8/* "COLUMN" */,-8 , 11/* "OPERATOR" */,-8 , 10/* "WORD" */,-8 , 9/* "STRING" */,-8 , 6/* "OR" */,-8 , 5/* "AND" */,-8 , 4/* "RIGHT_PARENTHESE" */,-8 ), /* State 7 */ new Array( 7/* "NOT" */,5 , 3/* "LEFT_PARENTHESE" */,7 , 8/* "COLUMN" */,8 , 11/* "OPERATOR" */,10 , 10/* "WORD" */,12 , 9/* "STRING" */,13 ), /* State 8 */ new Array( 3/* "LEFT_PARENTHESE" */,7 , 8/* "COLUMN" */,8 , 11/* "OPERATOR" */,10 , 10/* "WORD" */,12 , 9/* "STRING" */,13 ), /* State 9 */ new Array( 19/* "$" */,-11 , 7/* "NOT" */,-11 , 3/* "LEFT_PARENTHESE" */,-11 , 8/* "COLUMN" */,-11 , 11/* "OPERATOR" */,-11 , 10/* "WORD" */,-11 , 9/* "STRING" */,-11 , 6/* "OR" */,-11 , 5/* "AND" */,-11 , 4/* "RIGHT_PARENTHESE" */,-11 ), /* State 10 */ new Array( 10/* "WORD" */,12 , 9/* "STRING" */,13 ), /* State 11 */ new Array( 19/* "$" */,-13 , 7/* "NOT" */,-13 , 3/* "LEFT_PARENTHESE" */,-13 , 8/* "COLUMN" */,-13 , 11/* "OPERATOR" */,-13 , 10/* "WORD" */,-13 , 9/* "STRING" */,-13 , 6/* "OR" */,-13 , 5/* "AND" */,-13 , 4/* "RIGHT_PARENTHESE" */,-13 ), /* State 12 */ new Array( 19/* "$" */,-14 , 7/* "NOT" */,-14 , 3/* "LEFT_PARENTHESE" */,-14 , 8/* "COLUMN" */,-14 , 11/* "OPERATOR" */,-14 , 10/* "WORD" */,-14 , 9/* "STRING" */,-14 , 6/* "OR" */,-14 , 5/* "AND" */,-14 , 4/* "RIGHT_PARENTHESE" */,-14 ), /* State 13 */ new Array( 19/* "$" */,-15 , 7/* "NOT" */,-15 , 3/* "LEFT_PARENTHESE" */,-15 , 8/* "COLUMN" */,-15 , 11/* "OPERATOR" */,-15 , 10/* "WORD" */,-15 , 9/* "STRING" */,-15 , 6/* "OR" */,-15 , 5/* "AND" */,-15 , 4/* "RIGHT_PARENTHESE" */,-15 ), /* State 14 */ new Array( 7/* "NOT" */,5 , 3/* "LEFT_PARENTHESE" */,7 , 8/* "COLUMN" */,8 , 11/* "OPERATOR" */,10 , 10/* "WORD" */,12 , 9/* "STRING" */,13 ), /* State 15 */ new Array( 19/* "$" */,-3 , 4/* "RIGHT_PARENTHESE" */,-3 ), /* State 16 */ new Array( 7/* "NOT" */,5 , 3/* "LEFT_PARENTHESE" */,7 , 8/* "COLUMN" */,8 , 11/* "OPERATOR" */,10 , 10/* "WORD" */,12 , 9/* "STRING" */,13 ), /* State 17 */ new Array( 19/* "$" */,-7 , 7/* "NOT" */,-7 , 3/* "LEFT_PARENTHESE" */,-7 , 8/* "COLUMN" */,-7 , 11/* "OPERATOR" */,-7 , 10/* "WORD" */,-7 , 9/* "STRING" */,-7 , 6/* "OR" */,-7 , 5/* "AND" */,-7 , 4/* "RIGHT_PARENTHESE" */,-7 ), /* State 18 */ new Array( 4/* "RIGHT_PARENTHESE" */,23 ), /* State 19 */ new Array( 19/* "$" */,-10 , 7/* "NOT" */,-10 , 3/* "LEFT_PARENTHESE" */,-10 , 8/* "COLUMN" */,-10 , 11/* "OPERATOR" */,-10 , 10/* "WORD" */,-10 , 9/* "STRING" */,-10 , 6/* "OR" */,-10 , 5/* "AND" */,-10 , 4/* "RIGHT_PARENTHESE" */,-10 ), /* State 20 */ new Array( 19/* "$" */,-12 , 7/* "NOT" */,-12 , 3/* "LEFT_PARENTHESE" */,-12 , 8/* "COLUMN" */,-12 , 11/* "OPERATOR" */,-12 , 10/* "WORD" */,-12 , 9/* "STRING" */,-12 , 6/* "OR" */,-12 , 5/* "AND" */,-12 , 4/* "RIGHT_PARENTHESE" */,-12 ), /* State 21 */ new Array( 19/* "$" */,-4 , 4/* "RIGHT_PARENTHESE" */,-4 ), /* State 22 */ new Array( 19/* "$" */,-6 , 7/* "NOT" */,-6 , 3/* "LEFT_PARENTHESE" */,-6 , 8/* "COLUMN" */,-6 , 11/* "OPERATOR" */,-6 , 10/* "WORD" */,-6 , 9/* "STRING" */,-6 , 6/* "OR" */,-6 , 4/* "RIGHT_PARENTHESE" */,-6 ), /* State 23 */ new Array( 19/* "$" */,-9 , 7/* "NOT" */,-9 , 3/* "LEFT_PARENTHESE" */,-9 , 8/* "COLUMN" */,-9 , 11/* "OPERATOR" */,-9 , 10/* "WORD" */,-9 , 9/* "STRING" */,-9 , 6/* "OR" */,-9 , 5/* "AND" */,-9 , 4/* "RIGHT_PARENTHESE" */,-9 ) ); /* Goto-Table */ var goto_tab = new Array( /* State 0 */ new Array( 13/* begin */,1 , 12/* search_text */,2 , 14/* and_expression */,3 , 15/* boolean_expression */,4 , 16/* expression */,6 , 17/* value */,9 , 18/* string */,11 ), /* State 1 */ new Array( ), /* State 2 */ new Array( ), /* State 3 */ new Array( 12/* search_text */,15 , 14/* and_expression */,3 , 15/* boolean_expression */,4 , 16/* expression */,6 , 17/* value */,9 , 18/* string */,11 ), /* State 4 */ new Array( ), /* State 5 */ new Array( 16/* expression */,17 , 17/* value */,9 , 18/* string */,11 ), /* State 6 */ new Array( ), /* State 7 */ new Array( 12/* search_text */,18 , 14/* and_expression */,3 , 15/* boolean_expression */,4 , 16/* expression */,6 , 17/* value */,9 , 18/* string */,11 ), /* State 8 */ new Array( 16/* expression */,19 , 17/* value */,9 , 18/* string */,11 ), /* State 9 */ new Array( ), /* State 10 */ new Array( 18/* string */,20 ), /* State 11 */ new Array( ), /* State 12 */ new Array( ), /* State 13 */ new Array( ), /* State 14 */ new Array( 12/* search_text */,21 , 14/* and_expression */,3 , 15/* boolean_expression */,4 , 16/* expression */,6 , 17/* value */,9 , 18/* string */,11 ), /* State 15 */ new Array( ), /* State 16 */ new Array( 14/* and_expression */,22 , 15/* boolean_expression */,4 , 16/* expression */,6 , 17/* value */,9 , 18/* string */,11 ), /* State 17 */ new Array( ), /* State 18 */ new Array( ), /* State 19 */ new Array( ), /* State 20 */ new Array( ), /* State 21 */ new Array( ), /* State 22 */ new Array( ), /* State 23 */ new Array( ) ); /* Symbol labels */ var labels = new Array( "begin'" /* Non-terminal symbol */, "WHITESPACE" /* Terminal symbol */, "WHITESPACE" /* Terminal symbol */, "LEFT_PARENTHESE" /* Terminal symbol */, "RIGHT_PARENTHESE" /* Terminal symbol */, "AND" /* Terminal symbol */, "OR" /* Terminal symbol */, "NOT" /* Terminal symbol */, "COLUMN" /* Terminal symbol */, "STRING" /* Terminal symbol */, "WORD" /* Terminal symbol */, "OPERATOR" /* Terminal symbol */, "search_text" /* Non-terminal symbol */, "begin" /* Non-terminal symbol */, "and_expression" /* Non-terminal symbol */, "boolean_expression" /* Non-terminal symbol */, "expression" /* Non-terminal symbol */, "value" /* Non-terminal symbol */, "string" /* Non-terminal symbol */, "$" /* Terminal symbol */ ); info.offset = 0; info.src = src; info.att = new String(); if( !err_off ) err_off = new Array(); if( !err_la ) err_la = new Array(); sstack.push( 0 ); vstack.push( 0 ); la = __NODEJS_lex( info ); while( true ) { act = 25; for( var i = 0; i < act_tab[sstack[sstack.length-1]].length; i+=2 ) { if( act_tab[sstack[sstack.length-1]][i] == la ) { act = act_tab[sstack[sstack.length-1]][i+1]; break; } } if( <API key> && sstack.length > 0 ) { __NODEJS_dbg_print( "\nState " + sstack[sstack.length-1] + "\n" + "\tLookahead: " + labels[la] + " (\"" + info.att + "\")\n" + "\tAction: " + act + "\n" + "\tSource: \"" + info.src.substr( info.offset, 30 ) + ( ( info.offset + 30 < info.src.length ) ? "..." : "" ) + "\"\n" + "\tStack: " + sstack.join() + "\n" + "\tValue stack: " + vstack.join() + "\n" ); } //Panic-mode: Try recovery when parse-error occurs! if( act == 25 ) { if( <API key> ) __NODEJS_dbg_print( "Error detected: There is no reduce or shift on the symbol " + labels[la] ); err_cnt++; err_off.push( info.offset - info.att.length ); err_la.push( new Array() ); for( var i = 0; i < act_tab[sstack[sstack.length-1]].length; i+=2 ) err_la[err_la.length-1].push( labels[act_tab[sstack[sstack.length-1]][i]] ); //Remember the original stack! var rsstack = new Array(); var rvstack = new Array(); for( var i = 0; i < sstack.length; i++ ) { rsstack[i] = sstack[i]; rvstack[i] = vstack[i]; } while( act == 25 && la != 19 ) { if( <API key> ) __NODEJS_dbg_print( "\tError recovery\n" + "Current lookahead: " + labels[la] + " (" + info.att + ")\n" + "Action: " + act + "\n\n" ); if( la == -1 ) info.offset++; while( act == 25 && sstack.length > 0 ) { sstack.pop(); vstack.pop(); if( sstack.length == 0 ) break; act = 25; for( var i = 0; i < act_tab[sstack[sstack.length-1]].length; i+=2 ) { if( act_tab[sstack[sstack.length-1]][i] == la ) { act = act_tab[sstack[sstack.length-1]][i+1]; break; } } } if( act != 25 ) break; for( var i = 0; i < rsstack.length; i++ ) { sstack.push( rsstack[i] ); vstack.push( rvstack[i] ); } la = __NODEJS_lex( info ); } if( act == 25 ) { if( <API key> ) __NODEJS_dbg_print( "\tError recovery failed, terminating parse process..." ); break; } if( <API key> ) __NODEJS_dbg_print( "\tError recovery succeeded, continuing" ); } /* if( act == 25 ) break; */ //Shift if( act > 0 ) { if( <API key> ) __NODEJS_dbg_print( "Shifting symbol: " + labels[la] + " (" + info.att + ")" ); sstack.push( act ); vstack.push( info.att ); la = __NODEJS_lex( info ); if( <API key> ) __NODEJS_dbg_print( "\tNew lookahead symbol: " + labels[la] + " (" + info.att + ")" ); } //Reduce else { act *= -1; if( <API key> ) __NODEJS_dbg_print( "Reducing by producution: " + act ); rval = void(0); if( <API key> ) __NODEJS_dbg_print( "\tPerforming semantic action..." ); switch( act ) { case 0: { rval = vstack[ vstack.length - 1 ]; } break; case 1: { result = vstack[ vstack.length - 1 ]; } break; case 2: { rval = vstack[ vstack.length - 1 ]; } break; case 3: { rval = mkComplexQuery('OR',[vstack[ vstack.length - 2 ],vstack[ vstack.length - 1 ]]); } break; case 4: { rval = mkComplexQuery('OR',[vstack[ vstack.length - 3 ],vstack[ vstack.length - 1 ]]); } break; case 5: { rval = vstack[ vstack.length - 1 ] ; } break; case 6: { rval = mkComplexQuery('AND',[vstack[ vstack.length - 3 ],vstack[ vstack.length - 1 ]]); } break; case 7: { rval = mkNotQuery(vstack[ vstack.length - 1 ]); } break; case 8: { rval = vstack[ vstack.length - 1 ]; } break; case 9: { rval = vstack[ vstack.length - 2 ]; } break; case 10: { simpleQuerySetKey(vstack[ vstack.length - 1 ],vstack[ vstack.length - 2 ].split(':').slice(0,-1).join(':')); rval = vstack[ vstack.length - 1 ]; } break; case 11: { rval = vstack[ vstack.length - 1 ]; } break; case 12: { vstack[ vstack.length - 1 ].operator = vstack[ vstack.length - 2 ] ; rval = vstack[ vstack.length - 1 ]; } break; case 13: { rval = vstack[ vstack.length - 1 ]; } break; case 14: { rval = mkSimpleQuery('',vstack[ vstack.length - 1 ]); } break; case 15: { rval = mkSimpleQuery('',vstack[ vstack.length - 1 ].split('"').slice(1,-1).join('"')); } break; } if( <API key> ) __NODEJS_dbg_print( "\tPopping " + pop_tab[act][1] + " off the stack..." ); for( var i = 0; i < pop_tab[act][1]; i++ ) { sstack.pop(); vstack.pop(); } go = -1; for( var i = 0; i < goto_tab[sstack[sstack.length-1]].length; i+=2 ) { if( goto_tab[sstack[sstack.length-1]][i] == pop_tab[act][0] ) { go = goto_tab[sstack[sstack.length-1]][i+1]; break; } } if( act == 0 ) break; if( <API key> ) __NODEJS_dbg_print( "\tPushing non-terminal " + labels[ pop_tab[act][0] ] ); sstack.push( go ); vstack.push( rval ); } if( <API key> ) { alert( NODEJS__dbg_string ); NODEJS__dbg_string = new String(); } } if( <API key> ) { __NODEJS_dbg_print( "\nParse complete." ); alert( NODEJS__dbg_string ); } return err_cnt; } var arrayExtend = function () { var j, i, newlist = [], list_list = arguments; for (j = 0; j < list_list.length; j += 1) { for (i = 0; i < list_list[j].length; i += 1) { newlist.push(list_list[j][i]); } } return newlist; }, mkSimpleQuery = function (key, value, operator) { return {"type": "simple", "operator": "=", "key": key, "value": value}; }, mkNotQuery = function (query) { if (query.operator === "NOT") { return query.query_list[0]; } return {"type": "complex", "operator": "NOT", "query_list": [query]}; }, mkComplexQuery = function (operator, query_list) { var i, query_list2 = []; for (i = 0; i < query_list.length; i += 1) { if (query_list[i].operator === operator) { query_list2 = arrayExtend(query_list2, query_list[i].query_list); } else { query_list2.push(query_list[i]); } } return {type:"complex",operator:operator,query_list:query_list2}; }, simpleQuerySetKey = function (query, key) { var i; if (query.type === "complex") { for (i = 0; i < query.query_list.length; ++i) { simpleQuerySetKey (query.query_list[i],key); } return true; } if (query.type === "simple" && !query.key) { query.key = key; return true; } return false; }, error_offsets = [], error_lookaheads = [], error_count = 0, result; if ((error_count = __NODEJS_parse(string, error_offsets, error_lookaheads)) > 0) { var i; for (i = 0; i < error_count; i += 1) { throw new Error("Parse error near \"" + string.substr(error_offsets[i]) + "\", expecting \"" + error_lookaheads[i].join() + "\""); } } return result; } // parseStringToObject _export('parseStringToObject', parseStringToObject); /*jslint indent: 2, maxlen: 80, sloppy: true */ var query_class_dict = {}; /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */ /*global Query: true, query_class_dict: true, inherits: true, _export: true, QueryFactory: true */ /** * The ComplexQuery inherits from Query, and compares one or several metadata * values. * * @class ComplexQuery * @extends Query * @param {Object} [spec={}] The specifications * @param {String} [spec.operator="AND"] The compare method to use * @param {String} spec.key The metadata key * @param {String} spec.value The value of the metadata to compare */ function ComplexQuery(spec) { Query.call(this); /** * Logical operator to use to compare object values * * @attribute operator * @type String * @default "AND" * @optional */ this.operator = spec.operator || "AND"; /** * The sub Query list which are used to query an item. * * @attribute query_list * @type Array * @default [] * @optional */ this.query_list = spec.query_list || []; this.query_list = this.query_list.map(QueryFactory.create); } inherits(ComplexQuery, Query); /** * #crossLink "Query/match:method" */ ComplexQuery.prototype.match = function (item, wildcard_character) { return this[this.operator](item, wildcard_character); }; /** * #crossLink "Query/toString:method" */ ComplexQuery.prototype.toString = function () { var str_list = ["("], this_operator = this.operator; this.query_list.forEach(function (query) { str_list.push(query.toString()); str_list.push(this_operator); }); str_list.pop(); // remove last operator str_list.push(")"); return str_list.join(" "); }; /** * #crossLink "Query/serialized:method" */ ComplexQuery.prototype.serialized = function () { var s = { "type": "complex", "operator": this.operator, "query_list": [] }; this.query_list.forEach(function (query) { s.query_list.push(query.serialized()); }); return s; }; /** * Comparison operator, test if all sub queries match the * item value * * @method AND * @param {Object} item The item to match * @param {String} wildcard_character The wildcard character * @return {Boolean} true if all match, false otherwise */ ComplexQuery.prototype.AND = function (item, wildcard_character) { var i; for (i = 0; i < this.query_list.length; i += 1) { if (!this.query_list[i].match(item, wildcard_character)) { return false; } } return true; }; /** * Comparison operator, test if one of the sub queries matches the * item value * * @method OR * @param {Object} item The item to match * @param {String} wildcard_character The wildcard character * @return {Boolean} true if one match, false otherwise */ ComplexQuery.prototype.OR = function (item, wildcard_character) { var i; for (i = 0; i < this.query_list.length; i += 1) { if (this.query_list[i].match(item, wildcard_character)) { return true; } } return false; }; /** * Comparison operator, test if the sub query does not match the * item value * * @method NOT * @param {Object} item The item to match * @param {String} wildcard_character The wildcard character * @return {Boolean} true if one match, false otherwise */ ComplexQuery.prototype.NOT = function (item, wildcard_character) { return !this.query_list[0].match(item, wildcard_character); }; query_class_dict.complex = ComplexQuery; _export("ComplexQuery", ComplexQuery); /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */ /*global parseStringToObject: true, emptyFunction: true, sortOn: true, limit: true, select: true, _export: true, <API key>: true, deepClone: true */ /** * The query to use to filter a list of objects. * This is an abstract class. * * @class Query * @constructor */ function Query() { /** * Called before parsing the query. Must be overridden! * * @method onParseStart * @param {Object} object The object shared in the parse process * @param {Object} option Some option gave in parse() */ this.onParseStart = emptyFunction; /** * Called when parsing a simple query. Must be overridden! * * @method onParseSimpleQuery * @param {Object} object The object shared in the parse process * @param {Object} option Some option gave in parse() */ this.onParseSimpleQuery = emptyFunction; /** * Called when parsing a complex query. Must be overridden! * * @method onParseComplexQuery * @param {Object} object The object shared in the parse process * @param {Object} option Some option gave in parse() */ this.onParseComplexQuery = emptyFunction; /** * Called after parsing the query. Must be overridden! * * @method onParseEnd * @param {Object} object The object shared in the parse process * @param {Object} option Some option gave in parse() */ this.onParseEnd = emptyFunction; } /** * Filter the item list with matching item only * * @method exec * @param {Array} item_list The list of object * @param {Object} [option] Some operation option * @param {String} [option.wildcard_character="%"] The wildcard character * @param {Array} [option.select_list] A object keys to retrieve * @param {Array} [option.sort_on] Couples of object keys and "ascending" * or "descending" * @param {Array} [option.limit] Couple of integer, first is an index and * second is the length. */ Query.prototype.exec = function (item_list, option) { var i = 0; if (!Array.isArray(item_list)) { throw new TypeError("Query().exec(): Argument 1 is not of type 'array'"); } if (option === undefined) { option = {}; } if (typeof option !== 'object') { throw new TypeError("Query().exec(): " + "Optional argument 2 is not of type 'object'"); } if (option.wildcard_character === undefined) { option.wildcard_character = '%'; } while (i < item_list.length) { if (!this.match(item_list[i], option.wildcard_character)) { item_list.splice(i, 1); } else { i += 1; } } if (option.sort_on) { sortOn(option.sort_on, item_list); } if (option.limit) { limit(option.limit, item_list); } select(option.select_list || [], item_list); }; /** * Test if an item matches this query * * @method match * @param {Object} item The object to test * @param {String} wildcard_character The wildcard character to use * @return {Boolean} true if match, false otherwise */ Query.prototype.match = function () { return true; }; /** * Browse the Query in deep calling parser method in each step. * * `onParseStart` is called first, on end `onParseEnd` is called. * It starts from the simple queries at the bottom of the tree calling the * parser method `onParseSimpleQuery`, and go up calling the * `onParseComplexQuery` method. * * @method parse * @param {Object} option Any options you want (except 'parsed') * @return {Any} The parse result */ Query.prototype.parse = function (option) { var that = this, object; /** * The recursive parser. * * @param {Object} object The object shared in the parse process * @param {Object} options Some options usable in the parseMethods * @return {Any} The parser result */ function recParse(object, option) { var i, query = object.parsed; if (query.type === "complex") { for (i = 0; i < query.query_list.length; i += 1) { object.parsed = query.query_list[i]; recParse(object, option); query.query_list[i] = object.parsed; } object.parsed = query; that.onParseComplexQuery(object, option); } else if (query.type === "simple") { that.onParseSimpleQuery(object, option); } } object = {"parsed": JSON.parse(JSON.stringify(that.serialized()))}; that.onParseStart(object, option); recParse(object, option); that.onParseEnd(object, option); return object.parsed; }; /** * Convert this query to a parsable string. * * @method toString * @return {String} The string version of this query */ Query.prototype.toString = function () { return ""; }; /** * Convert this query to an jsonable object in order to be remake thanks to * QueryFactory class. * * @method serialized * @return {Object} The jsonable object */ Query.prototype.serialized = function () { return undefined; }; _export("Query", Query); /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */ /*global _export, ComplexQuery, SimpleQuery, Query, parseStringToObject, query_class_dict */ /** * Provides static methods to create Query object * * @class QueryFactory */ function QueryFactory() { return; } /** * Creates Query object from a search text string or a serialized version * of a Query. * * @method create * @static * @param {Object,String} object The search text or the serialized version * of a Query * @return {Query} A Query object */ QueryFactory.create = function (object) { if (object === "") { return new Query(); } if (typeof object === "string") { object = parseStringToObject(object); } if (typeof (object || {}).type === "string" && query_class_dict[object.type]) { return new query_class_dict[object.type](object); } throw new TypeError("QueryFactory.create(): " + "Argument 1 is not a search text or a parsable object"); }; _export("QueryFactory", QueryFactory); /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */ /*global _export: true, to_export: true */ function objectToSearchText(query) { var str_list = []; if (query.type === "complex") { str_list.push("("); (query.query_list || []).forEach(function (sub_query) { str_list.push(objectToSearchText(sub_query)); str_list.push(query.operator); }); str_list.length -= 1; str_list.push(")"); return str_list.join(" "); } if (query.type === "simple") { return query.id + (query.id ? ": " : "") + (query.operator || "=") + ' "' + query.value + '"'; } throw new TypeError("This object is not a query"); } _export("objectToSearchText", objectToSearchText); /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */ /*global Query: true, inherits: true, query_class_dict: true, _export: true, <API key>: true */ /** * The SimpleQuery inherits from Query, and compares one metadata value * * @class SimpleQuery * @extends Query * @param {Object} [spec={}] The specifications * @param {String} [spec.operator="="] The compare method to use * @param {String} spec.key The metadata key * @param {String} spec.value The value of the metadata to compare */ function SimpleQuery(spec) { Query.call(this); /** * Operator to use to compare object values * * @attribute operator * @type String * @default "=" * @optional */ this.operator = spec.operator || "="; /** * Key of the object which refers to the value to compare * * @attribute key * @type String */ this.key = spec.key; /** * Value is used to do the comparison with the object value * * @attribute value * @type String */ this.value = spec.value; } inherits(SimpleQuery, Query); /** * #crossLink "Query/match:method" */ SimpleQuery.prototype.match = function (item, wildcard_character) { return this[this.operator](item[this.key], this.value, wildcard_character); }; /** * #crossLink "Query/toString:method" */ SimpleQuery.prototype.toString = function () { return (this.key ? this.key + ": " : "") + (this.operator || "=") + ' "' + this.value + '"'; }; /** * #crossLink "Query/serialized:method" */ SimpleQuery.prototype.serialized = function () { return { "type": "simple", "operator": this.operator, "key": this.key, "value": this.value }; }; /** * Comparison operator, test if this query value matches the item value * * @method = * @param {String} object_value The value to compare * @param {String} comparison_value The comparison value * @param {String} wildcard_character The wildcard_character * @return {Boolean} true if match, false otherwise */ SimpleQuery.prototype["="] = function (object_value, comparison_value, wildcard_character) { var value, i; if (!Array.isArray(object_value)) { object_value = [object_value]; } for (i = 0; i < object_value.length; i += 1) { value = object_value[i]; if (typeof value === 'object') { value = value.content; } if (comparison_value === undefined) { if (value === undefined) { return true; } return false; } if (value === undefined) { return false; } if ( <API key>( comparison_value.toString(), wildcard_character ).test(value.toString()) ) { return true; } } return false; }; /** * Comparison operator, test if this query value does not match the item value * * @method != * @param {String} object_value The value to compare * @param {String} comparison_value The comparison value * @param {String} wildcard_character The wildcard_character * @return {Boolean} true if not match, false otherwise */ SimpleQuery.prototype["!="] = function (object_value, comparison_value, wildcard_character) { var value, i; if (!Array.isArray(object_value)) { object_value = [object_value]; } for (i = 0; i < object_value.length; i += 1) { value = object_value[i]; if (typeof value === 'object') { value = value.content; } if (comparison_value === undefined) { if (value === undefined) { return false; } return true; } if (value === undefined) { return true; } if ( <API key>( comparison_value.toString(), wildcard_character ).test(value.toString()) ) { return false; } } return true; }; /** * Comparison operator, test if this query value is lower than the item value * * @method < * @param {Number, String} object_value The value to compare * @param {Number, String} comparison_value The comparison value * @return {Boolean} true if lower, false otherwise */ SimpleQuery.prototype["<"] = function (object_value, comparison_value) { var value; if (!Array.isArray(object_value)) { object_value = [object_value]; } value = object_value[0]; if (typeof value === 'object') { value = value.content; } return value < comparison_value; }; /** * Comparison operator, test if this query value is equal or lower than the * item value * * @method <= * @param {Number, String} object_value The value to compare * @param {Number, String} comparison_value The comparison value * @return {Boolean} true if equal or lower, false otherwise */ SimpleQuery.prototype["<="] = function (object_value, comparison_value) { var value; if (!Array.isArray(object_value)) { object_value = [object_value]; } value = object_value[0]; if (typeof value === 'object') { value = value.content; } return value <= comparison_value; }; /** * Comparison operator, test if this query value is greater than the item * value * * @method > * @param {Number, String} object_value The value to compare * @param {Number, String} comparison_value The comparison value * @return {Boolean} true if greater, false otherwise */ SimpleQuery.prototype[">"] = function (object_value, comparison_value) { var value; if (!Array.isArray(object_value)) { object_value = [object_value]; } value = object_value[0]; if (typeof value === 'object') { value = value.content; } return value > comparison_value; }; /** * Comparison operator, test if this query value is equal or greater than the * item value * * @method >= * @param {Number, String} object_value The value to compare * @param {Number, String} comparison_value The comparison value * @return {Boolean} true if equal or greater, false otherwise */ SimpleQuery.prototype[">="] = function (object_value, comparison_value) { var value; if (!Array.isArray(object_value)) { object_value = [object_value]; } value = object_value[0]; if (typeof value === 'object') { value = value.content; } return value >= comparison_value; }; query_class_dict.simple = SimpleQuery; _export("SimpleQuery", SimpleQuery); /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */ /*global _export: true */ /** * Escapes regexp special chars from a string. * * @param {String} string The string to escape * @return {String} The escaped string */ function <API key>(string) { if (typeof string === "string") { return string.replace(/([\\\.\$\[\]\(\)\{\}\^\?\*\+\-])/g, "\\$1"); } throw new TypeError("complex_queries.<API key>(): " + "Argument no 1 is not of type 'string'"); } _export("<API key>", <API key>); /** * Convert metadata values to array of strings. ex: * * "a" -> ["a"], * {"content": "a"} -> ["a"] * * @param {Any} value The metadata value * @return {Array} The value in string array format */ function <API key>(value) { var i, new_value = []; if (value === undefined) { return undefined; } if (!Array.isArray(value)) { value = [value]; } for (i = 0; i < value.length; i += 1) { if (typeof value[i] === 'object') { new_value[i] = value[i].content; } else { new_value[i] = value[i]; } } return new_value; } /** * A sort function to sort items by key * * @param {String} key The key to sort on * @param {String} [way="ascending"] 'ascending' or 'descending' * @return {Function} The sort function */ function sortFunction(key, way) { if (way === 'descending') { return function (a, b) { // this comparison is 5 times faster than json comparison var i, l; a = <API key>(a[key]) || []; b = <API key>(b[key]) || []; l = a.length > b.length ? a.length : b.length; for (i = 0; i < l; i += 1) { if (a[i] === undefined) { return 1; } if (b[i] === undefined) { return -1; } if (a[i] > b[i]) { return -1; } if (a[i] < b[i]) { return 1; } } return 0; }; } if (way === 'ascending') { return function (a, b) { // this comparison is 5 times faster than json comparison var i, l; a = <API key>(a[key]) || []; b = <API key>(b[key]) || []; l = a.length > b.length ? a.length : b.length; for (i = 0; i < l; i += 1) { if (a[i] === undefined) { return -1; } if (b[i] === undefined) { return 1; } if (a[i] > b[i]) { return 1; } if (a[i] < b[i]) { return -1; } } return 0; }; } throw new TypeError("complex_queries.sortFunction(): " + "Argument 2 must be 'ascending' or 'descending'"); } /** * Clones all native object in deep. Managed types: Object, Array, String, * Number, Boolean, null. * * @param {A} object The object to clone * @return {A} The cloned object */ function deepClone(object) { var i, cloned; if (Array.isArray(object)) { cloned = []; for (i = 0; i < object.length; i += 1) { cloned[i] = deepClone(object[i]); } return cloned; } if (typeof object === "object") { cloned = {}; for (i in object) { if (object.hasOwnProperty(i)) { cloned[i] = deepClone(object[i]); } } return cloned; } return object; } /** * Inherits the prototype methods from one constructor into another. The * prototype of `constructor` will be set to a new object created from * `superConstructor`. * * @param {Function} constructor The constructor which inherits the super one * @param {Function} superConstructor The super constructor */ function inherits(constructor, superConstructor) { constructor.super_ = superConstructor; constructor.prototype = Object.create(superConstructor.prototype, { "constructor": { "configurable": true, "enumerable": false, "writable": true, "value": constructor } }); } /** * Does nothing */ function emptyFunction() { return; } /** * Filter a list of items, modifying them to select only wanted keys. If * `clone` is true, then the method will act on a cloned list. * * @param {Array} select_option Key list to keep * @param {Array} list The item list to filter * @param {Boolean} [clone=false] If true, modifies a clone of the list * @return {Array} The filtered list */ function select(select_option, list, clone) { var i, j, new_item; if (!Array.isArray(select_option)) { throw new TypeError("complex_queries.select(): " + "Argument 1 is not of type Array"); } if (!Array.isArray(list)) { throw new TypeError("complex_queries.select(): " + "Argument 2 is not of type Array"); } if (clone === true) { list = deepClone(list); } for (i = 0; i < list.length; i += 1) { new_item = {}; for (j = 0; j < select_option.length; j += 1) { new_item[select_option[j]] = list[i][select_option[j]]; } for (j in new_item) { if (new_item.hasOwnProperty(j)) { list[i] = new_item; break; } } } return list; } _export('select', select); /** * Sort a list of items, according to keys and directions. If `clone` is true, * then the method will act on a cloned list. * * @param {Array} sort_on_option List of couples [key, direction] * @param {Array} list The item list to sort * @param {Boolean} [clone=false] If true, modifies a clone of the list * @return {Array} The filtered list */ function sortOn(sort_on_option, list, clone) { var sort_index; if (!Array.isArray(sort_on_option)) { throw new TypeError("complex_queries.sortOn(): " + "Argument 1 is not of type 'array'"); } if (clone) { list = deepClone(list); } for (sort_index = sort_on_option.length - 1; sort_index >= 0; sort_index -= 1) { list.sort(sortFunction( sort_on_option[sort_index][0], sort_on_option[sort_index][1] )); } return list; } _export('sortOn', sortOn); /** * Limit a list of items, according to index and length. If `clone` is true, * then the method will act on a cloned list. * * @param {Array} limit_option A couple [from, length] * @param {Array} list The item list to limit * @param {Boolean} [clone=false] If true, modifies a clone of the list * @return {Array} The filtered list */ function limit(limit_option, list, clone) { if (!Array.isArray(limit_option)) { throw new TypeError("complex_queries.limit(): " + "Argument 1 is not of type 'array'"); } if (!Array.isArray(list)) { throw new TypeError("complex_queries.limit(): " + "Argument 2 is not of type 'array'"); } if (clone) { list = deepClone(list); } list.splice(0, limit_option[0]); if (limit_option[1]) { list.splice(limit_option[1]); } return list; } _export('limit', limit); /** * Convert a search text to a regexp. * * @param {String} string The string to convert * @param {String} [wildcard_character=undefined] The wildcard chararter * @return {RegExp} The search text regexp */ function <API key>(string, wildcard_character) { if (typeof string !== 'string') { throw new TypeError("complex_queries.<API key>(): " + "Argument 1 is not of type 'string'"); } if (wildcard_character === undefined || wildcard_character === null || wildcard_character === '') { return new RegExp("^" + <API key>(string) + "$"); } if (typeof wildcard_character !== 'string' || wildcard_character.length > 1) { throw new TypeError("complex_queries.<API key>(): " + "Optional argument 2 must be a string of length <= 1"); } return new RegExp("^" + <API key>(string).replace( new RegExp(<API key>(wildcard_character), 'g'), '.*' ) + "$"); } _export('<API key>', <API key>); return to_export; }));
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace Pango { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; #region Autogenerated code public partial class Fontset : GLib.Object { public Fontset (IntPtr raw) : base(raw) {} protected Fontset() : base(IntPtr.Zero) { CreateNativeObject (new string [0], new GLib.Value [0]); } [DllImport(NativeMethods.Pango, CallingConvention = CallingConvention.Cdecl)] static extern void <API key>(IntPtr raw, PangoSharp.<API key> func, IntPtr data); public void Foreach(Pango.FontsetForeachFunc func) { PangoSharp.<API key> func_wrapper = new PangoSharp.<API key> (func); <API key>(Handle, func_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport(NativeMethods.Pango, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr <API key>(IntPtr raw, uint wc); public Pango.Font GetFont(uint wc) { IntPtr raw_ret = <API key>(Handle, wc); Pango.Font ret = GLib.Object.GetObject(raw_ret) as Pango.Font; return ret; } [DllImport(NativeMethods.Pango, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr <API key>(IntPtr raw); public Pango.FontMetrics Metrics { get { IntPtr raw_ret = <API key>(Handle); Pango.FontMetrics ret = raw_ret == IntPtr.Zero ? null : (Pango.FontMetrics) GLib.Opaque.GetOpaque (raw_ret, typeof (Pango.FontMetrics), false); return ret; } } [DllImport(NativeMethods.Pango, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr <API key>(); public static new GLib.GType GType { get { IntPtr raw_ret = <API key>(); GLib.GType ret = new GLib.GType(raw_ret); return ret; } } #endregion } }
:- module(pce_dialog_layout, [ layout_dialog/1 ]). :- use_module(library(pce)). :- require([ append/3 , delete/3 , forall/2 , get_chain/3 , ignore/1 , maplist/3 , member/2 , include/3 , subset/2 , subtract/3 ]). /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - To be recognised: 1) rows/columns of objects. Alignment: top/bottom/reference/center 2) nesting? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ layout_dialog(D) :- send(D?graphicals, for_all, and(message(@arg1, right, @nil), message(@arg1, above, @nil), message(@arg1, left, @nil), message(@arg1, below, @nil))), get_chain(D, graphicals, Grs), get(D, overlay, Overlay), delete(Grs, Overlay, Items), make_rows(Items, Rows), sort_rows(Rows, Sorted), update_order(Sorted), make_alignments(Sorted), relate_dialog_items(Sorted), send(D, layout), send(Overlay, expose), send(D, fit). % make_rows/2 % Split list of graphicals into nested list of graphicals with % approximately the same Y make_rows([], []). make_rows([Gr1|Rest], [[Gr1|RestRow]|RestRows]) :- include(same_row(Gr1), Rest, RestRow), subtract(Rest, RestRow, Grs), make_rows(Grs, RestRows). same_row(Gr1, Gr2) :- get(Gr1, top_side, T1), get(Gr1, bottom_side, B1), get(Gr2, top_side, T2), get(Gr2, bottom_side, B2), Overlap is min(B1, B2) - max(T1, T2), Smallest is min(B1-T1, B2-T2), Overlap >= Smallest % sort_rows/2 % Sort rows in accending y-direction. sort_rows(Rows, Sorted) :- maplist(sort_row, Rows, LSorted), maplist(key_with_top_side, LSorted, KeyedRows), keysort(KeyedRows, SortedKeyedRows), maplist(unkey, SortedKeyedRows, Sorted). % sort_row/1 % Sort row left-to-right sort_row(Row, Sorted) :- maplist(key_with_left_side, Row, KeyedRow), keysort(KeyedRow, SortedKeyedRow), maplist(unkey, SortedKeyedRow, Sorted). key_with_top_side(Row, Top-Row) :- Row = [Gr1|_], get(Gr1, top_side, Top). key_with_left_side(Gr, Left-Gr) :- get(Gr, left_side, Left). unkey(_-Value, Value). % update_order/1 % Update the order of the graphical objects. update_order([]) :- !. update_order([H|T]) :- !, update_order(H), update_order(T). update_order(Ref) :- send(Ref, expose), send(Ref, auto_align, @on). % make_alignments/1 % Fix the alignments of the dialog items. make_alignments(Rows) :- forall(item(Item, Rows), ( get(Item, <API key>, alignment, Alignment), Alignment \== column -> send(Item, alignment, Alignment) ; send(Item, alignment, left) )), forall(item(Item, Rows), ( get(Item, auto_label_align, @on) -> ignore(send(Item, label_width, @default)) ; true )), <API key>(Rows), maplist(make_row_alignment, Rows), maplist(make_y_references, Rows). <API key>([]). <API key>([_]). <API key>([R1, R2|Rows]) :- ( R1 \== [], R2 \== [], <API key>(R1, R2) -> align_columns(R1, R2) ; true ), <API key>([R2|Rows]). <API key>([], _) :- !. <API key>(_, []) :- !. <API key>([H1|T1], [H2|T2]) :- above(H1, H2), <API key>(T1, T2). align_columns([], _) :- !. align_columns(_, []) :- !. align_columns([H1|T1], [H2|T2]) :- align_above(H1, H2), align_columns(T1, T2). align_above(I1, I2) :- send(I1, above, I2), send(I1, alignment, column), send(I2, alignment, column). above(Gr1, Gr2) :- ( \+ can_be_in_column(Gr1) ; \+ can_be_in_column(Gr2) ), !, fail. above(Gr1, Gr2) :- get(Gr1, auto_label_align, @on), get(Gr2, auto_label_align, @on), get(Gr1, label_format, right), get(Gr2, label_format, right), get(Gr1, left_side, L1), get(Gr1, label_width, W1), get(Gr2, left_side, L2), get(Gr2, label_width, W2), abs((L1+W1) - (L2+W2)) < 15. above(Gr1, Gr2) :- get(Gr1, left_side, L1), get(Gr2, left_side, L2), abs(L1 - L2) < 15. can_be_in_column(Gr) :- get(Gr, alignment, column), !. can_be_in_column(Gr) :- get(Gr, fixed_alignment, @off). make_row_alignment([_]) :- !. make_row_alignment(Row) :- findall(align_row(Sub, Alignment), row_alignment(Row, Sub, Alignment), Alignments), %format('~p~n', [Alignments]), <API key>(Alignments, Alignments, Cleaned), %format('~p~n', [Cleaned]), maplist(call, Cleaned). <API key>([], _, []). <API key>([H|T], As, L) :- H = align_row(S1, _), length(S1, L1), member(align_row(S2, _), As), length(S2, L2), L1 < L2, subset(S1, S2), !, <API key>(T, As, L). <API key>([H|T], As, [H|L]) :- <API key>(T, As, L). row_alignment(Row, Sub, Alignment) :- first(First, Row), get(First, device, Device), append(Before, R0, Row), left(Before, Device, LeftEdge), append(Sub, After, R0), Sub \== [], right(After, Device, RightEdge), \+((member(X, Sub), get(X, alignment, column))), left_to_right(Sub), first(Head, Sub), tail(Tail, Sub), get(Head, left_side, Left), get(Tail, right_side, Right), left_aligned(LeftEdge, RightEdge, Left, Right, LH), right_aligned(LeftEdge, RightEdge, Left, Right, RH), center_aligned(LeftEdge, RightEdge, Left, Right, CH), ( LH < RH, LH < CH -> Alignment = left ; RH < CH -> Alignment = right ; Alignment = center ). left([], Device, Left) :- get(Device?bounding_box, left_side, Left). left(L, _, Left) :- tail(T, L), % get(T, alignment, column), get(T, right_side, Left). right([], Device, Right) :- get(Device?bounding_box, right_side, Right). right(L, _, Right) :- first(H, L), % get(H, alignment, column), get(H, left_side, Right). % tail/2 is defined here as the system definitions of SICStus and % SWI-Prolog differ in the argument order. tail(Elem, [Elem]) :- !. tail(Elem, [_|T]) :- tail(Elem, T). first(H, [H|_]). align_row(Row, Alignment) :- forall(member(Gr, Row), send(Gr, alignment, Alignment)). left_to_right([]). left_to_right([_]). left_to_right([H1, H2|T]) :- get(H1, right_side, R), get(H2, left_side, L), L - R < 30, left_to_right([H2|T]). left_aligned(X, _W, Left, _Right, H) :- H is abs(X-Left). right_aligned(_X, W, _Left, Right, H) :- H is abs(Right - W). center_aligned(X, W, Left, Right, H) :- H is abs((Left+Right)//2 - ((X + W)//2)). % make_y_references/1 % Fix the (Y)-coordinate of the reference points make_y_references([]). make_y_references([_]). % 1 element: doesn't matter make_y_references(Row) :- forall((member(I, Row), get(I, fixed_reference, @off)), make_y_reference(I, Row)). make_y_reference(I, Row) :- findall(Proto, alignment_proto(I, Row, Proto), Protos), sort(Protos, [proto(_, I2, Side)|_]), !, get(I, top_side, Y1), get(I2, top_side, Y2), get(I, Side, S1), get(I2, Side, S2), get(I2?reference, y, YR), YR2 is (Y2-S2) + YR - (Y1-S1), get(I?reference, x, RX), send(I, reference, point(RX, YR2)). make_y_reference(_, _). alignment_proto(I1, Row, proto(H, I2, Side)) :- alignment_side(Side), member(I2, Row), I2 \== I1, get(I2, fixed_reference, @on), get(I1, Side, V1), get(I2, Side, V2), H is abs(V1 - V2). alignment_side(top_side). alignment_side(center_y). alignment_side(bottom_side). % relate_dialog_items/1 % Relate the dialog items top/bottom/left/right relate_dialog_items([]). relate_dialog_items([H|T]) :- <API key>(H), <API key>(H, T), relate_dialog_items(T). <API key>([_]) :- !. <API key>([H1,H2|T]) :- send(H2, right, H1), <API key>([H2|T]). <API key>(_, []) :- !. <API key>([H1|_], [[H2|_]|_]) :- send(H2, below, H1). item(Item, [Row|_]) :- member(Item, Row). item(Item, [_|T]) :- item(Item, T).
package org.alfresco.module.<API key>.capability.declarative.condition; import org.alfresco.module.<API key>.capability.declarative.<API key>; import org.alfresco.module.<API key>.model.<API key>; import org.alfresco.service.cmr.repository.NodeRef; /** * @author Roy Wetherall */ public class <API key> extends <API key> { @Override public boolean evaluateImpl(NodeRef nodeRef) { boolean result = false; if (recordService.isRecord(nodeRef)) { // Check the record for the vital record aspect result = nodeService.hasAspect(nodeRef, <API key>.ASPECT_VITAL_RECORD); } else if (recordFolderService.isRecordFolder(nodeRef)) { // Check the folder for the vital record indicator Boolean value = (Boolean)nodeService.getProperty(nodeRef, <API key>.<API key>); if (value != null) { result = value.booleanValue(); } } return result; } }
#include "tl-langconstruct.hpp" #include "tl-predicateutils.hpp" #include "tl-source.hpp" #include "cxx-attrnames.h" #include "cxx-exprtype.h" namespace TL { // Remove it once all LangConstruct sons have their own const AlwaysFalse<AST_t> LangConstruct::predicate; // Static predicates for LangConstructs const PredicateAST<<API key>> IdExpression::predicate; const PredicateAST<LANG_IS_STATEMENT> Statement::predicate; const PredicateAST<<API key>> ForStatement::predicate; const PredicateAST<<API key>> FunctionDefinition::predicate; const PredicateAST<<API key>> Expression::predicate; const PredicateAST<<API key>> <API key>::predicate; const PredicateAST<<API key>> DeclaredEntity::predicate; const PredicateAST<LANG_IS_DECLARATION> Declaration::predicate; const PredicateAST<<API key>> <API key>::predicate; std::string LangConstruct::prettyprint() { return _ref.prettyprint(); } ObjectList<IdExpression> LangConstruct::<API key>(SymbolsWanted symbol_filter) { PredicateAST<<API key>> id_expr_pred; PredicateAST<<API key>> member_access; ObjectList<AST_t> id_expressions = _ref.depth_subtrees() .filter(id_expr_pred) .filter(negate(member_access)); ObjectList<IdExpression> result; for (ObjectList<AST_t>::iterator it = id_expressions.begin(); it != id_expressions.end(); it++) { AST_t& ref = *it; Scope ref_scope = _scope_link.get_scope(ref); Symbol symbol = ref_scope.<API key>(ref); if (symbol.is_valid() && !symbol.is_builtin()) { IdExpression id_expression(*it, _scope_link); bool eligible = true; if (symbol_filter == ONLY_OBJECTS) { eligible = symbol.is_variable(); } else if (symbol_filter == ONLY_FUNCTIONS) { eligible = symbol.is_function(); } if (eligible) { result.push_back(id_expression); } } } return result; } ObjectList<IdExpression> LangConstruct::<API key>(SymbolsWanted symbol_filter) { PredicateAST<<API key>> id_expr_pred; PredicateAST<<API key>> member_access; ObjectList<AST_t> id_expressions = _ref.depth_subtrees() .filter(id_expr_pred) .filter(negate(member_access)); Scope statement_scope = _scope_link.get_scope(_ref); ObjectList<IdExpression> result; for (ObjectList<AST_t>::iterator it = id_expressions.begin(); it != id_expressions.end(); it++) { AST_t& ref = *it; Symbol symbol = statement_scope.<API key>(ref); if (symbol.is_valid() && !symbol.is_builtin()) { Scope ref_scope = _scope_link.get_scope(ref); Symbol local_symbol = ref_scope.<API key>(ref); if (local_symbol == symbol) { IdExpression id_expression(*it, _scope_link); bool eligible = true; if (symbol_filter == ONLY_OBJECTS) { eligible = symbol.is_variable(); } else if (symbol_filter == ONLY_FUNCTIONS) { eligible = symbol.is_function(); } if (eligible) { result.push_back(id_expression); } } } } return result; } ObjectList<Symbol> Statement::non_local_symbols() { ObjectList<IdExpression> id_expressions = <API key>(); ObjectList<Symbol> result = id_expressions.map(functor(&IdExpression::get_symbol)); return result; } bool Statement::<API key>() { TL::Bool b = _ref.get_attribute(<API key>); return b; } ObjectList<Statement> Statement::<API key>() { ObjectList<Statement> result; if (<API key>()) { AST_t list = _ref.get_attribute(<API key>); ASTIterator ast_iterator = list.get_list_iterator(); ast_iterator.rewind(); while (!ast_iterator.end()) { Statement st(ast_iterator.item(), _scope_link); result.append(st); ast_iterator.next(); } } return result; } FunctionDefinition LangConstruct::<API key>() { AST_t enclosing_function = _ref.<API key>(); FunctionDefinition result(enclosing_function, _scope_link); return result; } void FunctionDefinition::prepend_sibling(AST_t ast) { _ref.<API key>(ast); } IdExpression FunctionDefinition::get_function_name() { TL::AST_t ast = _ref.get_attribute(LANG_FUNCTION_NAME); return IdExpression(ast, _scope_link); } Statement FunctionDefinition::get_function_body() { TL::AST_t ast = _ref.get_attribute(LANG_FUNCTION_BODY); return Statement(ast, _scope_link); } bool FunctionDefinition::is_templated() const { TL::Bool result = _ref.get_attribute(<API key>); return result; } ObjectList<AST_t> FunctionDefinition::get_template_header() { TL::AST_t start = _ref.get_attribute(<API key>); PredicateAST<<API key>> <API key>; ObjectList<AST_t> result = start.depth_subtrees(<API key>); return result; } AST_t FunctionDefinition::<API key>() { return _ref.<API key>(); } DeclaredEntity FunctionDefinition::get_declared_entity() { AST_t declarator = _ref.get_attribute(<API key>); return DeclaredEntity(declarator, _scope_link); } bool Declaration::is_templated() { TL::Bool result = _ref.get_attribute(<API key>); return result; } ObjectList<AST_t> Declaration::get_template_header() { TL::AST_t start = _ref.get_attribute(<API key>); PredicateAST<<API key>> <API key>; ObjectList<AST_t> result = start.depth_subtrees(<API key>); return result; } AST_t Declaration::<API key>() { if (is_templated()) { // If it is templated we want to spring over the template headers TL::AST_t start = _ref.get_attribute(<API key>); AST inner_tree = start.get_internal_ast(); return ASTParent(inner_tree); } else { // Otherwise this is fine return _ref; } } // Returns a flattened version of this id-expression std::string IdExpression::<API key>() const { std::string id_expr_str = _ref.prettyprint(); unsigned int length = id_expr_str.size(); for (unsigned int i = 0; i < length; i++) { if (id_expr_str[i] == ':' || id_expr_str[i] == '<' || id_expr_str[i] == '>') { id_expr_str[i] = '_'; } } return id_expr_str; } Declaration IdExpression::get_declaration() { AST_t <API key> = this->get_symbol().<API key>(); TL::Bool b = <API key>.get_attribute(LANG_IS_DECLARATION); if (b) { return Declaration(<API key>, this->_scope_link); } else { std::cerr << "Cannot retrieve a proper declaration of id-expression '" << _ref.prettyprint() << "' from its point of declaration '" << <API key>.prettyprint() << "'" << std::endl; return Declaration(AST_t(), this->_scope_link); } } std::string IdExpression::get_qualified_part() const { if (is_unqualified()) { return ""; } else { TL::AST_t nested_name_part = _ref.get_attribute(<API key>); return nested_name_part.prettyprint(); } } bool IdExpression::is_template_id() const { TL::Bool ret = _ref. get_attribute(LANG_UNQUALIFIED_ID) ->get_attribute(LANG_IS_TEMPLATE_ID); return ret; } std::string IdExpression::<API key>() const { TL::AST_t ret = _ref .get_attribute(LANG_UNQUALIFIED_ID) ->get_attribute(LANG_TEMPLATE_ARGS); return "<" + ret.prettyprint(/*comma=*/true) + ">"; } std::string IdExpression::get_template_name() const { TL::AST_t ret = _ref.get_attribute(LANG_TEMPLATE_NAME); return ret.prettyprint(); } std::string IdExpression::<API key>(bool with_template_id) const { TL::AST_t unqualified_part = _ref.get_attribute(LANG_UNQUALIFIED_ID); if (!with_template_id) { TL::Bool is_template_id = unqualified_part.get_attribute(LANG_IS_TEMPLATE_ID); if (!is_template_id) { return unqualified_part.prettyprint(); } else { TL::AST_t template_name = unqualified_part.get_attribute(LANG_TEMPLATE_NAME); return template_name.prettyprint(); } } else { return unqualified_part.prettyprint(); } } bool IdExpression::is_qualified() const { TL::Bool is_qualif = _ref.get_attribute(<API key>); return (bool)is_qualif; } bool IdExpression::is_unqualified() const { TL::Bool is_qualif = _ref.get_attribute(<API key>); return !((bool)is_qualif); } Symbol IdExpression::get_symbol() const { Scope id_expr_scope = _scope_link.get_scope(_ref); Symbol result = id_expr_scope.<API key>(_ref); return result; } AST_t IdExpression::get_ast() const { return _ref; } /** Beginning of deprecated functions **/ void ReplaceIdExpression::add_replacement(Symbol sym, std::string str) { Source src; src << str; AST_t tree = src.parse_expression(sym.get_scope()); _repl_map[sym] = tree; } void ReplaceIdExpression::add_replacement(Symbol sym, Source src) { add_replacement(sym, src.get_source()); } /** End of deprecated functions **/ void ReplaceIdExpression::add_replacement(Symbol sym, AST_t ast) { _repl_map[sym] = ast; } void ReplaceIdExpression::add_replacement(Symbol sym, std::string str, AST_t ref_tree, ScopeLink scope_link) { Source src; src << str; AST_t tree = src.parse_expression(ref_tree, scope_link, Source::<API key>); _repl_map[sym] = tree; } void ReplaceIdExpression::add_replacement(Symbol sym, Source src, AST_t ref_tree, ScopeLink scope_link) { add_replacement(sym, src, ref_tree, scope_link); } bool ReplaceIdExpression::has_replacement(Symbol sym) { return (_repl_map.find(sym) != _repl_map.end()); } AST_t Expression::advance_over_nests(AST_t expr) { if (!expr.is_valid()) { std::cerr << "Expression is not valid" << std::endl; return expr; } TL::Bool is_expression_nest = expr.get_attribute(<API key>); while (is_expression_nest) { expr = expr.get_attribute(<API key>); is_expression_nest = expr.get_attribute(<API key>); } return expr; } bool Expression::is_literal() { TL::Bool b = _ref.get_attribute(LANG_IS_LITERAL); return b; } bool Expression::is_id_expression() { TL::Bool b = _ref.get_attribute(<API key>); return b; } IdExpression Expression::get_id_expression() { return IdExpression(_ref, this->_scope_link); } bool Expression::is_binary_operation() { TL::Bool b = _ref.get_attribute(<API key>); return b; } bool Expression::is_unary_operation() { TL::Bool b = _ref.get_attribute(<API key>); return b; } bool Expression::is_assignment() { TL::Bool b = _ref.get_attribute(LANG_IS_ASSIGNMENT); return b; } bool Expression::<API key>() { TL::Bool b(false); b = TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)) || TL::Bool(_ref.get_attribute(<API key>)); return b; } bool Expression::is_function_call() { TL::Bool b = _ref.get_attribute(<API key>); return b; } Expression Expression::<API key>() { TL::AST_t result = _ref.get_attribute(<API key>); Expression expr(result, get_scope_link()); return expr; } ObjectList<Expression> Expression::get_argument_list() { AST_t expression_list = _ref.get_attribute(<API key>); ObjectList<Expression> result; if (expression_list.is_list()) { ASTIterator it = expression_list.get_list_iterator(); it.rewind(); while (!it.end()) { Expression expr(it.item(), _scope_link); result.push_back(expr); it.next(); } } return result; } bool Expression::is_array_subscript() { TL::Bool b = _ref.get_attribute(<API key>); return b; } Expression Expression::<API key>() { TL::AST_t result = _ref.get_attribute(<API key>); return Expression(result, _scope_link); } Expression Expression::<API key>() { TL::AST_t result = _ref.get_attribute(<API key>); return Expression(result, _scope_link); } bool Expression::is_casting() { TL::Bool b = _ref.get_attribute(LANG_IS_CAST); return b; } AST_t Expression::get_cast_type() { AST_t result = _ref.get_attribute(LANG_CAST_TYPE); return result; } Expression Expression::<API key>() { Expression result(_ref.get_attribute(<API key>), this->_scope_link); return result; } Expression Expression::get_first_operand() { if (this->is_assignment() || this-><API key>()) { AST_t result = _ref.get_attribute(LANG_LHS_ASSIGNMENT); return Expression(result, this->_scope_link); } else { AST_t result = _ref.get_attribute(LANG_LHS_OPERAND); return Expression(result, this->_scope_link); } } Expression Expression::get_second_operand() { if (this->is_assignment() || this-><API key>()) { AST_t result = _ref.get_attribute(LANG_RHS_ASSIGNMENT); return Expression(result, this->_scope_link); } else { AST_t result = _ref.get_attribute(LANG_RHS_OPERAND); return Expression(result, this->_scope_link); } } Expression Expression::get_unary_operand() { AST_t result = _ref.get_attribute(LANG_UNARY_OPERAND); return Expression(result, this->_scope_link); } bool Expression::is_member_access() { TL::Bool b = _ref.get_attribute(<API key>); return b; } bool Expression::<API key>() { TL::Bool b = _ref.get_attribute(<API key>); return b; } IdExpression Expression::get_accessed_member() { TL::AST_t ast = _ref.get_attribute(<API key>); return IdExpression(ast, this->get_scope_link()); } Expression Expression::get_accessed_entity() { TL::AST_t ast = _ref.get_attribute(<API key>); return Expression(ast, this->get_scope_link()); } Expression::OperationKind Expression::get_operation_kind() { if (is_unary_operation()) { if( TL::Bool(_ref.get_attribute(LANG_IS_PLUS_OP))) return PLUS; else if (TL::Bool(_ref.get_attribute(LANG_IS_NEGATE_OP))) return MINUS; else if (TL::Bool(_ref.get_attribute(LANG_IS_NOT_OP))) return LOGICAL_NOT; else if (TL::Bool(_ref.get_attribute(<API key>))) return BITWISE_NOT; else if (TL::Bool(_ref.get_attribute(<API key>))) return REFERENCE; else if (TL::Bool(_ref.get_attribute(<API key>))) return DERREFERENCE; else if (TL::Bool(_ref.get_attribute(<API key>))) return PREINCREMENT; else if (TL::Bool(_ref.get_attribute(<API key>))) return PREDECREMENT; else if (TL::Bool(_ref.get_attribute(<API key>))) return POSTINCREMENT; else if (TL::Bool(_ref.get_attribute(<API key>))) return POSTDECREMENT; } else if (is_binary_operation()) { if (TL::Bool(_ref.get_attribute(LANG_IS_MULT_OP))) return MULTIPLICATION; else if (TL::Bool(_ref.get_attribute(LANG_IS_DIVISION_OP))) return DIVISION; else if (TL::Bool(_ref.get_attribute(LANG_IS_MODULUS_OP))) return MODULUS; else if (TL::Bool(_ref.get_attribute(LANG_IS_ADDITION_OP))) return ADDITION; else if (TL::Bool(_ref.get_attribute(<API key>))) return SUBSTRACTION; else if (TL::Bool(_ref.get_attribute(<API key>))) return SHIFT_LEFT; else if (TL::Bool(_ref.get_attribute(<API key>))) return SHIFT_RIGHT; else if (TL::Bool(_ref.get_attribute(<API key>))) return LOWER_THAN; else if (TL::Bool(_ref.get_attribute(<API key>))) return GREATER_THAN; else if (TL::Bool(_ref.get_attribute(<API key>))) return GREATER_EQUAL_THAN; else if (TL::Bool(_ref.get_attribute(<API key>))) return LOWER_EQUAL_THAN; else if (TL::Bool(_ref.get_attribute(LANG_IS_EQUAL_OP))) return COMPARISON; else if (TL::Bool(_ref.get_attribute(<API key>))) return DIFFERENT; else if (TL::Bool(_ref.get_attribute(<API key>))) return BITWISE_AND; else if (TL::Bool(_ref.get_attribute(<API key>))) return BITWISE_XOR; else if (TL::Bool(_ref.get_attribute(<API key>))) return BITWISE_OR; else if (TL::Bool(_ref.get_attribute(<API key>))) return LOGICAL_AND; else if (TL::Bool(_ref.get_attribute(<API key>))) return LOGICAL_OR; else if (TL::Bool(_ref.get_attribute(<API key>))) return MULTIPLICATION; else if (TL::Bool(_ref.get_attribute(<API key>))) return DIVISION; else if (TL::Bool(_ref.get_attribute(<API key>))) return ADDITION; else if (TL::Bool(_ref.get_attribute(<API key>))) return SUBSTRACTION; else if (TL::Bool(_ref.get_attribute(<API key>))) return SHIFT_LEFT; else if (TL::Bool(_ref.get_attribute(<API key>))) return SHIFT_RIGHT; else if (TL::Bool(_ref.get_attribute(<API key>))) return BITWISE_AND; else if (TL::Bool(_ref.get_attribute(<API key>))) return BITWISE_OR; else if (TL::Bool(_ref.get_attribute(<API key>))) return BITWISE_XOR; else if (TL::Bool(_ref.get_attribute(<API key>))) return MODULUS; } return UNKNOWN; } std::string Expression::get_operator_str() { switch ((int)this->get_operation_kind()) { case ADDITION : case PLUS : return "+"; case MINUS : case SUBSTRACTION : return "-"; case LOGICAL_NOT : return "!"; case BITWISE_NOT : return "~"; case REFERENCE : return "&"; case MULTIPLICATION : case DERREFERENCE : return "*"; case POSTDECREMENT : case PREDECREMENT : return " case PREINCREMENT : case POSTINCREMENT : return "++"; case DIVISION : return "/"; case MODULUS : return "%"; case SHIFT_LEFT : return "<<"; case SHIFT_RIGHT : return ">>"; case LOWER_THAN : return "<"; case GREATER_THAN : return ">"; case GREATER_EQUAL_THAN : return ">="; case LOWER_EQUAL_THAN : return "<="; case COMPARISON : return "=="; case DIFFERENT : return "!="; case BITWISE_AND : return "&"; case BITWISE_XOR : return "^"; case BITWISE_OR : return "|"; case LOGICAL_AND : return "&&"; case LOGICAL_OR : return "||"; default: return "??"; } } bool Expression::is_conditional() { TL::Bool b = _ref.get_attribute(<API key>); return b; } Expression Expression::<API key>() { TL::AST_t condition_expr = _ref.get_attribute(<API key>); return Expression(condition_expr, this->get_scope_link()); } Expression Expression::get_true_expression() { TL::AST_t condition_expr = _ref.get_attribute(<API key>); return Expression(condition_expr, this->get_scope_link()); } Expression Expression::<API key>() { TL::AST_t condition_expr = _ref.get_attribute(<API key>); return Expression(condition_expr, this->get_scope_link()); } Type Expression::get_type() { bool _dummy; return get_type(_dummy); } Type Expression::get_type(bool &is_lvalue) { // We need access to the inner representation of the tree AST_t expr = this->_ref; AST expr_tree = expr._ast; type_t* expression_type = ASTExprType(expr_tree); is_lvalue = ASTExprLvalue(expr_tree); Type result(expression_type); return result; } // Do not use this one, instead use get_declared_symbol // since this one will not work for type-names IdExpression DeclaredEntity::get_declared_entity() { AST_t declared_name = _ref.get_attribute(LANG_DECLARED_NAME); Source declared_name_str = declared_name.prettyprint(); Scope sc = this->_scope_link.get_scope(declared_name); AST_t expression_ast = declared_name_str.parse_expression(this->_ref, this->_scope_link); Expression expression(expression_ast, this->_scope_link); return expression.get_id_expression(); } AST_t DeclaredEntity::get_declared_tree() { AST_t declared_name = _ref.get_attribute(LANG_DECLARED_NAME); return declared_name; } Symbol DeclaredEntity::get_declared_symbol() { AST_t declared_name = _ref.get_attribute(LANG_DECLARED_NAME); Scope sc = this->_scope_link.get_scope(declared_name); Symbol symbol = sc.<API key>(declared_name); return symbol; } DeclarationSpec Declaration::<API key>() { AST_t <API key> = _ref.get_attribute(<API key>); DeclarationSpec result(<API key>, this->_scope_link); return result; } TypeSpec DeclarationSpec::get_type_spec() { AST_t tree = _ref.get_attribute(LANG_TYPE_SPECIFIER); return TypeSpec(tree, this->_scope_link); } bool TypeSpec::is_class_specifier() { TL::Bool b = _ref.get_attribute(<API key>); return b; } Symbol TypeSpec::get_class_symbol() { TL::Symbol sym = _ref.get_attribute(<API key>); return sym; } bool TypeSpec::is_enum_specifier() { TL::Bool b = _ref.get_attribute(<API key>); return b; } Symbol TypeSpec::get_enum_symbol() { TL::Symbol sym = _ref.get_attribute(<API key>); return sym; } bool DeclaredEntity::has_initializer() { AST_t initializer = _ref.get_attribute(LANG_INITIALIZER); return initializer.is_valid(); } Expression DeclaredEntity::get_initializer() { AST_t initializer = _ref.get_attribute(LANG_INITIALIZER); return Expression(initializer, this->_scope_link); } ObjectList<DeclaredEntity> Declaration::<API key>() { PredicateAST<<API key>> <API key>; AST_t declarators_tree = this->_ref.get_attribute(<API key>); ObjectList<AST_t> declared_symbols = declarators_tree.depth_subtrees(<API key>, AST_t::NON_RECURSIVE); ObjectList<DeclaredEntity> result; for (ObjectList<AST_t>::iterator it = declared_symbols.begin(); it != declared_symbols.end(); it++) { DeclaredEntity declared(*it, this->_scope_link); result.push_back(declared); } return result; } bool ForStatement::check_statement() { TL::Bool b = this->_ref.get_attribute(<API key>); if (!b) { std::cerr << "The given statement is not a for statement" << std::endl; } return b; } void ForStatement::<API key>() { // First gather init expression and lower bound // // std::cerr << "Gathering for-init-construct" << std::endl; AST_t init_expr = _ref.get_attribute(<API key>); TL::Bool is_expression = init_expr.get_attribute(<API key>); if (is_expression) { // // std::cerr << "Is an expression" << std::endl; Expression expr(init_expr, _scope_link); if (expr.is_assignment()) { // std::cerr << "Is an assignment" << std::endl; Expression lhs_assignment = expr.get_first_operand(); Expression rhs_assignment = expr.get_second_operand(); if (lhs_assignment.is_id_expression()) { // std::cerr << "LHS of expression is id_expression" << std::endl; _induction_variable = lhs_assignment.get_ast(); _lower_bound = rhs_assignment.get_ast(); } } } TL::Bool is_declaration = init_expr.get_attribute(LANG_IS_DECLARATION); if (is_declaration) { // std::cerr << "Is a declaration" << std::endl; Declaration declaration(init_expr, this->_scope_link); ObjectList<DeclaredEntity> declared_symbols = declaration.<API key>(); if (declared_symbols.size() == 1) { // std::cerr << "Only one declared, ok" << std::endl; DeclaredEntity declared_name = *(declared_symbols.begin()); _induction_variable = declared_name.get_declared_tree(); AST_t initializer = declared_name.get_initializer().get_ast(); _lower_bound = initializer; } } // std::cerr << "Induction variable '" << _induction_variable.prettyprint() << "'" << std::endl; // std::cerr << "Lower bound '" << _lower_bound.prettyprint() << "'" << std::endl; // Now gather upper bound // std::cerr << "Gathering upper bound" << std::endl; AST_t condition = _ref.get_attribute(LANG_FOR_CONDITION); is_expression = condition.get_attribute(<API key>); if (is_expression) { // std::cerr << "Upper bound is an expression, ok" << std::endl; Expression expression(condition, _scope_link); if (expression.is_binary_operation()) { // std::cerr << "Upper bound appears in a binary expression" << std::endl; Expression right_hand = expression.get_second_operand(); switch ((int)expression.get_operation_kind()) { case Expression::LOWER_THAN: { Source adjust_value; adjust_value << "(" << right_hand.get_ast().prettyprint() << ") - 1"; _upper_bound = adjust_value.parse_expression(expression.get_ast(), expression.get_scope_link()); break; } case Expression::GREATER_THAN: { Source adjust_value; adjust_value << "(" << right_hand.get_ast().prettyprint() << ") + 1"; _upper_bound = adjust_value.parse_expression(expression.get_ast(), expression.get_scope_link()); break; } case Expression::LOWER_EQUAL_THAN : case Expression::GREATER_EQUAL_THAN : { _upper_bound = right_hand.get_ast(); break; } } } // std::cerr << "Upper bound is '" << _upper_bound.prettyprint() << "'" << std::endl; } // Now get the step AST_t <API key> = _ref.get_attribute(<API key>); if (<API key>.is_valid()) { Expression <API key>(<API key>, _scope_link); if (<API key>.is_unary_operation()) { switch ((int)<API key>.get_operation_kind()) { case Expression::PREINCREMENT : case Expression::POSTINCREMENT : { // var++ // ++var Source step; step << "1"; _step = step.parse_expression(<API key>.get_ast(), <API key>.get_scope_link()); break; } case Expression::PREDECREMENT : case Expression::POSTDECREMENT : { // var-- // --var Source step; step << "-1"; _step = step.parse_expression(<API key>.get_ast(), <API key>.get_scope_link()); break; } } } else if (<API key>.is_assignment()) { Expression <API key> = <API key>.get_second_operand(); if (<API key>.is_binary_operation()) { switch ((int)<API key>.get_operation_kind()) { case Expression::ADDITION : { // var = var + incr // var = incr + var Expression first_sumand = <API key>.get_first_operand(); Expression second_sumand = <API key>.get_first_operand(); if (first_sumand.is_id_expression()) { _step = second_sumand.get_ast(); } else if (second_sumand.is_id_expression()) { _step = first_sumand.get_ast(); } break; } case Expression::SUBSTRACTION : { // var = var - incr Expression subtrahend = <API key>.get_second_operand(); _step = subtrahend.get_ast(); break; } } } } else if (<API key>.<API key>()) { Expression <API key> = <API key>.get_second_operand(); switch ((int)<API key>.get_operation_kind()) { case Expression::ADDITION : { _step = <API key>.get_ast(); break; } case Expression::SUBSTRACTION : { Source adjust; adjust << " - (" << <API key>.get_ast().prettyprint() << ")"; _step = adjust.parse_expression(<API key>.get_ast(), <API key>.get_scope_link()); break; } } } } } bool ForStatement::regular_loop() { return (_induction_variable.is_valid() && _lower_bound.is_valid() && _upper_bound.is_valid() && _step.is_valid()); } IdExpression ForStatement::<API key>() { IdExpression result(_induction_variable, _scope_link); return result; } Expression ForStatement::get_lower_bound() { Expression result(_lower_bound, _scope_link); return result; } Expression ForStatement::get_upper_bound() { Expression result(_upper_bound, _scope_link); return result; } Expression ForStatement::get_step() { Expression result(_step, _scope_link); return result; } Statement ForStatement::get_loop_body() { AST_t loop_body = _ref.get_attribute(<API key>); Statement result(loop_body, _scope_link); return result; } AST_t ForStatement::get_iterating_init() { AST_t result = _ref.get_attribute(<API key>); return result; } Expression ForStatement::<API key>() { Expression result(_ref.get_attribute(LANG_FOR_CONDITION), _scope_link); return result; } Expression ForStatement::<API key>() { Expression result(_ref.get_attribute(<API key>), _scope_link); return result; } bool DeclaredEntity::<API key>() { TL::Bool b = _ref.get_attribute(<API key>); return b; } // A traverse functor only for the first level of parameter declarations // (We want to avoid finding inner parameters of pointer-to-function // parameters) class TraverseParameters : public Functor<ASTTraversalResult, AST_t> { private: PredicateAST<<API key>> _pred; public: ASTTraversalResult operator()(AST_t& a) const { bool match = _pred(a); bool recurse = !match; return <API key>(match, recurse); } }; ObjectList<<API key>> DeclaredEntity::<API key>() { bool _dummy; return <API key>(_dummy); } ObjectList<<API key>> DeclaredEntity::<API key>(bool &has_ellipsis) { ObjectList<<API key>> result; Symbol symbol = get_declared_symbol(); Type type = symbol.get_type(); if (!type.is_function()) { std::cerr << "Error: Entity '" << _ref.prettyprint() << "' in '" << _ref.get_locus() << "' is not a function type" << std::endl; return result; } ObjectList<Type> parameter_types = type.parameters(has_ellipsis); // This avoids problems with the case 'f(void)' where we have // some sort of declarations but the computed type does not. if (parameter_types.empty()) { return result; } TraverseParameters <API key>; ObjectList<AST_t> <API key> = _ref.depth_subtrees(<API key>); ObjectList<Type>::iterator it_type = parameter_types.begin(); ObjectList<AST_t>::iterator it_tree = <API key>.begin(); while (it_tree != <API key>.end()) { <API key> parameter_decl(*it_tree, _scope_link, *it_type); result.append(parameter_decl); it_tree++; it_type++; } return result; } bool <API key>::is_named() { TL::Bool b = _ref.get_attribute(<API key>); return b; } IdExpression <API key>::get_name() { AST_t declaration = _ref.get_attribute(<API key>); return IdExpression(declaration, _scope_link); } ObjectList<GCCAttribute> <API key>::<API key>() { ObjectList<GCCAttribute> result; AST_t list = _ref.get_attribute(<API key>); if (list.is_valid()) { ASTIterator iterator = list.get_list_iterator(); iterator.rewind(); while (!iterator.end()) { GCCAttribute current_attribute(iterator.item(), _scope_link); result.append(current_attribute); iterator.next(); } } return result; } std::string GCCAttribute::get_name() { AST_t tree = _ref.get_attribute(<API key>); return _ref.get_text(); } bool GCCAttribute::has_argument_list() const { AST_t tree = _ref.get_attribute(<API key>); return tree.is_valid(); } ObjectList<Expression> GCCAttribute::get_argument_list() { ObjectList<Expression> result; AST_t tree = _ref.get_attribute(<API key>); ASTIterator it = tree.get_list_iterator(); it.rewind(); while (!it.end()) { Expression expr(it.item(), _scope_link); result.append(expr); it.next(); } return result; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_31) on Mon Apr 06 15:30:26 CEST 2015 --> <title>DelayMatrix_Float</title> <meta name="date" content="2015-04-06"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DelayMatrix_Float"; } } catch(err) { } var methods = {"i0":10,"i1":10,"i2":10,"i3":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DelayMatrix_Float.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../org/cloudbus/cloudsim/network/FloydWarshall_Float.html" title="class in org.cloudbus.cloudsim.network"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/cloudbus/cloudsim/network/DelayMatrix_Float.html" target="_top">Frames</a></li> <li><a href="DelayMatrix_Float.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <div class="subTitle">org.cloudbus.cloudsim.network</div> <h2 title="Class DelayMatrix_Float" class="title">Class DelayMatrix_Float</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.cloudbus.cloudsim.network.DelayMatrix_Float</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">DelayMatrix_Float</span> extends java.lang.Object</pre> <div class="block">This class represents an delay-topology storing every distance between connected nodes</div> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>CloudSim Toolkit 1.0</dd> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>Thomas Hohnstein</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field.summary"> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected float[][]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#mDelayMatrix">mDelayMatrix</a></span></code> <div class="block">matrix holding delay information between any two nodes</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#mTotalNodeNum">mTotalNodeNum</a></span></code> <div class="block">number of nodes in the <API key></div> </td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier</th> <th class="colLast" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private </code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#DelayMatrix_Float--">DelayMatrix_Float</a></span>()</code> <div class="block">private constructor to ensure that only an correct initialized delay-matrix could be created</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#<API key>.cloudbus.cloudsim.network.<API key>-">DelayMatrix_Float</a></span>(<a href="../../../../org/cloudbus/cloudsim/network/TopologicalGraph.html" title="class in org.cloudbus.cloudsim.network">TopologicalGraph</a>&nbsp;graph, boolean&nbsp;directed)</code> <div class="block">this constructor creates an correct initialized Float-Delay-Matrix</div> </td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method.summary"> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>private void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#<API key>--"><API key></a></span>()</code> <div class="block">just calculates all pairs shortest paths</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>private void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#<API key>.cloudbus.cloudsim.network.<API key>-">createDelayMatrix</a></span>(<a href="../../../../org/cloudbus/cloudsim/network/TopologicalGraph.html" title="class in org.cloudbus.cloudsim.network">TopologicalGraph</a>&nbsp;graph, boolean&nbsp;directed)</code> <div class="block">creates all internal necessary network-distance structures from the given graph for similarity we assume all <API key> are symmetrical thus leads to an undirected network</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>float</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#getDelay-int-int-">getDelay</a></span>(int&nbsp;srcID, int&nbsp;destID)</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/cloudbus/cloudsim/network/DelayMatrix_Float.html#toString--">toString</a></span>()</code> <div class="block">this method just creates an string-output from the internal structures...</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="field.detail"> </a> <h3>Field Detail</h3> <a name="mDelayMatrix"> </a> <ul class="blockList"> <li class="blockList"> <h4>mDelayMatrix</h4> <pre>protected&nbsp;float[][] mDelayMatrix</pre> <div class="block">matrix holding delay information between any two nodes</div> </li> </ul> <a name="mTotalNodeNum"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>mTotalNodeNum</h4> <pre>protected&nbsp;int mTotalNodeNum</pre> <div class="block">number of nodes in the <API key></div> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> </a> <h3>Constructor Detail</h3> <a name="DelayMatrix_Float </a> <ul class="blockList"> <li class="blockList"> <h4>DelayMatrix_Float</h4> <pre>private&nbsp;DelayMatrix_Float()</pre> <div class="block">private constructor to ensure that only an correct initialized delay-matrix could be created</div> </li> </ul> <a name="<API key>.cloudbus.cloudsim.network.<API key>-"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DelayMatrix_Float</h4> <pre>public&nbsp;DelayMatrix_Float(<a href="../../../../org/cloudbus/cloudsim/network/TopologicalGraph.html" title="class in org.cloudbus.cloudsim.network">TopologicalGraph</a>&nbsp;graph, boolean&nbsp;directed)</pre> <div class="block">this constructor creates an correct initialized Float-Delay-Matrix</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>graph</code> - the topological graph as source-information</dd> <dd><code>directed</code> - true if an directed matrix should be computed, false otherwise</dd> </dl> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method.detail"> </a> <h3>Method Detail</h3> <a name="getDelay-int-int-"> </a> <ul class="blockList"> <li class="blockList"> <h4>getDelay</h4> <pre>public&nbsp;float&nbsp;getDelay(int&nbsp;srcID, int&nbsp;destID)</pre> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>srcID</code> - the id of the source-node</dd> <dd><code>destID</code> - the id of the destination-node</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the delay-count between the given two nodes</dd> </dl> </li> </ul> <a name="<API key>.cloudbus.cloudsim.network.<API key>-"> </a> <ul class="blockList"> <li class="blockList"> <h4>createDelayMatrix</h4> <pre>private&nbsp;void&nbsp;createDelayMatrix(<a href="../../../../org/cloudbus/cloudsim/network/TopologicalGraph.html" title="class in org.cloudbus.cloudsim.network">TopologicalGraph</a>&nbsp;graph, boolean&nbsp;directed)</pre> <div class="block">creates all internal necessary network-distance structures from the given graph for similarity we assume all <API key> are symmetrical thus leads to an undirected network</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>graph</code> - this graph contains all node and link information</dd> <dd><code>directed</code> - defines to preinitialize an directed or undirected Delay-Matrix!</dd> </dl> </li> </ul> <a name="<API key> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>private&nbsp;void&nbsp;<API key>()</pre> <div class="block">just calculates all pairs shortest paths</div> </li> </ul> <a name="toString </a> <ul class="blockListLast"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block">this method just creates an string-output from the internal structures... eg. printsout the delay-matrix...</div> <dl> <dt><span class="<API key>">Overrides:</span></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DelayMatrix_Float.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../org/cloudbus/cloudsim/network/FloydWarshall_Float.html" title="class in org.cloudbus.cloudsim.network"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/cloudbus/cloudsim/network/DelayMatrix_Float.html" target="_top">Frames</a></li> <li><a href="DelayMatrix_Float.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
//#define NOTWINDOWSH //#define NEEDMFCH //#define NEEDAFXDLGSH #include "stdafx.h" #include "BoneLineDlg.h" #include <Commdlg.h> //#include <Afxdlgs.h> #include <shdelem.h> #include "ColDlg.h" extern CColDlg g_coldlg; // CBoneLineDlg CBoneLineDlg::CBoneLineDlg() { InitParams(); } CBoneLineDlg::~CBoneLineDlg() { } int CBoneLineDlg::InitParams() { m_selcol = RGB( 255, 255, 255 ); m_unselcol = RGB( 255, 255, 255 ); m_selem = 0; m_bonelinedisp = 1; m_checkchild = 0; return 0; } int CBoneLineDlg::SetSelemParam( CShdElem* srcselem ) { if( !srcselem ){ _ASSERT( 0 ); return 0; } m_selem = srcselem; m_bonelinedisp = m_selem->m_bonelinedisp; m_checkchild = 0; return 0; } LRESULT CBoneLineDlg::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { SetWnd(); ParamsToDlg(); return 1; } LRESULT CBoneLineDlg::OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { UINT checkflag; checkflag = m_dlg_wnd.IsDlgButtonChecked( IDC_CHECK_CHILD ); if( checkflag == BST_CHECKED ){ m_checkchild = 1; }else if( checkflag == BST_UNCHECKED ){ m_checkchild = 0; } checkflag = m_dlg_wnd.IsDlgButtonChecked( IDC_RADIO_DODISP ); if( checkflag == BST_CHECKED ){ m_bonelinedisp = 1; }else if( checkflag == BST_UNCHECKED ){ m_bonelinedisp = 0; } if( m_selem ){ if( m_checkchild ){ m_selem->SetBoneLineDispReq( m_bonelinedisp, 0 ); }else{ m_selem->m_bonelinedisp = m_bonelinedisp; } }else{ DbgOut( "BoneLineDlg : OnOK : selem NULL warning !!!\n" ); _ASSERT( 0 ); } EndDialog(wID); return 0; } LRESULT CBoneLineDlg::OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { EndDialog(wID); return 0; } void CBoneLineDlg::SetWnd() { m_dlg_wnd = m_hWnd; m_selcol_wnd = GetDlgItem( IDC_SELCOL ); m_unselcol_wnd = GetDlgItem( IDC_UNSELCOL ); m_checkchild_wnd = GetDlgItem( IDC_CHECK_CHILD ); } int CBoneLineDlg::ParamsToDlg() { //check if( m_checkchild ){ m_dlg_wnd.CheckDlgButton( IDC_CHECK_CHILD, BST_CHECKED ); }else{ m_dlg_wnd.CheckDlgButton( IDC_CHECK_CHILD, BST_UNCHECKED ); } //radio if( m_bonelinedisp == 0 ){ m_dlg_wnd.CheckRadioButton( IDC_RADIO_NOTDISP, IDC_RADIO_DODISP, IDC_RADIO_NOTDISP ); }else{ m_dlg_wnd.CheckRadioButton( IDC_RADIO_NOTDISP, IDC_RADIO_DODISP, IDC_RADIO_DODISP ); } return 0; } LRESULT CBoneLineDlg::OnRefSelCol(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { int ret; ret = g_coldlg.Choose( m_hWnd, &m_selcol ); if( ret ){ BOOL dummy; OnPaint( 0, 0, 0, dummy ); } return 0; } LRESULT CBoneLineDlg::OnRefUnSelCol(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { int ret; ret = g_coldlg.Choose( m_hWnd, &m_unselcol ); if( ret ){ BOOL dummy; OnPaint( 0, 0, 0, dummy ); } return 0; } LRESULT CBoneLineDlg::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { bHandled = FALSE; int ret; ret = FillColorGDI( m_selcol, m_selcol_wnd ); _ASSERT( !ret ); ret = FillColorGDI( m_unselcol, m_unselcol_wnd ); _ASSERT( !ret ); return 0; } int CBoneLineDlg::FillColorGDI( COLORREF srccol, CWindow srcwnd ) { HBRUSH brush; brush = ::CreateSolidBrush( srccol ); _ASSERT( brush != NULL ); HDC hdc; hdc = srcwnd.GetDC(); RECT clirect; srcwnd.GetClientRect( &clirect ); HBRUSH hOldBrush = (HBRUSH)SelectObject( hdc, brush ); BOOL bret; bret = ::Rectangle( hdc, clirect.left, clirect.top, clirect.right, clirect.bottom ); _ASSERT( bret ); ::SelectObject( hdc, hOldBrush ); srcwnd.ReleaseDC( hdc ); return 0; }
package com.github.janpeuker.<API key>.springbootreactive.repository; import com.github.janpeuker.<API key>.springbootreactive.Application; import com.github.janpeuker.<API key>.springbootreactive.repository.StocksRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.<API key>; import org.springframework.test.context.junit4.<API key>; import static org.junit.Assert.*; @RunWith(<API key>.class) @<API key>(classes = Application.class) public class <API key> { @Autowired private StocksRepository stocksRepository; @Test public void <API key>() throws Exception { assertTrue(stocksRepository.<API key>("NASDAQ").size() > 0); } @Test public void testGetStock() throws Exception { assertEquals("GOOG", stocksRepository.getStock("GOOG").getSymbol()); } }
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by gtLib.rc #define <API key> 5000 #define <API key> 5001 #define ID_WAVEFORM_WND 5002 #define ID_XYGRAPH_WND 5003 #define ID_LEGEND_WND 5004 #define ID_SELECT_POINT 5005 #define IDC_CHECK1 5022 #define <API key> 5138 #define <API key> 5139 #define IDC_CURSOR_LEFTTOP 5140 #define <API key> 5141 #define <API key> 6000 #define <API key> 6000 #define <API key> 6001 #define <API key> 6001 #define <API key> 6002 #define IDC_EDIT_X_MAX 6003 #define <API key> 6004 #define IDC_EDIT_X_MIN 6005 #define <API key> 6006 #define IDC_EDIT_X_GRID 6006 #define <API key> 6007 #define IDC_EDIT_X_SUB_GRID 6008 #define IDC_EDIT_X_TICK 6008 #define IDC_EDIT_Y_MAX 6009 #define IDC_EDIT_Y_MIN 6010 #define <API key> 6011 #define IDC_EDIT_Y_GRID 6011 #define IDC_EDIT_Y_SUB_GRID 6012 #define IDC_EDIT_Y_TICK 6012 #define <API key> 6013 #define <API key> 6014 #define <API key> 6014 #define IDC_EDIT_X_TITLE 6015 #define <API key> 6016 #define <API key> 6016 #define IDC_EDIT_Y_TITLE 6017 #define <API key> 6018 #define <API key> 6019 #define <API key> 6020 // Next default values for new objects #ifdef APSTUDIO_INVOKED #ifndef <API key> #define <API key> 5142 #define <API key> 32771 #define <API key> 5023 #define <API key> 5006 #endif #endif
#include "tagresourcerequest.h" #include "<API key>.h" #include "tagresourceresponse.h" #include "<API key>.h" namespace QtAws { namespace SSMContacts { /*! * \class QtAws::SSMContacts::TagResourceRequest * \brief The TagResourceRequest class provides an interface for SSMContacts TagResource requests. * * \inmodule QtAwsSSMContacts * * * \sa SSMContactsClient::tagResource */ /*! * Constructs a copy of \a other. */ TagResourceRequest::TagResourceRequest(const TagResourceRequest &other) : SSMContactsRequest(new <API key>(*other.d_func(), this)) { } /*! * Constructs a TagResourceRequest object. */ TagResourceRequest::TagResourceRequest() : SSMContactsRequest(new <API key>(SSMContactsRequest::TagResourceAction, this)) { } /*! * \reimp */ bool TagResourceRequest::isValid() const { return false; } /*! * Returns a TagResourceResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * TagResourceRequest::response(QNetworkReply * const reply) const { return new TagResourceResponse(*this, reply); } /*! * \class QtAws::SSMContacts::<API key> * \brief The <API key> class provides private implementation for TagResourceRequest. * \internal * * \inmodule QtAwsSSMContacts */ /*! * Constructs a <API key> object for SSMContacts \a action, * with public implementation \a q. */ <API key>::<API key>( const SSMContactsRequest::Action action, TagResourceRequest * const q) : <API key>(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the TagResourceRequest * class' copy constructor. */ <API key>::<API key>( const <API key> &other, TagResourceRequest * const q) : <API key>(other, q) { } } // namespace SSMContacts } // namespace QtAws
/** \file BuiltinDataType.h * \brief Header file providing the BuiltinDataType class interface */ #ifndef <API key> #define <API key> #include <variant_topic_tools/BuiltinTypeTraits.h> #include <variant_topic_tools/DataType.h> namespace variant_topic_tools { /** \brief Built-in data type */ class BuiltinDataType : public DataType { friend class DataType; friend class DataTypeRegistry; public: /** \brief Default constructor */ BuiltinDataType(); /** \brief Copy constructor */ BuiltinDataType(const BuiltinDataType& src); /** \brief Copy constructor (overloaded version taking a data type) */ BuiltinDataType(const DataType& src); /** \brief Destructor */ virtual ~BuiltinDataType(); /** \brief Assignment operator */ BuiltinDataType& operator=(const DataType& src); /** \brief True, if this built-in data type is numeric */ bool isNumeric() const; protected: /** \brief Built-in data type implementation */ class Impl : public DataType::Impl { public: /** \brief Constructor */ Impl(const std::string& identifier); /** \brief Destructor */ virtual ~Impl(); /** \brief Retrieve the identifier representing this data type * (implementation) */ const std::string& getIdentifier() const; /** \brief True, if this built-in data type is numeric (abstract * declaration) */ virtual bool isNumeric() const = 0; /** \brief The identifier representing this built-in data type */ std::string identifier; }; /** \brief Built-in data type implementation (templated strong-typed * version) */ template <typename T> class ImplT : public Impl { public: BOOST_STATIC_ASSERT(type_traits::IsBuiltin<T>::value); /** \brief Constructor */ ImplT(const std::string& identifier); /** \brief Destructor */ virtual ~ImplT(); /** \brief Retrieve the type information associated with this data type * (re-implementation) */ const std::type_info& getTypeInfo() const; /** \brief Retrieve the size of the instances of this data type * (implementation) */ size_t getSize() const; /** \brief True, if this data type represents a fixed-size data type * (implementation) */ bool isFixedSize() const; /** \brief True, if this data type represents a simple data type * (implementation) */ bool isSimple() const; /** \brief True, if this built-in data type is numeric (implementation) */ bool isNumeric() const; /** \brief Create a serializer for this data type (re-implementation) */ Serializer createSerializer(const DataType& type) const; /** \brief Create a variant from this data type (re-implementation) */ Variant createVariant(const DataType& type) const; }; /** \brief Create a built-in data type */ template <typename T> static BuiltinDataType create(const std::string& identifier); }; }; #include <variant_topic_tools/BuiltinDataType.tpp> #endif
package com.arthurportas.mongodb.example.repository; import com.arthurportas.mongodb.example.domain.User; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends MongoRepository<User, String>{ }
import os from django.core.wsgi import <API key> os.environ.setdefault("<API key>", "patchwatcher2.settings") application = <API key>()
package fr.univavignon.graphcentr.tests.g01; import fr.univavignon.graphcentr.g01.Clique; import fr.univavignon.graphcentr.g07.core.centrality.CentralityResult; import fr.univavignon.graphcentr.g07.core.graphs.SimpleGraph; /** * @author Riviere Colin, Benoit Loris * */ public class CliqueTest { /** * Execute Clique Test */ public static void execute() { SimpleGraph graph = new SimpleGraph(); graph.createNode(); graph.createNode(); graph.createNode(); graph.createNode(); graph.createNode(); graph.createNode(); graph.createNode(); graph.createNode(); graph.createLink(0, 1); graph.createLink(0, 2); graph.createLink(0, 3); graph.createLink(1, 2); graph.createLink(1, 3); graph.createLink(2, 3); graph.createLink(3, 4); graph.createLink(3, 5); graph.createLink(3, 6); graph.createLink(3, 7); graph.createLink(6, 7); Clique centrality = new Clique(); CentralityResult result = centrality.evaluate(graph); System.out.println(result); } }
package cx.ath.jbzdak.ioCommons.termios; import cx.ath.jbzdak.ioCommons.PortException; public class <API key> extends PortException{ public <API key>(Throwable cause) { super(cause); } public <API key>(String message) { super(message); } public <API key>(String message, Throwable cause) { super(message, cause); } }
package com.sinhika.bark.entities; import java.util.List; import com.sinhika.bark.items.ModItems; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityBoat; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.world.World; /** * Too much of this class is a cut & paste of EntityBoat, because EntityBoat makes * all its internal fields private, and thus not inheritable. Bad design, Mojang!! * * @author Sinhika * */ public class EntityCanoe extends EntityBoat { /* make these stupid fields PROTECTED, not private (bad Mojang!) so children can * inherit without re-writing half the class methods. */ /** true if no player in boat */ protected boolean isBoatEmpty; protected double speedMultiplier; protected int <API key>; protected double boatX; protected double boatY; protected double boatZ; protected double boatYaw; protected double boatPitch; @SideOnly(Side.CLIENT) protected double velocityX; @SideOnly(Side.CLIENT) protected double velocityY; @SideOnly(Side.CLIENT) protected double velocityZ; public EntityCanoe(World par1World) { super(par1World); this.isBoatEmpty = true; this.speedMultiplier = 0.07D; } public EntityCanoe(World par1World, double par2, double par4, double par6) { this(par1World); this.setPosition(par2, par4 + (double)this.yOffset, par6); this.motionX = 0.0D; this.motionY = 0.0D; this.motionZ = 0.0D; this.prevPosX = par2; this.prevPosY = par4; this.prevPosZ = par6; } /** * Sets the position and rotation. Only difference from the other one is no bounding on the rotation. Args: posX, * posY, posZ, yaw, pitch. copied because accesses *new* protected variables that are same name as hidden * private variables. */ @SideOnly(Side.CLIENT) public void <API key>(double par1, double par3, double par5, float par7, float par8, int par9) { if (this.isBoatEmpty) { this.<API key> = par9 + 5; } else { double d3 = par1 - this.posX; double d4 = par3 - this.posY; double d5 = par5 - this.posZ; double d6 = d3 * d3 + d4 * d4 + d5 * d5; if (d6 <= 1.0D) { return; } this.<API key> = 3; } this.boatX = par1; this.boatY = par3; this.boatZ = par5; this.boatYaw = (double)par7; this.boatPitch = (double)par8; this.motionX = this.velocityX; this.motionY = this.velocityY; this.motionZ = this.velocityZ; } /** * Sets the velocity to the args. Args: x, y, z * copied because accesses *new* protected variables that are same name as hidden * private variables. */ @SideOnly(Side.CLIENT) public void setVelocity(double par1, double par3, double par5) { this.velocityX = this.motionX = par1; this.velocityY = this.motionY = par3; this.velocityZ = this.motionZ = par5; } public void updateRiderPosition() { if (this.riddenByEntity != null) { double d0 = Math.cos((double)this.rotationYaw * Math.PI / 180.0D) * 0.4D; double d1 = Math.sin((double)this.rotationYaw * Math.PI / 180.0D) * 0.4D; this.riddenByEntity.setPosition(this.posX + d0, this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset(), this.posZ + d1); } } /* (non-Javadoc) * @see net.minecraft.entity.item.EntityBoat#onUpdate() */ @SuppressWarnings("rawtypes") @Override public void onUpdate() { this.onEntityUpdate(); if (this.getTimeSinceHit() > 0) { this.setTimeSinceHit(this.getTimeSinceHit() - 1); } if (this.getDamageTaken() > 0.0F) { this.setDamageTaken(this.getDamageTaken() - 1.0F); } this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; byte b0 = 5; double d0 = 0.0D; for (int i = 0; i < b0; ++i) { double d1 = this.boundingBox.minY + (this.boundingBox.maxY - this.boundingBox.minY) * (double)(i + 0) / (double)b0 - 0.125D; double d3 = this.boundingBox.minY + (this.boundingBox.maxY - this.boundingBox.minY) * (double)(i + 1) / (double)b0 - 0.125D; AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(this.boundingBox.minX, d1, this.boundingBox.minZ, this.boundingBox.maxX, d3, this.boundingBox.maxZ); if (this.worldObj.isAABBInMaterial(axisalignedbb, Material.water)) { d0 += 1.0D / (double)b0; } } double d10 = Math.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ); double d2; double d4; int j; if (d10 > 0.26249999999999996D) { d2 = Math.cos((double)this.rotationYaw * Math.PI / 180.0D); d4 = Math.sin((double)this.rotationYaw * Math.PI / 180.0D); for (j = 0; (double)j < 1.0D + d10 * 60.0D; ++j) { double d5 = (double)(this.rand.nextFloat() * 2.0F - 1.0F); double d6 = (double)(this.rand.nextInt(2) * 2 - 1) * 0.7D; double d8; double d9; if (this.rand.nextBoolean()) { d8 = this.posX - d2 * d5 * 0.8D + d4 * d6; d9 = this.posZ - d4 * d5 * 0.8D - d2 * d6; this.worldObj.spawnParticle("splash", d8, this.posY - 0.125D, d9, this.motionX, this.motionY, this.motionZ); } else { d8 = this.posX + d2 + d4 * d5 * 0.7D; d9 = this.posZ + d4 - d2 * d5 * 0.7D; this.worldObj.spawnParticle("splash", d8, this.posY - 0.125D, d9, this.motionX, this.motionY, this.motionZ); } } } double d11; double d12; if (this.worldObj.isRemote && this.isBoatEmpty) { if (this.<API key> > 0) { d2 = this.posX + (this.boatX - this.posX) / (double)this.<API key>; d4 = this.posY + (this.boatY - this.posY) / (double)this.<API key>; d11 = this.posZ + (this.boatZ - this.posZ) / (double)this.<API key>; d12 = MathHelper.<API key>(this.boatYaw - (double)this.rotationYaw); this.rotationYaw = (float)((double)this.rotationYaw + d12 / (double)this.<API key>); this.rotationPitch = (float)((double)this.rotationPitch + (this.boatPitch - (double)this.rotationPitch) / (double)this.<API key>); --this.<API key>; this.setPosition(d2, d4, d11); this.setRotation(this.rotationYaw, this.rotationPitch); } else { d2 = this.posX + this.motionX; d4 = this.posY + this.motionY; d11 = this.posZ + this.motionZ; this.setPosition(d2, d4, d11); if (this.onGround) { this.motionX *= 0.5D; this.motionY *= 0.5D; this.motionZ *= 0.5D; } this.motionX *= 0.9900000095367432D; this.motionY *= 0.949999988079071D; this.motionZ *= 0.9900000095367432D; } } else { if (d0 < 1.0D) { d2 = d0 * 2.0D - 1.0D; this.motionY += 0.03999999910593033D * d2; } else { if (this.motionY < 0.0D) { this.motionY /= 2.0D; } this.motionY += 0.007000000216066837D; } if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityLivingBase) { EntityLivingBase entitylivingbase = (EntityLivingBase)this.riddenByEntity; float f = this.riddenByEntity.rotationYaw + -entitylivingbase.moveStrafing * 90.0F; this.motionX += -Math.sin((double)(f * (float)Math.PI / 180.0F)) * this.speedMultiplier * (double)entitylivingbase.moveForward * 0.05000000074505806D; this.motionZ += Math.cos((double)(f * (float)Math.PI / 180.0F)) * this.speedMultiplier * (double)entitylivingbase.moveForward * 0.05000000074505806D; } d2 = Math.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ); if (d2 > 0.35D) { d4 = 0.35D / d2; this.motionX *= d4; this.motionZ *= d4; d2 = 0.35D; } if (d2 > d10 && this.speedMultiplier < 0.35D) { this.speedMultiplier += (0.35D - this.speedMultiplier) / 35.0D; if (this.speedMultiplier > 0.35D) { this.speedMultiplier = 0.35D; } } else { this.speedMultiplier -= (this.speedMultiplier - 0.07D) / 35.0D; if (this.speedMultiplier < 0.07D) { this.speedMultiplier = 0.07D; } } int l; for (l = 0; l < 4; ++l) { int i1 = MathHelper.floor_double(this.posX + ((double)(l % 2) - 0.5D) * 0.8D); j = MathHelper.floor_double(this.posZ + ((double)(l / 2) - 0.5D) * 0.8D); for (int j1 = 0; j1 < 2; ++j1) { int k = MathHelper.floor_double(this.posY) + j1; Block block = this.worldObj.getBlock(i1, k, j); if (block == Blocks.snow_layer) { this.worldObj.setBlockToAir(i1, k, j); this.<API key> = false; } else if (block == Blocks.waterlily) { this.worldObj.func_147480_a(i1, k, j, true); this.<API key> = false; } } } if (this.onGround) { this.motionX *= 0.5D; this.motionY *= 0.5D; this.motionZ *= 0.5D; } this.moveEntity(this.motionX, this.motionY, this.motionZ); // We removed the 'break on collision' code here. // birchbark canoes are resilient. this.motionX *= 0.9900000095367432D; this.motionY *= 0.949999988079071D; this.motionZ *= 0.9900000095367432D; this.rotationPitch = 0.0F; d4 = (double)this.rotationYaw; d11 = this.prevPosX - this.posX; d12 = this.prevPosZ - this.posZ; if (d11 * d11 + d12 * d12 > 0.001D) { d4 = (double)((float)(Math.atan2(d12, d11) * 180.0D / Math.PI)); } double d7 = MathHelper.<API key>(d4 - (double)this.rotationYaw); if (d7 > 20.0D) { d7 = 20.0D; } if (d7 < -20.0D) { d7 = -20.0D; } this.rotationYaw = (float)((double)this.rotationYaw + d7); this.setRotation(this.rotationYaw, this.rotationPitch); if (!this.worldObj.isRemote) { List list = this.worldObj.<API key>(this, this.boundingBox.expand(0.20000000298023224D, 0.0D, 0.20000000298023224D)); if (list != null && !list.isEmpty()) { for (int k1 = 0; k1 < list.size(); ++k1) { Entity entity = (Entity)list.get(k1); if (entity != this.riddenByEntity && entity.canBePushed() && entity instanceof EntityBoat) { entity.<API key>(this); } } } if (this.riddenByEntity != null && this.riddenByEntity.isDead) { this.riddenByEntity = null; } } } } // end OnUpdate() /** * true if no player in boat */ @SideOnly(Side.CLIENT) public void setIsBoatEmpty(boolean par1) { this.isBoatEmpty = par1; } /** * Override to get a real canoe, not a vanilla boat back. Yes, we just ignore * all the parameters and substitute our own. * (non-Javadoc) * @see net.minecraft.entity.Entity#func_145778_a(net.minecraft.item.Item, int, float) */ @Override public EntityItem func_145778_a(Item entityItem, int quantity, float p_145778_3_) { return this.entityDropItem(new ItemStack(ModItems.canoeItem, 1, 0), 0.0F); } } // end class EntityCanoe
Ext.define('Dmpc.view.ScheduleDataview', { extend: 'Ext.dataview.List', xtype: 'scheduledataview', config: { cls: 'scheduleDataView', scrollable: true, grouped: true, store: 'OfflineSchedule', itemTpl: Dmpc.view.templates.TalkListItem } });
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Raven.Client; using Raven.Client.Linq; using AutoMapper; using SwissSdr.Datamodel; using SwissSdr.Api.Resources; using SwissSdr.Api.InputModels; using SwissSdr.Api.Indexes; using System.Collections.Generic; using RestApiHelpers.Validation; using SwissSdr.Api; using SwissSdr.Api.Services; using System.Linq.Expressions; using SwissSdr.Api.Infrastructure; using System.Collections.ObjectModel; using System.Net; using SwissSdr.Api.QueryModels; using Microsoft.AspNetCore.Authorization; using SwissSdr.Api.Authorization; using SwissSdr.Api.Transformers; using SwissSdr.Api.Endpoints; using Halcyon.HAL; namespace SwissSdr.Api.Controllers { [Route(ApiConstants.Routes.Projects)] public class ProjectsController : ControllerBase, <API key>, IHasImagesEndpoint, IHasLibraryEndpoint, <API key>, IHasJobsEndpoint, <API key> { private readonly IMapper _mapper; private readonly <API key> _session; private readonly ResourceFactory _resourceFactory; private readonly <API key><ProjectsController> <API key>; private readonly ImagesEndpoint<ProjectsController> _imagesEndpoint; private readonly LibraryEndpoint<ProjectsController> _libraryEndpoint; private readonly <API key><ProjectsController> <API key>; private readonly JobsEndpoint<ProjectsController> _jobsEndpoint; private readonly PermissionsEndpoint<ProjectsController> <API key>; private readonly PermissionService _permissionService; private readonly TagService _tagService; private readonly I<API key> _<API key>; private readonly GeocodingService _geocodingService; public <API key> <API key> => <API key>; public IImagesEndpoint ImagesEndpoint => _imagesEndpoint; public ILibraryEndpoint LibraryEndpoint => _libraryEndpoint; public <API key> <API key> => <API key>; public IJobsEndpoint JobsEndpoint => _jobsEndpoint; public <API key> PermissionsEndpoint => <API key>; public ProjectsController( <API key> session, IMapper mapper, ResourceFactory resourceFactory, <API key><ProjectsController> <API key>, ImagesEndpoint<ProjectsController> imagesEndpoint, LibraryEndpoint<ProjectsController> libraryEndpoint, <API key><ProjectsController> <API key>, JobsEndpoint<ProjectsController> jobsEndpoint, PermissionsEndpoint<ProjectsController> permissionsEndpoint, PermissionService permissionService, TagService tagService, I<API key> <API key>, GeocodingService geocodingService) { _session = session; _mapper = mapper; _resourceFactory = resourceFactory; <API key> = <API key>; _imagesEndpoint = imagesEndpoint; _libraryEndpoint = libraryEndpoint; <API key> = <API key>; _jobsEndpoint = jobsEndpoint; <API key> = permissionsEndpoint; _permissionService = permissionService; _tagService = tagService; _<API key> = <API key>; _geocodingService = geocodingService; } [HttpGet] [ProducesResponse(typeof(<API key>), HttpStatusCode.OK)] public async Task<IActionResult> GetProjects(int? skip, int? take, [FromQuery]<API key> filter) { if (filter == null) { filter = new <API key>(); } <API key> statistics; var projects = await _session.QueryFrom(filter) .Statistics(out statistics) .Paged(skip, take) .TransformWith<Projects_Summary, <API key>>() .ToListAsync(); var resource = _resourceFactory.<API key><ProjectsController>( projects, skip, take, statistics.TotalResults, (s, t) => (_) => GetProjects(s, t, filter)); return Ok(resource); } [HttpGet(ApiConstants.Routes.Item)] [ProducesResponse(typeof(ProjectResource), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] public async Task<IActionResult> GetProject(int id) { var project = await _session.<API key><<API key>, DenormalizedProject>(id); var resource = <API key>(project); return Ok(resource); } [HttpPost] [Authorize(Policies.CreateProject)] [<API key>] [<API key>] [ProducesResponse(typeof(ProjectResource), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.BadRequest)] public async Task<IActionResult> CreateProject([FromBody]<API key> updateModel) { var project = new Project() { CreatedAt = DateTime.UtcNow }; _permissionService.<API key>(User, project); await UpdateModel(updateModel, project); await _session.StoreAsync(project); await _session.SaveChangesAsync(); var data = await _session.<API key><<API key>, DenormalizedProject>(project.Id); var resource = <API key>(data); return this.CreatedAtAction(c => c.GetProject(_session.GetIdValuePart(project.Id)), resource); } [HttpPut(ApiConstants.Routes.Item)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ProjectResource), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.BadRequest)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> UpdateProject(int id, [FromBody]<API key> updateModel) { var project = await _session.<API key><Project>(id); if (await _<API key>.AuthorizeEditAsync(User, project)) { await UpdateModel(updateModel, project); await _session.SaveChangesAsync(); return await GetProject(id); } return Forbid(); } [HttpDelete(ApiConstants.Routes.Item)] [Authorize(Policies.Authenticated)] [ProducesResponse(HttpStatusCode.NoContent)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> DeleteProject(int id) { var project = await _session.<API key><Project>(id); if (await _<API key>.<API key>(User, project)) { _session.Delete(project); await _session.SaveChangesAsync(); return NoContent(); } return Forbid(); } [HttpGet(ApiConstants.Routes.Associations)] [ProducesResponse(typeof(ItemsResource<<API key>>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] public async Task<IActionResult> GetAssociations(int id) { return await <API key>.GetAssociations<<API key>, DenormalizedProject>(this, id); } [HttpPut(ApiConstants.Routes.Associations)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ItemsResource<<API key>>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.BadRequest)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> UpdateAssociations(int id, [FromBody]<API key> updateModel) { return await <API key>.UpdateAssociations<Project>(this, id, updateModel); } [HttpGet(ApiConstants.Routes.Images)] [ProducesResponse(typeof(ItemsResource<ImageResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] public async Task<IActionResult> GetImages(int id) { return await _imagesEndpoint.GetImages<<API key>, DenormalizedProject>(this, id); } [HttpPut(ApiConstants.Routes.Images)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ItemsResource<ImageResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.BadRequest)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> UpdateImages(int id, [FromBody]<API key> updateModel) { return await _imagesEndpoint.UpdateImages<Project>(this, id, updateModel); } [HttpGet(ApiConstants.Routes.Jobs)] [ProducesResponse(typeof(ItemsResource<JobResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] public async Task<IActionResult> GetJobs(int id) { return await _jobsEndpoint.GetJobs<Project>(this, id); } [HttpPut(ApiConstants.Routes.Jobs)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ItemsResource<JobResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.BadRequest)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> UpdateJobs(int id, [FromBody]<API key> updateModel) { return await _jobsEndpoint.UpdateJobs<Project>(this, id, updateModel); } [HttpGet(ApiConstants.Routes.Library)] [ProducesResponse(typeof(ItemsResource<LibraryResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] public async Task<IActionResult> GetLibrary(int id) { return await _libraryEndpoint.GetLibrary<<API key>, DenormalizedProject>(this, id); } [HttpPut(ApiConstants.Routes.Library)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ItemsResource<LibraryResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.BadRequest)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> UpdateLibrary(int id, [FromBody]<API key> updateModel) { return await _libraryEndpoint.UpdateLibrary<Project>(this, id, updateModel); } [HttpGet(ApiConstants.Routes.Publications)] [ProducesResponse(typeof(ItemsResource<LibraryResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] public async Task<IActionResult> GetPublications(int id) { return await <API key>.GetPublications<<API key>, DenormalizedProject>(this, id); } [HttpPut(ApiConstants.Routes.Publications)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ItemsResource<LibraryResourceItem>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.BadRequest)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> UpdatePublications(int id, [FromBody]<API key> updateModel) { return await <API key>.UpdatePublications<Project>(this, id, updateModel); } [HttpGet(ApiConstants.Routes.Permissions)] [ProducesResponse(typeof(ItemsResource<<API key>>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.Forbidden)] public async Task<IActionResult> GetPermissions(int id) { return await <API key>.GetPermissions<Project>(this, id); } [HttpPatch(ApiConstants.Routes.Permissions)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ItemsResource<<API key>>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.Forbidden)] [ProducesResponse(HttpStatusCode.Unauthorized)] public async Task<IActionResult> UpdatePermissions(int id, [FromBody]<API key> updateModel) { return await <API key>.UpdatePermissions<Project>(this, id, updateModel); } [HttpPut(ApiConstants.Routes.Permissions)] [Authorize(Policies.Authenticated)] [<API key>] [<API key>] [ProducesResponse(typeof(ItemsResource<<API key>>), HttpStatusCode.OK)] [ProducesResponse(HttpStatusCode.NotFound)] [ProducesResponse(HttpStatusCode.Forbidden)] [ProducesResponse(HttpStatusCode.Unauthorized)] public async Task<IActionResult> ReplacePermissions(int id, [FromBody]<API key> updateModel) { return await <API key>.ReplacePermissions<Project>(this, id, updateModel); } private async Task UpdateModel(<API key> updateModel, Project project) { _mapper.Map(updateModel, project); await _geocodingService.Geocode(project.ContactInfo); await _tagService.<API key>(updateModel.Tags); } protected HALResponse <API key>(DenormalizedProject model) { var id = _session.GetIdValuePart(model.Id); var resource = _mapper.Map<ProjectResource>(model.Entity); var representation = resource .<API key>(this, _ => GetProject(id)) .AddLibrary(this, model, id) .AddPublications(this, model, id) .AddImages(this, model, id) .AddJobs(this, model.Entity, id) .AddAssociations(this, model, id) .AddParentProject(_resourceFactory, model.ParentProject) .AddPartnerProjects(_resourceFactory, model.PartnerProjects); return representation; } } }
<?php namespace pocketmine\network\protocol; #include <rules/DataPacket.h> class RespawnPacket extends DataPacket{ const NETWORK_ID = Info::RESPAWN_PACKET; public $x; public $y; public $z; public function decode(){ $this->x = $this->getLFloat(); $this->y = $this->getLFloat(); $this->z = $this->getLFloat(); } public function encode(){ $this->reset(); $this->putLFloat($this->x); $this->putLFloat($this->y); $this->putLFloat($this->z); } }
<!DOCTYPE html> <html class="um landscape min-width-240px min-width-320px min-width-480px min-width-768px min-width-1024px"> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" href="../../../css/fonts/font-awesome.min.css"> <link rel="stylesheet" href="../../../css/ui-box.css"> <link rel="stylesheet" href="../../../css/ui-base.css"> <link rel="stylesheet" href="../../../css/ui-color.css"> <link rel="stylesheet" href="../../../css/appcan.icon.css"> <link rel="stylesheet" href="../../../css/appcan.control.css"> <link rel="stylesheet" href="../../../css/my.css"> <style type="text/css"> .fa-book{font-size: 1.3em} </style> </head> <body class="um-vp " ontouchstart> <div id="page_0" class="up ub ub-ver bc-bg" tabindex="0"> <!--header <div id="header" class="uh bc-text-head ub bc-head"> <div class="nav-btn" id="nav-left"> <div class="fa fa-angle-left fa-2x"></div><div class="text"></div> </div> <h1 class="ut ub-f1 ulev-3 ut-s tx-c" tabindex="0"><API key></h1> <div class="nav-btn nav-bt" id="nav-right"> <!-- <div class="fa fa-book"></div> --> </div> </div> <!--header--><!--content--> <div id="content" class="ub-f1 tx-l"> </div> <!--content </div> <script src="../../../js/appcan.js"></script> <script src="../../../js/appcan.control.js"></script> </body> <script> appcan.ready(function() { appcan.locStorage.val("single",0) var titHeight = $('#header').offset().height; appcan.frame.open("content", "api_content.html", 0, titHeight); window.onorientationchange = window.onresize = function() { appcan.frame.resize("content", 0, titHeight); } appcan.window.subscribe("close", function() { appcan.window.close(-1); }); }); appcan.button("#nav-left", "btn-act", function() { appcan.window.close(-1); }) </script> </html>
// This file is part of the go-trustmachine library. // The go-trustmachine library is free software: you can redistribute it and/or modify // (at your option) any later version. // The go-trustmachine library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // Package compiler wraps the Solidity compiler executable (solc). package compiler import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "os/exec" "regexp" "strconv" "strings" ) var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`) type Contract struct { Code string `json:"code"` Info ContractInfo `json:"info"` } type ContractInfo struct { Source string `json:"source"` Language string `json:"language"` LanguageVersion string `json:"languageVersion"` CompilerVersion string `json:"compilerVersion"` CompilerOptions string `json:"compilerOptions"` AbiDefinition interface{} `json:"abiDefinition"` UserDoc interface{} `json:"userDoc"` DeveloperDoc interface{} `json:"developerDoc"` Metadata string `json:"metadata"` } // Solidity contains information about the solidity compiler. type Solidity struct { Path, Version, FullVersion string Major, Minor, Patch int } // --combined-output format type solcOutput struct { Contracts map[string]struct { Bin, Abi, Devdoc, Userdoc, Metadata string } Version string } func (s *Solidity) makeArgs() []string { p := []string{ "--combined-json", "bin,abi,userdoc,devdoc", "--add-std", // include standard lib contracts "--optimize", // code optimizer switched on } if s.Major > 0 || s.Minor > 4 || s.Patch > 6 { p[1] += ",metadata" } return p } // SolidityVersion runs solc and parses its version output. func SolidityVersion(solc string) (*Solidity, error) { if solc == "" { solc = "solc" } var out bytes.Buffer cmd := exec.Command(solc, "--version") cmd.Stdout = &out err := cmd.Run() if err != nil { return nil, err } matches := versionRegexp.FindStringSubmatch(out.String()) if len(matches) != 4 { return nil, fmt.Errorf("can't parse solc version %q", out.String()) } s := &Solidity{Path: cmd.Path, FullVersion: out.String(), Version: matches[0]} if s.Major, err = strconv.Atoi(matches[1]); err != nil { return nil, err } if s.Minor, err = strconv.Atoi(matches[2]); err != nil { return nil, err } if s.Patch, err = strconv.Atoi(matches[3]); err != nil { return nil, err } return s, nil } // <API key> builds and returns all the contracts contained within a source string. func <API key>(solc, source string) (map[string]*Contract, error) { if len(source) == 0 { return nil, errors.New("solc: empty source string") } s, err := SolidityVersion(solc) if err != nil { return nil, err } args := append(s.makeArgs(), " cmd := exec.Command(s.Path, append(args, "-")...) cmd.Stdin = strings.NewReader(source) return s.run(cmd, source) } // CompileSolidity compiles all given Solidity source files. func CompileSolidity(solc string, sourcefiles ...string) (map[string]*Contract, error) { if len(sourcefiles) == 0 { return nil, errors.New("solc: no source files") } source, err := slurpFiles(sourcefiles) if err != nil { return nil, err } s, err := SolidityVersion(solc) if err != nil { return nil, err } args := append(s.makeArgs(), " cmd := exec.Command(s.Path, append(args, sourcefiles...)...) return s.run(cmd, source) } func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) { var stderr, stdout bytes.Buffer cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Run(); err != nil { return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes()) } var output solcOutput if err := json.Unmarshal(stdout.Bytes(), &output); err != nil { return nil, err } // Compilation succeeded, assemble and return the contracts. contracts := make(map[string]*Contract) for name, info := range output.Contracts { // Parse the individual compilation results. var abi interface{} if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil { return nil, fmt.Errorf("solc: error reading abi definition (%v)", err) } var userdoc interface{} if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil { return nil, fmt.Errorf("solc: error reading user doc: %v", err) } var devdoc interface{} if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil { return nil, fmt.Errorf("solc: error reading dev doc: %v", err) } contracts[name] = &Contract{ Code: "0x" + info.Bin, Info: ContractInfo{ Source: source, Language: "Solidity", LanguageVersion: s.Version, CompilerVersion: s.Version, CompilerOptions: strings.Join(s.makeArgs(), " "), AbiDefinition: abi, UserDoc: userdoc, DeveloperDoc: devdoc, Metadata: info.Metadata, }, } } return contracts, nil } func slurpFiles(files []string) (string, error) { var concat bytes.Buffer for _, file := range files { content, err := ioutil.ReadFile(file) if err != nil { return "", err } concat.Write(content) } return concat.String(), nil }
#ifndef __HTTPRESPONSE_H__ #define __HTTPRESPONSE_H__ #define MAXGET 50 struct _content; struct _httpresponse { enum {E_ResponseStatus, E_ResponseHeader, E_ResponseContent, E_ResponseEnd } m_state; struct _content *m_Content; char *m_header; char *m_ptr; int m_status; }; typedef struct _httpresponse HttpResponse; HttpResponse * httpresponse_new(struct _content *content); void <API key>(HttpResponse *p_http); int httpresponse_format(HttpResponse *p_http, char *buff, int len); #endif
<?php class <API key> extends <API key> { private $_object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @access protected */ protected function setUp() { $this->_object = new <API key>( TestHelper::getContext() ); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @access protected */ protected function tearDown() { $this->_object = null; } public function testSearchItems() { $params = (object) array( 'site' => 'unittest', 'condition' => (object) array( '&&' => array( 0 => (object) array( '==' => (object) array( 'product.list.type.code' => 'unittype2' ) ) ) ), 'sort' => 'product.list.position', 'dir' => 'ASC', 'start' => 0, 'limit' => 1, ); $result = $this->_object->searchItems( $params ); $this->assertEquals( 1, count( $result['items'] ) ); $this->assertEquals( 1, $result['total'] ); $this->assertEquals( 'media', $result['items'][0]->{'product.list.domain'} ); $this->assertEquals( 1, count( $result['graph']['Media']['items'] ) ); $this->assertEquals( 'cn_colombie_266x221', $result['graph']['Media']['items'][0]->{'media.label'} ); } public function testSaveDeleteItem() { $params = (object) array( 'site' => 'unittest', 'limit' => 1 ); $productManager = new <API key>( TestHelper::getContext() ); $result = $productManager->searchItems( $params ); $params = (object) array( 'site' => 'unittest', 'condition' => (object) array( '&&' => array( 0 => (object) array( '==' => (object) array( 'product.list.type.domain' => 'text' ) ) ) ), 'start' => 0, 'limit' => 1, ); $<API key> = <API key>::createController( TestHelper::getContext() ); $resultType = $<API key>->searchItems( $params ); $saveParams = (object) array( 'site' => 'unittest', 'items' => (object) array( 'product.list.parentid' => $result['items'][0]->{'product.id'}, 'product.list.typeid' => $resultType['items'][0]->{'product.list.type.id'}, 'product.list.domain' => 'text', 'product.list.refid' => -1, 'product.list.datestart' => '2000-01-01 00:00:00', 'product.list.dateend' => '2001-01-01 00:00:00', 'product.list.config' => array('test' => 'unit'), 'product.list.position' => 1, 'product.list.status' => 1, ), ); $searchParams = (object) array( 'site' => 'unittest', 'condition' => (object) array( '&&' => array( 0 => (object) array( '==' => (object) array( 'product.list.refid' => -1 ) ) ) ) ); $saved = $this->_object->saveItems( $saveParams ); $searched = $this->_object->searchItems( $searchParams ); $deleteParams = (object) array( 'site' => 'unittest', 'items' => $saved['items']->{'product.list.id'} ); $this->_object->deleteItems( $deleteParams ); $result = $this->_object->searchItems( $searchParams ); $this->assertInternalType( 'object', $saved['items'] ); $this->assertNotNull( $saved['items']->{'product.list.id'} ); $this->assertEquals( $saved['items']->{'product.list.id'}, $searched['items'][0]->{'product.list.id'}); $this->assertEquals( $saved['items']->{'product.list.parentid'}, $searched['items'][0]->{'product.list.parentid'}); $this->assertEquals( $saved['items']->{'product.list.typeid'}, $searched['items'][0]->{'product.list.typeid'}); $this->assertEquals( $saved['items']->{'product.list.domain'}, $searched['items'][0]->{'product.list.domain'}); $this->assertEquals( $saved['items']->{'product.list.refid'}, $searched['items'][0]->{'product.list.refid'}); $this->assertEquals( $saved['items']->{'product.list.datestart'}, $searched['items'][0]->{'product.list.datestart'}); $this->assertEquals( $saved['items']->{'product.list.dateend'}, $searched['items'][0]->{'product.list.dateend'}); $this->assertEquals( $saved['items']->{'product.list.config'}, $searched['items'][0]->{'product.list.config'}); $this->assertEquals( $saved['items']->{'product.list.position'}, $searched['items'][0]->{'product.list.position'}); $this->assertEquals( $saved['items']->{'product.list.status'}, $searched['items'][0]->{'product.list.status'}); $this->assertEquals( 1, count( $searched['items'] ) ); $this->assertEquals( 0, count( $result['items'] ) ); } }
<?php /** * TOP API: taobao.jipiao.policiesstatus.update request * * @author auto create * @since 1.0, 2014-02-20 17:02:53 */ class <API key> { private $airline; private $arrAirport; private $depAirport; /** * id,1000,,out_product_id **/ private $outProductIds; /** * id,1000policy_id **/ private $policyIds; private $publishDate; /** * , taobao.jipiao.policy.processsourceTOP,sourcePC,excelsourceUPLOAD,taobao.jipiao.policies.fulladd,taobao.jipiao.policies.addsource **/ private $source; /** * 0policy_ids1out_product_ids2: **/ private $type; private $apiParas = array(); public function setAirline($airline) { $this->airline = $airline; $this->apiParas["airline"] = $airline; } public function getAirline() { return $this->airline; } public function setArrAirport($arrAirport) { $this->arrAirport = $arrAirport; $this->apiParas["arr_airport"] = $arrAirport; } public function getArrAirport() { return $this->arrAirport; } public function setDepAirport($depAirport) { $this->depAirport = $depAirport; $this->apiParas["dep_airport"] = $depAirport; } public function getDepAirport() { return $this->depAirport; } public function setOutProductIds($outProductIds) { $this->outProductIds = $outProductIds; $this->apiParas["out_product_ids"] = $outProductIds; } public function getOutProductIds() { return $this->outProductIds; } public function setPolicyIds($policyIds) { $this->policyIds = $policyIds; $this->apiParas["policy_ids"] = $policyIds; } public function getPolicyIds() { return $this->policyIds; } public function setPublishDate($publishDate) { $this->publishDate = $publishDate; $this->apiParas["publish_date"] = $publishDate; } public function getPublishDate() { return $this->publishDate; } public function setSource($source) { $this->source = $source; $this->apiParas["source"] = $source; } public function getSource() { return $this->source; } public function setType($type) { $this->type = $type; $this->apiParas["type"] = $type; } public function getType() { return $this->type; } public function getApiMethodName() { return "taobao.jipiao.policiesstatus.update"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkMaxLength($this->airline,5,"airline"); RequestCheckUtil::checkMaxLength($this->arrAirport,3,"arrAirport"); RequestCheckUtil::checkMaxLength($this->depAirport,3,"depAirport"); RequestCheckUtil::checkMaxLength($this->source,20,"source"); RequestCheckUtil::checkNotNull($this->type,"type"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
import React, { Component, PropTypes } from 'react' import PageLayout from '../PageLayout' import Link from '../Link/' import { USER_ROLE } from '../../constants/Generic' import { redirect } from '<API key>' import '!style!css!less!./style.less' class Users extends React.Component { constructor(props) { super(props); this.state = { user: null } } componentDidMount() { const { onLoadUsers } = this.props; onLoadUsers(); } onDelete(userId) { return (evt) => { evt.preventDefault(); if (userId) { const { users } = this.props; this.setState({ user: users.find((userItem) => userId === userItem.id) }); $('#confirm').modal('show'); } } } deleteUser() { return (evt) => { evt.preventDefault(); $('#confirm').modal('hide'); const { onDelete } = this.props; onDelete && onDelete(this.state.user.id); this.setState({ user: null }); } } render() { const { cmsName, router, onClickLogout, auth_user, users, mainPages, } = this.props; let selectedUser = this.state.user; selectedUser = selectedUser ? selectedUser : { id: 0, email: '' }; return ( <PageLayout cmsName={cmsName} router={router} onClickLogout={onClickLogout} auth_user={auth_user} mainPages={mainPages} > <div className="modal fade bs-example-modal-sm" tabIndex="-1" role="dialog" aria-labelledby="mySmallModalLabel" id="confirm"> <div className="modal-dialog modal-sm" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 className="modal-title" id="myModalLabel">{`Confirm to delete`}</h4> </div> <div className="modal-body"> {`You sure that you want to delete user with email ${selectedUser.email} ?`} </div> <div className="modal-footer"> <button onClick={this.deleteUser()} type="button" className="btn btn-default" data-dismiss="modal">Delete</button> <button type="button" className="btn btn-default" data-dismiss="modal">Cancel</button> </div> </div> </div> </div> <div className="container list-wrapper"> <div className="row"> <div className="col-md-10"> <div className="panel panel-primary"> <div className="panel-heading"> <span className="glyphicon glyphicon-list"></span> <span>Users</span> <div className="pull-right action-buttons"> <div className="btn-group pull-right"> <Link url={'users/0'} className="btn btn-default btn-xs"> <span className="glyphicon glyphicon-plus"></span> <span>Add New User</span> </Link> </div> </div> </div> <div className="panel-body"> <ul className="list-group"> {users .filter((user) => { const authPriority = USER_ROLE.indexOf(auth_user.role); const userPriority = USER_ROLE.indexOf(user.role); return authPriority - userPriority <= 0; }) .map((user) => { return ( <li className="list-group-item" key={user.id}> <span className="list-wrapper__name">{user.email}</span> <small className="small list-wrapper__role">{user.role}</small> <div className="pull-right action-buttons"> <Link url={`/users/${user.id}`}><span className="glyphicon glyphicon-pencil"></span></Link> <a href="#" className="trash" onClick={this.onDelete(user.id)}><span className="glyphicon glyphicon-trash"></span></a> </div> </li> ); })} </ul> </div> <div className="panel-footer"> <div className="row"> <div className="col-md-6"> <h6>Total Count <span className="label label-info">{users.length}</span></h6> </div> </div> </div> </div> </div> </div> </div> </PageLayout> ); } } // <button type="button" className="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown"> // <span className="glyphicon glyphicon-cog"></span> // </button> // <ul className="dropdown-menu slidedown"> export default Users;
#!/bin/python # -*- coding: utf-8 -*- # Fenrir TTY screen reader # By Chrys, Storm Dragon, and contributers. import os, struct, sys, pty, tty, termios, shlex, signal, pyte, time, fcntl ,getpass from select import select from fenrirscreenreader.core import debug from fenrirscreenreader.core.eventData import fenrirEventType from fenrirscreenreader.core.screenDriver import screenDriver from fenrirscreenreader.utils import screen_utils class fenrirScreen(pyte.Screen): def set_margins(self, *args, **kwargs): kwargs.pop("private", None) super(fenrirScreen, self).set_margins(*args, **kwargs) class Terminal: def __init__(self, columns, lines, p_in): self.text = '' self.attributes = None self.screen = fenrirScreen(columns, lines) self.screen.write_process_input = \ lambda data: p_in.write(data.encode()) self.stream = pyte.ByteStream() self.stream.attach(self.screen) def feed(self, data): self.stream.feed(data) def updateAttributes(self, initialize = False): buffer = self.screen.buffer lines = None if not initialize: lines = self.screen.dirty else: lines = range(self.screen.lines) self.attributes = [[list(attribute[1:]) + [False, 'default', 'default'] for attribute in line.values()] for line in buffer.values()] for y in lines: try: t = self.attributes[y] except: self.attributes.append([]) self.attributes[y] = [list(attribute[1:]) + [False, 'default', 'default'] for attribute in (buffer[y].values())] if len(self.attributes[y]) < self.screen.columns: diff = self.screen.columns - len(self.attributes[y]) self.attributes[y] += [['default', 'default', False, False, False, False, False, False, 'default', 'default']] * diff def resize(self, lines, columns): self.screen.resize(lines, columns) self.setCursor() self.updateAttributes(True) def setCursor(self, x = -1, y = -1): xPos = x yPos = y if xPos == -1: xPos = self.screen.cursor.x if yPos == -1: yPos = self.screen.cursor.y self.screen.cursor.x = min(self.screen.cursor.x, self.screen.columns - 1) self.screen.cursor.y = min(self.screen.cursor.y, self.screen.lines - 1) def GetScreenContent(self): cursor = self.screen.cursor self.text = '\n'.join(self.screen.display) self.updateAttributes(self.attributes == None) self.screen.dirty.clear() return {"cursor": (cursor.x, cursor.y), 'lines': self.screen.lines, 'columns': self.screen.columns, "text": self.text, 'attributes': self.attributes.copy(), 'screen': 'pty', 'screenUpdateTime': time.time(), }.copy() class driver(screenDriver): def __init__(self): screenDriver.__init__(self) self.signalPipe = os.pipe() self.p_out = None self.terminal = None self.p_pid = -1 signal.signal(signal.SIGWINCH, self.handleSigwinch) def initialize(self, environment): self.env = environment self.command = self.env['runtime']['settingsManager'].getSetting('general','shell') self.shortcutType = self.env['runtime']['inputManager'].getShortcutType() self.env['runtime']['processManager'].<API key>(self.terminalEmulation) def getCurrScreen(self): self.env['screen']['oldTTY'] = 'pty' self.env['screen']['newTTY'] = 'pty' def injectTextToScreen(self, msgBytes, screen = None): if not screen: screen = self.p_out.fileno() if isinstance(msgBytes, str): msgBytes = bytes(msgBytes, 'UTF-8') os.write(screen, msgBytes) def <API key>(self): self.env['screen']['autoIgnoreScreens'] = [] self.env['general']['prevUser'] = getpass.getuser() self.env['general']['currUser'] = getpass.getuser() def readAll(self, fd, timeout = 0.3, interruptFd = None, len = 65536): msgBytes = b'' fdList = [] fdList += [fd] if interruptFd: fdList += [interruptFd] starttime = time.time() while True: r = screen_utils.hasMoreWhat(fdList, 0.0001) # nothing more to read if not fd in r: break data = os.read(fd, len) if data == b'': raise EOFError msgBytes += data # exit on interrupt available if interruptFd in r: break # respect timeout but wait a little bit of time to see if something more is here if (time.time() - starttime) >= timeout: break return msgBytes def openTerminal(self, columns, lines, command): p_pid, master_fd = pty.fork() if p_pid == 0: # Child. argv = shlex.split(command) env = os.environ.copy() #values are VT100,xterm-256color,linux try: if env["TERM"] == '': env["TERM"] = 'linux' except: env["TERM"] = 'linux' os.execvpe(argv[0], argv, env) # File-like object for I/O with the child process aka command. p_out = os.fdopen(master_fd, "w+b", 0) return Terminal(columns, lines, p_out), p_pid, p_out def resizeTerminal(self,fd): s = struct.pack('HHHH', 0, 0, 0, 0) s = fcntl.ioctl(0, termios.TIOCGWINSZ, s) fcntl.ioctl(fd, termios.TIOCSWINSZ, s) lines, columns, _, _ = struct.unpack('hhhh', s) return lines, columns def getTerminalSize(self, fd): s = struct.pack('HHHH', 0, 0, 0, 0) lines, columns, _, _ = struct.unpack('HHHH', fcntl.ioctl(fd, termios.TIOCGWINSZ, s)) return lines, columns def handleSigwinch(self, *args): os.write(self.signalPipe[1], b'w') def terminalEmulation(self,active , eventQueue): try: old_attr = termios.tcgetattr(sys.stdin) tty.setraw(0) lines, columns = self.getTerminalSize(0) if self.command == '': self.command = screen_utils.getShell() self.terminal, self.p_pid, self.p_out = self.openTerminal(columns, lines, self.command) lines, columns = self.resizeTerminal(self.p_out) self.terminal.resize(lines, columns) fdList = [sys.stdin, self.p_out, self.signalPipe[0]] while active.value: r, _, _ = select(fdList, [], [], 1) # none if r == []: continue # signals if self.signalPipe[0] in r: os.read(self.signalPipe[0], 1) lines, columns = self.resizeTerminal(self.p_out) self.terminal.resize(lines, columns) # input if sys.stdin in r: try: msgBytes = self.readAll(sys.stdin.fileno(), len=4096) except (EOFError, OSError): eventQueue.put({"Type":fenrirEventType.StopMainLoop,"Data":None}) break if self.shortcutType == 'KEY': try: self.injectTextToScreen(msgBytes) except: eventQueue.put({"Type":fenrirEventType.StopMainLoop,"Data":None}) break else: eventQueue.put({"Type":fenrirEventType.ByteInput, "Data":msgBytes }) # output if self.p_out in r: try: msgBytes = self.readAll(self.p_out.fileno(), interruptFd=sys.stdin.fileno()) except (EOFError, OSError): eventQueue.put({"Type":fenrirEventType.StopMainLoop,"Data":None}) break # feed and send event bevore write, the pyte already has the right state # so fenrir already can progress bevore os.write what should give some better reaction time self.terminal.feed(msgBytes) eventQueue.put({"Type":fenrirEventType.ScreenUpdate, "Data":screen_utils.<API key>(self.terminal.GetScreenContent()) }) self.injectTextToScreen(msgBytes, screen=sys.stdout.fileno()) except Exception as e: # Process died? print(e) eventQueue.put({"Type":fenrirEventType.StopMainLoop,"Data":None}) finally: os.kill(self.p_pid, signal.SIGTERM) self.p_out.close() termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attr) eventQueue.put({"Type":fenrirEventType.StopMainLoop,"Data":None}) sys.exit(0) def getCurrApplication(self): pass
<?php ?> <!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js"></script> <script> function initialize() { var mapCanvas = document.getElementById('map-canvas'); var mapOptions = { center: new google.maps.LatLng(35.1107, -106.6100), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(mapCanvas, mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); </script> <style> body { background-image: linear-gradient(90deg, red, yellow ); } .homeLink { color: whitesmoke; text-decoration: none; } .homeLink:hover{ color: cadetblue; } #headLink{ margin-left: 2.5em; margin-top: 3em; } #cirAst { position: absolute; top: 99%; right: 2%; color: #ADD8E6; text-align: center; font-size: 20px; border-radius: 100% border: 2px solid white; } #map-canvas { position: absolute; top: 18%; left: 28%; width: 500px; height: 400px; background-color: #CCC; } </style> </head> <body> <header> <p id="headLink"><a class="homeLink" href="index.php">Home</a></p> </header> <div id="map-canvas"></div> <a class="homeLink" href="index.php"> <p id="cirAst">&circledast;</p> </a> </body> </html>
package com.nextgis.maplibui.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.nextgis.maplib.datasource.GeoGeometry; import com.nextgis.maplib.map.VectorLayer; import com.nextgis.maplib.util.Constants; import com.nextgis.maplib.util.FileUtil; import com.nextgis.maplib.util.GeoConstants; import com.nextgis.maplibui.R; import com.nextgis.maplibui.activity.<API key>; import com.nextgis.maplibui.activity.<API key>; import com.nextgis.maplibui.activity.NGActivity; import com.nextgis.maplibui.api.IVectorLayerUI; import com.nextgis.maplibui.service.LayerFillService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.ArrayList; import static com.nextgis.maplibui.util.ConstantsUI.KEY_FEATURE_ID; import static com.nextgis.maplibui.util.ConstantsUI.KEY_FORM_PATH; import static com.nextgis.maplibui.util.ConstantsUI.KEY_GEOMETRY; import static com.nextgis.maplibui.util.ConstantsUI.<API key>; import static com.nextgis.maplibui.util.ConstantsUI.KEY_LAYER_ID; import static com.nextgis.maplibui.util.ConstantsUI.KEY_META_PATH; /** * Raster and vector layer utilities */ public final class LayerUtil { public static ArrayList<String> fillLookupTableIds(File path) throws IOException, JSONException { String formText = FileUtil.readFromFile(path); JSONArray formJson = new JSONArray(formText); ArrayList<String> lookupTableIds = new ArrayList<>(); for (int i = 0; i < formJson.length(); i++) { JSONObject element = formJson.getJSONObject(i); if (ConstantsUI.JSON_COMBOBOX_VALUE.equals(element.optString(Constants.JSON_TYPE_KEY))) { element = element.getJSONObject(ConstantsUI.JSON_ATTRIBUTES_KEY); if (element.has(ConstantsUI.JSON_NGW_ID_KEY)) if (element.getLong(ConstantsUI.JSON_NGW_ID_KEY) != -1) lookupTableIds.add(element.getLong(ConstantsUI.JSON_NGW_ID_KEY) + ""); } } return lookupTableIds; } public static void showEditForm(VectorLayer layer, Context context, long featureId, GeoGeometry geometry) { if (!layer.isFieldsInitialized()) { Toast.makeText(context, context.getString(R.string.<API key>), Toast.LENGTH_SHORT).show(); return; } boolean isGeometryChanged = geometry != null; //get geometry if (geometry == null && featureId != Constants.NOT_FOUND) { geometry = layer.getGeometryForId(featureId); } Intent intent; //check custom form File form = new File(layer.getPath(), ConstantsUI.FILE_FORM); if (form.exists()) { //show custom form intent = new Intent(context, <API key>.class); intent.putExtra(KEY_FORM_PATH, form); File meta = new File(layer.getPath(), LayerFillService.NGFP_META); if (meta.exists()) intent.putExtra(KEY_META_PATH, meta); } else { //if not exist show standard form intent = new Intent(context, <API key>.class); } intent.putExtra(KEY_LAYER_ID, layer.getId()); intent.putExtra(KEY_FEATURE_ID, featureId); intent.putExtra(<API key>, isGeometryChanged); if (null != geometry) intent.putExtra(KEY_GEOMETRY, geometry); ((Activity) context).<API key>(intent, IVectorLayerUI.MODIFY_REQUEST); } public static void shareTrackAsGPX(NGActivity activity, String creator, String[] tracksId) { ExportGPXTask exportTask = new ExportGPXTask(activity, creator, tracksId); exportTask.execute(); } public static void shareLayerAsGeoJSON(Activity activity, VectorLayer layer, boolean proceedAttaches) { ExportGeoJSONTask exportTask = new ExportGeoJSONTask(activity, layer, proceedAttaches, false); exportTask.execute(); } public static String getGeometryName(Context context, int geometryType) { switch (geometryType) { case GeoConstants.GTPoint: return context.getString(R.string.point); case GeoConstants.GTMultiPoint: return context.getString(R.string.multi_point); case GeoConstants.GTLineString: return context.getString(R.string.linestring); case GeoConstants.GTMultiLineString: return context.getString(R.string.multi_linestring); case GeoConstants.GTPolygon: return context.getString(R.string.polygon); case GeoConstants.GTMultiPolygon: return context.getString(R.string.multi_polygon); default: return context.getString(R.string.n_a); } } }
import * as React from 'react'; import { Component } from '../../../types/types'; import CodeSnippet from '../../common/CodeSnippet'; import <API key> from './<API key>'; export interface <API key> { component: Component; } const sonarProjectSnippet = (key: string) => `sonar.projectKey=${key}`; export default function DefaultProjectKey(props: <API key>) { const { component } = props; return ( <li className="abs-width-600"> <<API key> filename="sonar-project.properties" translationKey="onboarding.tutorial.other.project_key" /> <CodeSnippet snippet={sonarProjectSnippet(component.key)} /> </li> ); }
#region Using #endregion namespace Guidgets.XamlGrid.Core { <summary> The interface definition for a PureMVC Model </summary> <remarks> <para>In PureMVC, <c>IModel</c> implementors provide access to <c>IModel</c> objects by named lookup</para> <para>An <c>IModel</c> assumes these responsibilities:</para> <list type="bullet"> <item>Maintain a cache of <c>IModel</c> instances</item> <item>Provide methods for registering, retrieving, and removing <c>IModel</c> instances</item> </list> </remarks> public interface IMainModel { <summary> Register an <c>IModel</c> instance with the <c>Model</c> </summary> <param name="model">A reference to the Model object to be held by the <c>Model</c></param> void RegisterModel(IModel model); <summary> Retrieve an <c>IModel</c> instance from the Model </summary> <param name="ModelName">The name of the Model to retrieve</param> <returns>The <c>IModel</c> instance previously registered with the given <c>ModelName</c></returns> IModel RetrieveModel(string ModelName); <summary> Remove an <c>IModel</c> instance from the Model </summary> <param name="ModelName">The name of the <c>IModel</c> instance to be removed</param> IModel RemoveModel(string ModelName); <summary> Check if a Model is registered </summary> <param name="ModelName">The name of the Model to check for</param> <returns>whether a Model is currently registered with the given <c>ModelName</c>.</returns> bool HasModel(string ModelName); } }
namespace <API key> { partial class Form1 { <summary> Required designer variable. </summary> private System.ComponentModel.IContainer components = null; <summary> Clean up any resources being used. </summary> <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent() { this.cbWii = new System.Windows.Forms.ComboBox(); this.panel1 = new System.Windows.Forms.Panel(); this.cbX = new System.Windows.Forms.ComboBox(); this.cbY = new System.Windows.Forms.ComboBox(); this.ezB_Connect1 = new EZ_B.UCEZB_Connect(); this.btnRefreshREmotes = new System.Windows.Forms.Button(); this.SuspendLayout(); // cbWii this.cbWii.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbWii.FormattingEnabled = true; this.cbWii.Location = new System.Drawing.Point(12, 37); this.cbWii.Name = "cbWii"; this.cbWii.Size = new System.Drawing.Size(257, 21); this.cbWii.TabIndex = 1; this.cbWii.<API key> += new System.EventHandler(this.<API key>); // panel1 this.panel1.Location = new System.Drawing.Point(77, 121); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(295, 245); this.panel1.TabIndex = 2; // cbX this.cbX.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbX.FormattingEnabled = true; this.cbX.Location = new System.Drawing.Point(12, 64); this.cbX.Name = "cbX"; this.cbX.Size = new System.Drawing.Size(82, 21); this.cbX.TabIndex = 4; // cbY this.cbY.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbY.FormattingEnabled = true; this.cbY.Location = new System.Drawing.Point(100, 64); this.cbY.Name = "cbY"; this.cbY.Size = new System.Drawing.Size(82, 21); this.cbY.TabIndex = 5; // ezB_Connect1 this.ezB_Connect1.Location = new System.Drawing.Point(0, 0); this.ezB_Connect1.Name = "ezB_Connect1"; this.ezB_Connect1.Port = ""; this.ezB_Connect1.ShowDebugButton = true; this.ezB_Connect1.Size = new System.Drawing.Size(283, 31); this.ezB_Connect1.TabIndex = 0; // btnRefreshREmotes this.btnRefreshREmotes.Location = new System.Drawing.Point(275, 37); this.btnRefreshREmotes.Name = "btnRefreshREmotes"; this.btnRefreshREmotes.Size = new System.Drawing.Size(107, 23); this.btnRefreshREmotes.TabIndex = 6; this.btnRefreshREmotes.Text = "Refresh Remotes"; this.btnRefreshREmotes.<API key> = true; this.btnRefreshREmotes.Click += new System.EventHandler(this.<API key>); // Form1 this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(524, 405); this.Controls.Add(this.btnRefreshREmotes); this.Controls.Add(this.cbY); this.Controls.Add(this.cbX); this.Controls.Add(this.panel1); this.Controls.Add(this.cbWii); this.Controls.Add(this.ezB_Connect1); this.Name = "Form1"; this.Text = "Form1"; this.FormClosed += new System.Windows.Forms.<API key>(this.Form1_FormClosed); this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion private EZ_B.UCEZB_Connect ezB_Connect1; private System.Windows.Forms.ComboBox cbWii; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ComboBox cbX; private System.Windows.Forms.ComboBox cbY; private System.Windows.Forms.Button btnRefreshREmotes; } }
''' @package gradientutils gradientutils was writen by Giuseppe Marco Randazzo <gmrandazzo@gmail.com> Geneve May 2016 gradientutils contains function which are used to estimate: - get_lss_peak_width: get the peak width according to the lss theory - <API key>: critical couples with their resolutions for linear gradient - <API key>: critical couble with their selectivity for linear gradient - <API key>: get the peak width for logarithmic solvent strength according to the lss theory - <API key>: critical couples with their resolutions for logarithmic gradient - <API key>: critical couble with their selectivity for linear gradient ''' from ssengine import SSGenerator from math import sqrt, isnan, log, fabs def get_lss_peak_width(c_length, c_particle, logkw, s, init_b, final_b, tg, flow, v_m, v_d, s_extra): """ Peak width estimation using the Snynder and Dolan modelling and considering also the peak compression effect G """ N = (c_length*10000.)/(3.4*c_particle) t0 = v_m*flow b = (t0*(final_b-init_b)*s)/tg k0 = logkw-(s*init_b) ke = 1/(2.3*b) p = (2.3*b*k0)/(k0+1) G = ((1+p+(p**2/3))/(1+p)**2)**(1/2.) Nobs = 0. if s_extra != None: s_col = (v_m*(1+ke))/N Nobs = N*(1/(1+(s_extra/s_col))) else: Nobs = N return 4*Nobs**(-1/2.)*G*t0*(1+ke) def <API key>(c_length, c_particle, init_b, final_b, tg, flow, v_m, v_d, lssparam , crit_res=1.4): """Function to estimate critical couples and resolutions N.B.: The molecule id correspond to the exact position in lssparam. """ if final_b > 1 or final_b < 0 or isnan(final_b) or init_b < 0 or init_b > 1 or isnan(init_b) or tg < 0 or isnan(tg): return None, None else: deltafi = final_b - init_b t0 = v_m/flow td = v_d/flow N = (c_length*10000.)/(3.4*c_particle) trtab = [] lssmol = SSGenerator(None, None, None, t0, v_d, flow) i = 0 for row in lssparam: lss_logkw = float(row[0]) lss_s = float(row[1]) W = get_lss_peak_width(c_length, c_particle, lss_logkw, lss_s, init_b, final_b, tg, flow, v_m, v_d, None) try: tr_tmp = lssmol.rtpred(lss_logkw, lss_s, tg, init_b, final_b, t0, td) if tr_tmp < t0 or tr_tmp > tg or isnan(tr_tmp): continue #trtab.append([t0, W, i]) else: trtab.append([tr_tmp, W, i]) except: trtab.append([t0, W, i]) i += 1 if len(trtab) < len(lssparam): return None, None else: trtab = sorted(trtab, key=lambda x:x[0]) if trtab[-1][0] > tg: #if the maximumt time is over the time gradient Error!! return None, None else: lstcc = [] lowestrs = None for i in range(1, len(trtab)): # Multiply by 1.7 to obtain the peak width at base. width1 = trtab[i][1] * 1.7 width2 = trtab[i-1][1] * 1.7 tr1 = trtab[i-1][0] tr2 = trtab[i][0] rs = (2.*(tr2-tr1)) / (width1+width2) if rs < crit_res: # Save the original id of lssparam lstcc.append([trtab[i-1][2], trtab[i][2], rs]) if lowestrs != None: if rs < lowestrs: lowestrs = rs else: continue else: lowestrs = rs else: continue return lstcc, lowestrs def <API key>(c_lenght, c_particle, init_b, final_b, tg, flow, v_m, v_d, lssparam , crit_alpha=1.1): """Function to estimate critical couples and selectivity N.B.: The molecule id correspond to the exact position in lssparam. """ if final_b > 1 or final_b < 0 or isnan(final_b) or init_b < 0 or init_b > 1 or isnan(init_b) or tg < 0 or isnan(tg): return None, None else: deltafi = final_b - init_b t0 = v_m/flow td = v_d/flow trtab = [] lssmol = SSGenerator(None, None, None, t0, v_d, flow) i = 0 for row in lssparam: lss_logkw = float(row[0]) lss_s = float(row[1]) b = (t0*(final_b-init_b)*lss_s)/tg try: tr_tmp = lssmol.rtpred(lss_logkw, lss_s, tg, init_b, final_b, t0, td) if tr_tmp < t0 or isnan(tr_tmp) or tr_tmp > tg: return None, None # these condition are not ok for selectivity calculations else: trtab.append([tr_tmp, i]) except: return None, None # these condition are not ok for selectivity calculations i += 1 trtab = sorted(trtab, key=lambda x:x[0]) if trtab[-1][0] > tg or trtab[0][0]-t0 < 0.3: #if the maximumt time is over the time gradient Error!! return None, None else: lstcc = [] lowest_alpha = None for i in range(1, len(trtab)): # Multiply by 1.7 to obtain the peak width at base. alpha = trtab[i][0] / trtab[i-1][0] if lowest_alpha != None: if alpha < lowest_alpha: lowest_alpha = alpha else: lowest_alpha = alpha if alpha < crit_alpha: # Save the original id of lssparam lstcc.append([trtab[i-1][1], trtab[i][1], alpha]) else: continue return lstcc, lowest_alpha def <API key>(c_length, c_particle, lss_logkw, lss_s, init_b, final_b, tg, flow, v_m, v_d, s_extra): """ Peak width estimation for logarithmic solvent strength using the Snynder and Dolan modelling and considering also the peak compression effect G """ alpha = (final_b - init_b)/log10(tg+1) N = (c_length*10000.)/(3.4*c_particle) t0 = v_m*flow b = lss_s * alpha k0 = logkw-(s*init_b) ke = 1/(2.3*b) p = (2.3*b*k0)/(k0+1) G = ((1+p+(p**2/3))/(1+p)**2)**(1/2.) Nobs = 0. if s_extra != None: s_col = (v_m*(1+ke))/N Nobs = N*(1/(1+(s_extra/s_col))) else: Nobs = N return 4*Nobs**(-1/2.)*G*t0*(1+ke) def <API key>(c_length, c_particle, init_b, final_b, tg, flow, v_m, v_d, lssparam , crit_res=1.4): """Function to estimate critical couples and resolutions for logarithmic gradient mode N.B.: The molecule id correspond to the exact position in lssparam. """ if final_b > 1 or final_b < 0 or isnan(final_b) or init_b < 0 or init_b > 1 or isnan(init_b) or tg < 0 or isnan(tg): return None, None else: trtab = [] logssmol = SSGenerator(None, None, None, t0, v_d, flow) i = 0 for row in lssparam: lss_logkw = float(row[0]) lss_s = float(row[1]) W = <API key>(c_length, c_particle, lss_logkw, lss_s, init_b, final_b, tg, flow, v_m, v_d, None) try: tr_tmp = logssmol.logrtpred(lss_logkw, lss_s, tg, init_b, final_b, t0, td) if tr_tmp < t0 or isnan(tr_tmp): trtab.append([t0, W, i]) else: trtab.append([tr_tmp, W, i]) except: trtab.append([t0, W, i]) i += 1 trtab = sorted(trtab, key=lambda x:x[0]) if trtab[-1][0] > tg: #if the maximumt time is over the time gradient Error!! return None, None else: lstcc = [] lowestrs = None for i in range(1, len(trtab)): # Multiply by 1.7 to obtain the peak width at base. width1 = trtab[i][1] * 1.7 width2 = trtab[i-1][1] * 1.7 tr1 = trtab[i-1][0] tr2 = trtab[i][0] rs = (2.*(tr2-tr1)) / (width1+width2) if rs < crit_res: # Save the original id of lssparam lstcc.append([trtab[i-1][2], trtab[i][2], rs]) if lowestrs != None: if rs < lowestrs: lowestrs = rs else: continue else: lowestrs = rs else: continue return lstcc, lowestrs def <API key>(c_lenght, c_particle, init_b, final_b, tg, flow, v_m, v_d, lssparam, crit_alpha=1.1): """Function to estimate critical couples and resolutions for logarithmic gradient mode N.B.: The molecule id correspond to the exact position in lssparam. """ if final_b > 1 or final_b < 0 or isnan(final_b) or init_b < 0 or init_b > 1 or isnan(init_b) or tg < 0 or isnan(tg): return None, None else: t0 = v_m/flow td = v_d/flow N = (c_lenght*10000.)/(3.4*c_particle) trtab = [] logssmol = SSGenerator(None, None, None, t0, v_d, flow) i = 0 for row in lssparam: lss_logkw = float(row[0]) lss_s = float(row[1]) try: tr_tmp = logssmol.logrtpred(lss_logkw, lss_s, tg, init_b, final_b, t0, td) if tr_tmp < t0 or isnan(tr_tmp): return None, None # these condition are not ok for selectivity calculations else: trtab.append([tr_tmp, i]) except: return None, None # these condition are not ok for selectivity calculations i += 1 if len(trtab) == len(lssparam): trtab = sorted(trtab, key=lambda x:x[0]) lstcc = [] lowest_alpha = (trtab[1][0] - t0) / (trtab[0][0]-t0) for i in range(1, len(trtab)): alpha = (trtab[i][0]-t0) / (trtab[i-1][0]-t0) #print trtab[i][0], trtab[i-1][0], t0, (trtab[i][0] - t0), (trtab[i-1][0]-t0) if alpha < lowest_alpha: lowest_alpha = alpha if alpha < crit_alpha: # Save the original id of lssparam lstcc.append([trtab[i-1][1], trtab[i][1], alpha]) return lstcc, lowest_alpha else: return None, None
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-b10 // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.06.13 at 12:42:16 PM CEST package com.telefonica.schemas.unica.rpc.common.v1; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.telefonica.schemas.unica.rpc.common.v1 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.telefonica.schemas.unica.rpc.common.v1 * */ public ObjectFactory() { } /** * Create an instance of {@link UserIdType } * */ public UserIdType createUserIdType() { return new UserIdType(); } /** * Create an instance of {@link SimpleReferenceType } * */ public SimpleReferenceType <API key>() { return new SimpleReferenceType(); } /** * Create an instance of {@link OtherIdType } * */ public OtherIdType createOtherIdType() { return new OtherIdType(); } /** * Create an instance of {@link IpAddressType } * */ public IpAddressType createIpAddressType() { return new IpAddressType(); } }
package masp.plugins.mlight.managers; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import masp.plugins.mlight.data.Attribute; public class AttributeManager { private Map<String, Attribute> skills = new LinkedHashMap<String, Attribute>(); public Attribute getSkill(String name) { if (skills.containsKey(name)) { return skills.get(name); } throw new <API key>(name); } public boolean skillExists(String name) { if (skills.containsKey(name)) { return true; } return false; } public void addSkill(Attribute skill) { if (!skills.containsKey(skill.getName())) { skills.put(skill.getName(), skill); } } public void removeSkill(String name) { skills.remove(name); } public void removeSkill(Attribute skill) { skills.remove(skill.getName()); } public Collection<Attribute> getSkills() { return skills.values(); } private class <API key> extends <API key> { private static final long serialVersionUID = -<API key>; private String name; public <API key>(String name) { this.name = name; } @Override public String getMessage() { return "Skill class was unable to be found by the name " + name; } } }
<?php namespace MyBackup; include_once 'utils.php'; if ( defined( __NAMESPACE__.'\\DROPBOX_TARGET' ) ) { } if ( defined( __NAMESPACE__.'\\GOOGLE_TARGET' ) ) { } define( __NAMESPACE__.'\\DENY_DOWNLOAD_EXT', 'php,htaccess,config,conf,json,auth' ); function downloadAllowed( $filename ) { $extensions = explode( ',', DENY_DOWNLOAD_EXT ); if ( empty( $extensions ) ) return true; $ext = ''; preg_match( '/\.([^\.]*)$/', $filename, $matches ) && $ext = $matches[1]; return ! in_array( $ext, $extensions ); } function redirectError( $message, $timeout ) { echo "<!DOCTYPE html><html><body>$message<script>setTimeout(function(){window.history.go(-1);}, $timeout);</script></body></html>"; exit(); } function downloadServiceFile( $service, $path, $outfile, $settings, $redirect_error = true ) { if ( ! downloadAllowed( $path ) ) return; $session = null; switch ( $service ) { case 'dropbox' : $session = new DropboxOAuth2Client(); $api = new DropboxCloudStorage( $session ); $function = 'downloadFile'; $oauth_file = 'dropbox.auth'; break; case 'google' : $session = new GoogleOAuth2Client(); $api = new GoogleCloudStorage( $session ); $function = preg_match( '/^http:\/\//', $path ) ? 'downloadUrl' : 'downloadFile'; $oauth_file = 'google.auth'; $outfile = null; break; case 'webdav' : $api = new WebDAVWebStorage( $settings ); $function = 'downloadFile'; break; default : throw new MyException( 'Unknown download file service' ); break; } if ( null != $session ) { $session->setProxyURI( OAUTH_PROXY_URL, '' ); $session->setTimeout( $settings['request_timeout'] ); $session->initFromFile( ROOT_OAUTH_FILE . $oauth_file ); } $err = null; try { $result = _call_user_func( array( $api, $function ), $path, $outfile ); if ( true !== $result ) $err = $result; } catch ( \Exception $e ) { $err = $e->getMessage(); } if ( $redirect_error && ! empty( $err ) ) echo redirectError( $err, 3000 ); return _call_user_func( array( $api, 'getFile' ), $path ); } function downloadFile( $filename = null, $service = null, $settings = null, $download = true ) { if ( ! downloadAllowed( $filename ) ) { return; } if ( ! ( empty( $service ) || empty( $filename ) ) ) { $unlink = in_array( $service, array( 'google', 'dropbox', 'ftp', 'webdav', 'test' ) ); $mime_type = 'application/octet-stream'; $tmpfile = ! empty( $filename ) ? addTrailingSlash( defined( __NAMESPACE__.'\\LOG_DIR' ) ? LOG_DIR : _sys_get_temp_dir() ) . basename( $filename ) : null; switch ( $service ) { case 'dropbox' : case 'google' : case 'webdav' : $mime_type = downloadServiceFile( $service, $filename, $tmpfile, $settings, $download ); $mime_type = ! empty( $mime_type['mime_type'] ) ? $mime_type['mime_type'] : null; break; case 'ssh' : case 'ftp' : $ftp = getFtpObject( $settings, 'ssh' == $service ); $ftp->ftpDownload( $filename, $tmpfile ); break; case 'test' : case 'disk' : $tmpfile = $filename; break; default : echo sprintf( _esc( "Download method '%s' not implemented" ), $service ); break; } if ( isset( $tmpfile ) && _file_exists( $tmpfile ) && ! empty( $mime_type ) ) { if ( $download ) { <API key>( $tmpfile, $mime_type ); if ( $unlink ) @unlink( $tmpfile ); } else return $tmpfile; } } $download && exit(); return false; } ?>
// This code contains NVIDIA Confidential Information and is disclosed to you // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. #ifndef <API key> #define <API key> #include "PxPvdClient.h" #include "PsHashMap.h" #include "PsMutex.h" #include "<API key>.h" namespace physx { namespace pvdsdk { class PvdImpl; class PvdDataStream; struct ProfileZoneClient; class <API key> : public PvdClient, public profile::<API key>, public shdfnd::UserAllocated { PX_NOCOPY(<API key>) public: <API key>(PvdImpl& pvd); virtual ~<API key>(); bool isConnected() const; void onPvdConnected(); void onPvdDisconnected(); void flush(); PvdDataStream* getDataStream(); PvdUserRenderer* getUserRender(); // <API key> void onZoneAdded(profile::PxProfileZone& inSDK); void onZoneRemoved(profile::PxProfileZone& inSDK); private: shdfnd::Mutex mMutex; // zoneAdded can called from different threads PvdImpl& mSDKPvd; PvdDataStream* mPvdDataStream; physx::shdfnd::Array<ProfileZoneClient*> mProfileZoneClients; bool mIsConnected; }; } // namespace pvdsdk } // namespace physx #endif // <API key>
<!doctype html> <head> <title>$pese</title> {%include 'links.html'%} <script> $(document).ready(function() { $('select').material_select(); $('.button-collapse').sideNav(); }); </script> </head> <body> {%include 'navbar_sidebar.html'%} <div class="row"> <div class="col s12"> <div class="card"> <div class="card-content white-text"> <table class=""> <thead> <tr> <th> Creditore </th> <th> Importo </th> <th> Data </th> <th> Descrizione </th> </tr> </thead> <tbody> {% for entry in lista %} <tr> <td> {{ entry.nome }} </td> <td> {{ "{0:.2f}".format(entry.importo) }} € </td> <td> {{ entry.data }} </td> <td> {{ entry.descrizione }} </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </body>
package net.sf.dynamicreports.examples.column; import static net.sf.dynamicreports.report.builder.DynamicReports.*; import java.math.BigDecimal; import net.sf.dynamicreports.examples.Templates; import net.sf.dynamicreports.report.builder.column.TextColumnBuilder; import net.sf.dynamicreports.report.datasource.DRDataSource; import net.sf.dynamicreports.report.exception.DRException; import net.sf.jasperreports.engine.JRDataSource; /** * @author Ricardo Mariaca (r.mariaca@dynamicreports.org) */ public class <API key> { public <API key>() { build(); } private void build() { TextColumnBuilder<Integer> column1 = col.column("A", "field1", type.integerType()); TextColumnBuilder<Integer> column2 = col.column("B", "field2", type.integerType()); TextColumnBuilder<BigDecimal> column3 = column1.multiply(column2).setTitle("A * B"); TextColumnBuilder<BigDecimal> column4 = column1.divide(2, column2).setTitle("A / B"); TextColumnBuilder<BigDecimal> column5 = column1.add(column2).setTitle("A + B"); TextColumnBuilder<BigDecimal> column6 = column1.subtract(column2).setTitle("A - B"); TextColumnBuilder<BigDecimal> column7 = column3.add(6).setTitle("A * B + 6"); TextColumnBuilder<BigDecimal> column8 = column7.divide(2, 5).add(1).setTitle("(A*B+6) / 5 + 1"); try { report() .setTemplate(Templates.reportTemplate) .columns( column1, column2, column3, column4, column5, column6, column7, column8) .title(Templates.<API key>("CalculatedColumn")) .pageFooter(Templates.footerComponent) .setDataSource(createDataSource()) .show(); } catch (DRException e) { e.printStackTrace(); } } private JRDataSource createDataSource() { DRDataSource dataSource = new DRDataSource("field1", "field2"); dataSource.add(10, 5); return dataSource; } public static void main(String[] args) { new <API key>(); } }
<?php namespace application\modules\user\controllers; class Delete extends \application\modules\user\<API key> { protected $usesView = false; public function _before(\framework\core\Request &$request, \framework\core\Response &$response) { $var = $request->getParams(); if (empty($var)) { $url = $this->getConfig("siteUrl") . "user"; $this->getComponent("httpResponse")->redirect($url); } } public function processAction($userId) { $url = $this->getConfig("siteUrl") . "user"; $em = $this->getComponent("entityManager"); $user = $em->getRepository('application\modules\user\models\User')->find($userId); if ($user) { $em->remove($user); } $this->getComponent("httpResponse")->redirect($url, 302, false); } }
function O_vio_console_in (name) { this.name = name; } O_vio_console_in.prototype.close = function () { } function O_vio_console_out (name) { this.name = name; } O_vio_console_out.prototype.close = function () { } var O_vio_protocols_in = { console: O_vio_console_in, // http: O_vio_http_in } var O_vio_protocols_out = { console: O_vio_console_out, // http: O_vio_http_in } function O_vio_open_in (uri) { var parts = /([^:]+):\/\/(.*)/.exec (uri); var protocol, name; if (parts) { protocol = O_vio_protocols_in[parts[1]]; name = parts[2]; } else { protocol = O_vio_protocols_in["http"]; name = uri; } return new protocol (name); } function O_vio_open_out (uri) { var parts = /([^:]+):\/\/(.*)/.exec (uri); var protocol, name; if (parts) { protocol = O_vio_protocols_out[parts[1]]; name = parts[2]; } else { protocol = O_vio_protocols_out["post"]; name = uri; } return new protocol (name); } var O_vio_ops = { id: "_vio", compare: function (x, y) { return (x == y); }, hash: function () { O_fatal ("cannot hash a vio channel"); }, serialize: function () { O_fatal ("cannot serialize a vio channel"); }, deserialize: function () { O_fatal ("cannot deserialize a vio channel"); } } function <API key> (descr /* : int */) /* : in_channel */ { if (int_val (descr) == 0) return mk_custom (O_vio_ops, new O_vio_console_in ("STDIN")); else O_fatal ("<API key> unsupported"); } function <API key> (descr /* : int */) /* : out_channel */ { if (int_val (descr) == 1) return mk_custom (O_vio_ops, new O_vio_console_out ("STDOUT")); else if (int_val (descr) == 2) return mk_custom (O_vio_ops, new O_vio_console_out ("STDERR")); else O_fatal ("<API key> unsupported"); }
package org.ethereum.core; import com.google.common.util.concurrent.<API key>; import org.ethereum.config.BlockchainConfig; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.crypto.HashUtil; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.db.*; import org.ethereum.trie.Trie; import org.ethereum.trie.TrieImpl; import org.ethereum.listener.EthereumListener; import org.ethereum.listener.<API key>; import org.ethereum.manager.AdminInfo; import org.ethereum.sync.SyncManager; import org.ethereum.util.*; import org.ethereum.validator.<API key>; import org.ethereum.validator.<API key>; import org.ethereum.vm.program.invoke.<API key>; import org.ethereum.vm.program.invoke.<API key>; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.concurrent.*; import static java.lang.Math.PI; import static java.lang.Math.max; import static java.lang.Runtime.getRuntime; import static java.math.BigInteger.ONE; import static java.math.BigInteger.ZERO; import static java.util.Collections.emptyList; import static org.ethereum.core.Denomination.SZABO; import static org.ethereum.core.ImportResult.*; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.BIUtil.isMoreThan; @Component public class BlockchainImpl implements Blockchain, org.ethereum.facade.Blockchain { private static final Logger logger = LoggerFactory.getLogger("blockchain"); private static final Logger stateLogger = LoggerFactory.getLogger("state"); // to avoid using minGasPrice=0 from Genesis for the wallet private static final long <API key> = 10 * SZABO.longValue(); private static final int MAGIC_REWARD_OFFSET = 8; public static final byte[] EMPTY_LIST_HASH = sha3(RLP.encodeList(new byte[0])); @Autowired @Qualifier("defaultRepository") private Repository repository; @Autowired protected BlockStore blockStore; @Autowired private TransactionStore transactionStore; private Block bestBlock; private BigInteger totalDifficulty = ZERO; @Autowired private EthereumListener listener; @Autowired <API key> <API key>; @Autowired private AdminInfo adminInfo; @Autowired private <API key> <API key>; @Autowired private PendingState pendingState; @Autowired EventDispatchThread eventDispatchThread; @Autowired CommonConfig commonConfig = CommonConfig.getDefault(); @Autowired SyncManager syncManager; @Autowired PruneManager pruneManager; @Autowired StateSource stateDataSource; @Autowired DbFlushManager dbFlushManager; SystemProperties config = SystemProperties.getDefault(); private List<Chain> altChains = new ArrayList<>(); private List<Block> garbage = new ArrayList<>(); long exitOn = Long.MAX_VALUE; public boolean byTest = false; private boolean fork = false; private byte[] minerCoinbase; private byte[] minerExtraData; private int UNCLE_LIST_LIMIT; private int <API key>; private Stack<State> stateStack = new Stack<>(); /** Tests only **/ public BlockchainImpl() { } @Autowired public BlockchainImpl(final SystemProperties config) { this.config = config; initConst(config); } //todo: autowire over constructor public BlockchainImpl(final BlockStore blockStore, final Repository repository) { this.blockStore = blockStore; this.repository = repository; this.adminInfo = new AdminInfo(); this.listener = new <API key>(); this.<API key> = null; this.transactionStore = new TransactionStore(new HashMapDB()); this.eventDispatchThread = EventDispatchThread.getDefault(); this.<API key> = new <API key>(); initConst(SystemProperties.getDefault()); } public BlockchainImpl <API key>(TransactionStore transactionStore) { this.transactionStore = transactionStore; return this; } public BlockchainImpl withAdminInfo(AdminInfo adminInfo) { this.adminInfo = adminInfo; return this; } public BlockchainImpl <API key>(EthereumListener listener) { this.listener = listener; return this; } public BlockchainImpl withSyncManager(SyncManager syncManager) { this.syncManager = syncManager; return this; } public BlockchainImpl <API key>(<API key> <API key>) { this.<API key> = <API key>; return this; } private void initConst(SystemProperties config) { minerCoinbase = config.getMinerCoinbase(); minerExtraData = config.getMineExtraData(); UNCLE_LIST_LIMIT = config.getBlockchainConfig().getCommonConstants().getUNCLE_LIST_LIMIT(); <API key> = config.getBlockchainConfig().getCommonConstants().<API key>(); } @Override public byte[] getBestBlockHash() { return getBestBlock().getHash(); } @Override public long getSize() { return bestBlock.getNumber() + 1; } @Override public Block getBlockByNumber(long blockNr) { return blockStore.<API key>(blockNr); } @Override public TransactionInfo getTransactionInfo(byte[] hash) { List<TransactionInfo> infos = transactionStore.get(hash); if (infos == null || infos.isEmpty()) return null; TransactionInfo txInfo = null; if (infos.size() == 1) { txInfo = infos.get(0); } else { // pick up the receipt from the block on the main chain for (TransactionInfo info : infos) { Block block = blockStore.getBlockByHash(info.blockHash); Block mainBlock = blockStore.<API key>(block.getNumber()); if (FastByteComparisons.equal(info.blockHash, mainBlock.getHash())) { txInfo = info; break; } } } if (txInfo == null) { logger.warn("Can't find block from main chain for transaction " + Hex.toHexString(hash)); return null; } Transaction tx = this.getBlockByHash(txInfo.getBlockHash()).getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(tx); return txInfo; } @Override public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); } @Override public synchronized List<byte[]> <API key>(byte[] hash, int qty) { return blockStore.<API key>(hash, qty); } @Override public synchronized List<byte[]> <API key>(long blockNumber, int qty) { long bestNumber = bestBlock.getNumber(); if (blockNumber > bestNumber) { return emptyList(); } if (blockNumber + qty - 1 > bestNumber) { qty = (int) (bestNumber - blockNumber + 1); } long endNumber = blockNumber + qty - 1; Block block = getBlockByNumber(endNumber); List<byte[]> hashes = blockStore.<API key>(block.getHash(), qty); // asc order of hashes is required in the response Collections.reverse(hashes); return hashes; } public static byte[] calcTxTrie(List<Transaction> transactions) { Trie txsState = new TrieImpl(); if (transactions == null || transactions.isEmpty()) return HashUtil.EMPTY_TRIE_HASH; for (int i = 0; i < transactions.size(); i++) { txsState.put(RLP.encodeInt(i), transactions.get(i).getEncoded()); } return txsState.getRootHash(); } public Repository getRepository() { return repository; } public Repository <API key>() { return repository.getSnapshotTo(blockStore.getBestBlock().getStateRoot()); } @Override public BlockStore getBlockStore() { return blockStore; } public <API key> <API key>() { return <API key>; } private State pushState(byte[] bestBlockHash) { State push = stateStack.push(new State()); this.bestBlock = blockStore.getBlockByHash(bestBlockHash); totalDifficulty = blockStore.<API key>(bestBlockHash); this.repository = this.repository.getSnapshotTo(this.bestBlock.getStateRoot()); return push; } private void popState() { State state = stateStack.pop(); this.repository = repository.getSnapshotTo(state.root); this.bestBlock = state.savedBest; this.totalDifficulty = state.savedTD; } public void dropState() { stateStack.pop(); } private synchronized BlockSummary tryConnectAndFork(final Block block) { State savedState = pushState(block.getParentHash()); this.fork = true; final BlockSummary summary; Repository repo; try { // FIXME: adding block with no option for flush Block parentBlock = getBlockByHash(block.getParentHash()); repo = repository.getSnapshotTo(parentBlock.getStateRoot()); summary = add(repo, block); if (summary == null) { return null; } } catch (Throwable th) { logger.error("Unexpected error: ", th); return null; } finally { this.fork = false; } if (summary.betterThan(savedState.savedTD)) { logger.info("Rebranching: {} ~> {}", savedState.savedBest.getShortHash(), block.getShortHash()); // main branch become this branch // cause we proved that total difficulty // is greateer blockStore.reBranch(block); // The main repository rebranch this.repository = repo; // this.repository.syncToRoot(block.getStateRoot()); dropState(); } else { // Stay on previous branch popState(); } return summary; } public synchronized ImportResult tryToConnect(final Block block) { if (logger.isDebugEnabled()) logger.debug("Try connect block hash: {}, number: {}", Hex.toHexString(block.getHash()).substring(0, 6), block.getNumber()); if (blockStore.getMaxNumber() >= block.getNumber() && blockStore.isBlockExist(block.getHash())) { if (logger.isDebugEnabled()) logger.debug("Block already exist hash: {}, number: {}", Hex.toHexString(block.getHash()).substring(0, 6), block.getNumber()); // retry of well known block return EXIST; } final ImportResult ret; // The simple case got the block // to connect to the main chain final BlockSummary summary; if (bestBlock.isParentOf(block)) { recordBlock(block); // Repository repoSnap = repository.getSnapshotTo(bestBlock.getStateRoot()); summary = add(repository, block); ret = summary == null ? INVALID_BLOCK : IMPORTED_BEST; } else { if (blockStore.isBlockExist(block.getParentHash())) { BigInteger oldTotalDiff = getTotalDifficulty(); recordBlock(block); summary = tryConnectAndFork(block); ret = summary == null ? INVALID_BLOCK : (summary.betterThan(oldTotalDiff) ? IMPORTED_BEST : IMPORTED_NOT_BEST); } else { summary = null; ret = NO_PARENT; } } if (ret.isSuccessful()) { listener.onBlock(summary); listener.trace(String.format("Block chain size: [ %d ]", this.getSize())); if (ret == IMPORTED_BEST) { eventDispatchThread.invokeLater(() -> pendingState.processBest(block, summary.getReceipts())); } } return ret; } public synchronized Block createNewBlock(Block parent, List<Transaction> txs, List<BlockHeader> uncles) { long time = System.currentTimeMillis() / 1000; // adjust time to parent block this may happen due to system clocks difference if (parent.getTimestamp() >= time) time = parent.getTimestamp() + 1; return createNewBlock(parent, txs, uncles, time); } public synchronized Block createNewBlock(Block parent, List<Transaction> txs, List<BlockHeader> uncles, long time) { final long blockNumber = parent.getNumber() + 1; final byte[] extraData = config.getBlockchainConfig().getConfigForBlock(blockNumber).getExtraData(minerExtraData, blockNumber); Block block = new Block(parent.getHash(), EMPTY_LIST_HASH, // uncleHash minerCoinbase, new byte[0], // log bloom - from tx receipts new byte[0], // difficulty computed right after block creation blockNumber, parent.getGasLimit(), // (add to config ?) 0, // gas used - computed after running all transactions time, // block time extraData, // extra data new byte[0], // mixHash (to mine) new byte[0], // nonce (to mine) new byte[0], // receiptsRoot - computed after running all transactions calcTxTrie(txs), // TransactionsRoot - computed after running all transactions new byte[] {0}, // stateRoot - computed after running all transactions txs, null); // uncle list for (BlockHeader uncle : uncles) { block.addUncle(uncle); } block.getHeader().setDifficulty(ByteUtil.bigIntegerToBytes(block.getHeader(). calcDifficulty(config.getBlockchainConfig(), parent.getHeader()))); Repository track = repository.getSnapshotTo(parent.getStateRoot()); BlockSummary summary = applyBlock(track, block); List<TransactionReceipt> receipts = summary.getReceipts(); block.setStateRoot(track.getRoot()); Bloom logBloom = new Bloom(); for (TransactionReceipt receipt : receipts) { logBloom.or(receipt.getBloomFilter()); } block.getHeader().setLogsBloom(logBloom.getData()); block.getHeader().setGasUsed(receipts.size() > 0 ? receipts.get(receipts.size() - 1).<API key>() : 0); block.getHeader().setReceiptsRoot(calcReceiptsTrie(receipts)); return block; } @Override public BlockSummary add(Block block) { throw new RuntimeException("Not supported"); } // @Override public synchronized BlockSummary add(Repository repo, final Block block) { BlockSummary summary = addImpl(repo, block); if (summary == null) { stateLogger.warn("Trying to reimport the block for debug..."); try { Thread.sleep(50); } catch (<API key> e) { } BlockSummary summary1 = addImpl(repo.getSnapshotTo(getBestBlock().getStateRoot()), block); stateLogger.warn("Second import trial " + (summary1 == null ? "FAILED" : "OK")); if (summary1 != null) { if (config.exitOnBlockConflict()) { stateLogger.error("Inconsistent behavior, exiting..."); System.exit(-1); } else { return summary1; } } } return summary; } public synchronized BlockSummary addImpl(Repository repo, final Block block) { if (exitOn < block.getNumber()) { System.out.print("Exiting after block.number: " + bestBlock.getNumber()); dbFlushManager.flushSync(); System.exit(-1); } if (!isValid(repo, block)) { logger.warn("Invalid block with number: {}", block.getNumber()); return null; } // Repository track = repo.startTracking(); byte[] origRoot = repo.getRoot(); if (block == null) return null; // keep chain continuity // if (!Arrays.equals(bestBlock.getHash(), // block.getParentHash())) return null; if (block.getNumber() >= config.traceStartBlock() && config.traceStartBlock() != -1) { AdvancedDeviceUtils.<API key>(config, block.getNumber()); } BlockSummary summary = processBlock(repo, block); final List<TransactionReceipt> receipts = summary.getReceipts(); // Sanity checks if (!FastByteComparisons.equal(block.getReceiptsRoot(), calcReceiptsTrie(receipts))) { logger.warn("Block's given Receipt Hash doesn't match: {} != {}", Hex.toHexString(block.getReceiptsRoot()), Hex.toHexString(calcReceiptsTrie(receipts))); logger.warn("Calculated receipts: " + receipts); repo.rollback(); summary = null; } if (!FastByteComparisons.equal(block.getLogBloom(), calcLogBloom(receipts))) { logger.warn("Block's given logBloom Hash doesn't match: {} != {}", Hex.toHexString(block.getLogBloom()), Hex.toHexString(calcLogBloom(receipts))); repo.rollback(); summary = null; } if (!FastByteComparisons.equal(block.getStateRoot(), repo.getRoot())) { stateLogger.warn("BLOCK: State conflict or received invalid block. block: {} worldstate {} mismatch", block.getNumber(), Hex.toHexString(repo.getRoot())); stateLogger.warn("Conflict block dump: {}", Hex.toHexString(block.getEncoded())); // track.rollback(); // repository.rollback(); repository = repository.getSnapshotTo(origRoot); // block is bad so 'rollback' the state root to the original state // ((RepositoryImpl) repository).setRoot(origRoot); // track.rollback(); // block is bad so 'rollback' the state root to the original state // ((RepositoryImpl) repository).setRoot(origRoot); if (config.exitOnBlockConflict()) { adminInfo.lostConsensus(); System.out.println("CONFLICT: BLOCK #" + block.getNumber() + ", dump: " + Hex.toHexString(block.getEncoded())); System.exit(1); } else { summary = null; } } if (summary != null) { repo.commit(); <API key>(block); summary.setTotalDifficulty(getTotalDifficulty()); if (!byTest) { dbFlushManager.commit(() -> { storeBlock(block, receipts); repository.commit(); }); } else { storeBlock(block, receipts); } } return summary; } @Override public void flush() { // repository.flush(); // stateDataSource.flush(); // blockStore.flush(); // transactionStore.flush(); // repository = repository.getSnapshotTo(repository.getRoot()); // if (isMemoryBoundFlush()) { // System.gc(); } private boolean needFlushByMemory(double maxMemoryPercents) { return getRuntime().freeMemory() < (getRuntime().totalMemory() * (1 - maxMemoryPercents)); } public static byte[] calcReceiptsTrie(List<TransactionReceipt> receipts) { Trie receiptsTrie = new TrieImpl(); if (receipts == null || receipts.isEmpty()) return HashUtil.EMPTY_TRIE_HASH; for (int i = 0; i < receipts.size(); i++) { receiptsTrie.put(RLP.encodeInt(i), receipts.get(i).<API key>()); } return receiptsTrie.getRootHash(); } private byte[] calcLogBloom(List<TransactionReceipt> receipts) { Bloom retBloomFilter = new Bloom(); if (receipts == null || receipts.isEmpty()) return retBloomFilter.getData(); for (TransactionReceipt receipt : receipts) { retBloomFilter.or(receipt.getBloomFilter()); } return retBloomFilter.getData(); } public Block getParent(BlockHeader header) { return blockStore.getBlockByHash(header.getParentHash()); } public boolean isValid(BlockHeader header) { if (<API key> == null) return true; Block parentBlock = getParent(header); if (!<API key>.validate(header, parentBlock.getHeader())) { if (logger.isErrorEnabled()) <API key>.logErrors(logger); return false; } return true; } /** * This mechanism enforces a homeostasis in terms of the time between blocks; * a smaller period between the last two blocks results in an increase in the * difficulty level and thus additional computation required, lengthening the * likely next period. Conversely, if the period is too large, the difficulty, * and expected time to the next block, is reduced. */ private boolean isValid(Repository repo, Block block) { boolean isValid = true; if (!block.isGenesis()) { isValid = isValid(block.getHeader()); // Sanity checks String trieHash = Hex.toHexString(block.getTxTrieRoot()); String trieListHash = Hex.toHexString(calcTxTrie(block.getTransactionsList())); if (!trieHash.equals(trieListHash)) { logger.warn("Block's given Trie Hash doesn't match: {} != {}", trieHash, trieListHash); return false; } // if (!validateUncles(block)) return false; List<Transaction> txs = block.getTransactionsList(); if (!txs.isEmpty()) { // Repository parentRepo = repository; // if (!Arrays.equals(bestBlock.getHash(), block.getParentHash())) { // parentRepo = repository.getSnapshotTo(getBlockByHash(block.getParentHash()).getStateRoot()); Map<ByteArrayWrapper, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { byte[] txSender = tx.getSender(); ByteArrayWrapper key = new ByteArrayWrapper(txSender); BigInteger expectedNonce = curNonce.get(key); if (expectedNonce == null) { expectedNonce = repo.getNonce(txSender); } curNonce.put(key, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}", txNonce, expectedNonce, repo.getNonce(txSender), tx); return false; } } } } return isValid; } public boolean validateUncles(Block block) { String unclesHash = Hex.toHexString(block.getHeader().getUnclesHash()); String unclesListHash = Hex.toHexString(HashUtil.sha3(block.getHeader().getUnclesEncoded(block.getUncleList()))); if (!unclesHash.equals(unclesListHash)) { logger.warn("Block's given Uncle Hash doesn't match: {} != {}", unclesHash, unclesListHash); return false; } if (block.getUncleList().size() > UNCLE_LIST_LIMIT) { logger.warn("Uncle list to big: block.getUncleList().size() > UNCLE_LIST_LIMIT"); return false; } Set<ByteArrayWrapper> ancestors = getAncestors(blockStore, block, <API key> + 1, false); Set<ByteArrayWrapper> usedUncles = getUsedUncles(blockStore, block, false); for (BlockHeader uncle : block.getUncleList()) { // - They are valid headers (not necessarily valid blocks) if (!isValid(uncle)) return false; //if uncle's parent's number is not less than currentBlock - UNCLE_GEN_LIMIT, mark invalid boolean isValid = !(getParent(uncle).getNumber() < (block.getNumber() - <API key>)); if (!isValid) { logger.warn("Uncle too old: generationGap must be under <API key>"); return false; } ByteArrayWrapper uncleHash = new ByteArrayWrapper(uncle.getHash()); if (ancestors.contains(uncleHash)) { logger.warn("Uncle is direct ancestor: " + Hex.toHexString(uncle.getHash())); return false; } if (usedUncles.contains(uncleHash)) { logger.warn("Uncle is not unique: " + Hex.toHexString(uncle.getHash())); return false; } Block uncleParent = blockStore.getBlockByHash(uncle.getParentHash()); if (!ancestors.contains(new ByteArrayWrapper(uncleParent.getHash()))) { logger.warn("Uncle has no common parent: " + Hex.toHexString(uncle.getHash())); return false; } } return true; } public static Set<ByteArrayWrapper> getAncestors(BlockStore blockStore, Block testedBlock, int limitNum, boolean isParentBlock) { Set<ByteArrayWrapper> ret = new HashSet<>(); limitNum = (int) max(0, testedBlock.getNumber() - limitNum); Block it = testedBlock; if (!isParentBlock) { it = blockStore.getBlockByHash(it.getParentHash()); } while(it != null && it.getNumber() >= limitNum) { ret.add(new ByteArrayWrapper(it.getHash())); it = blockStore.getBlockByHash(it.getParentHash()); } return ret; } public Set<ByteArrayWrapper> getUsedUncles(BlockStore blockStore, Block testedBlock, boolean isParentBlock) { Set<ByteArrayWrapper> ret = new HashSet<>(); long limitNum = max(0, testedBlock.getNumber() - <API key>); Block it = testedBlock; if (!isParentBlock) { it = blockStore.getBlockByHash(it.getParentHash()); } while(it.getNumber() > limitNum) { for (BlockHeader uncle : it.getUncleList()) { ret.add(new ByteArrayWrapper(uncle.getHash())); } it = blockStore.getBlockByHash(it.getParentHash()); } return ret; } private BlockSummary processBlock(Repository track, Block block) { if (!block.isGenesis() && !config.blockChainOnly()) { return applyBlock(track, block); } else { return new BlockSummary(block, new HashMap<byte[], BigInteger>(), new ArrayList<TransactionReceipt>(), new ArrayList<<API key>>()); } } private BlockSummary applyBlock(Repository track, Block block) { logger.debug("applyBlock: block: [{}] tx.list: [{}]", block.getNumber(), block.getTransactionsList().size()); BlockchainConfig blockchainConfig = config.getBlockchainConfig().getConfigForBlock(block.getNumber()); blockchainConfig.hardForkTransfers(block, track); long saveTime = System.nanoTime(); int i = 1; long totalGasUsed = 0; List<TransactionReceipt> receipts = new ArrayList<>(); List<<API key>> summaries = new ArrayList<>(); for (Transaction tx : block.getTransactionsList()) { stateLogger.debug("apply block: [{}] tx: [{}] ", block.getNumber(), i); Repository txTrack = track.startTracking(); TransactionExecutor executor = new TransactionExecutor(tx, block.getCoinbase(), txTrack, blockStore, <API key>, block, listener, totalGasUsed) .withCommonConfig(commonConfig); executor.init(); executor.execute(); executor.go(); <API key> summary = executor.finalization(); totalGasUsed += executor.getGasUsed(); txTrack.commit(); final TransactionReceipt receipt = executor.getReceipt(); if (blockchainConfig.eip658()) { receipt.setTxStatus(receipt.isSuccessful()); } else { receipt.setPostTxState(track.getRoot()); } stateLogger.info("block: [{}] executed tx: [{}] \n state: [{}]", block.getNumber(), i, Hex.toHexString(track.getRoot())); stateLogger.info("[{}] ", receipt.toString()); if (stateLogger.isInfoEnabled()) stateLogger.info("tx[{}].receipt: [{}] ", i, Hex.toHexString(receipt.getEncoded())); // TODO // if (block.getNumber() >= config.traceStartBlock()) // repository.dumpState(block, totalGasUsed, i++, tx.getHash()); receipts.add(receipt); if (summary != null) { summaries.add(summary); } } Map<byte[], BigInteger> rewards = addReward(track, block, summaries); stateLogger.info("applied reward for block: [{}] \n state: [{}]", block.getNumber(), Hex.toHexString(track.getRoot())); // TODO // if (block.getNumber() >= config.traceStartBlock()) // repository.dumpState(block, totalGasUsed, 0, null); long totalTime = System.nanoTime() - saveTime; adminInfo.addBlockExecTime(totalTime); logger.debug("block: num: [{}] hash: [{}], executed after: [{}]nano", block.getNumber(), block.getShortHash(), totalTime); return new BlockSummary(block, rewards, receipts, summaries); } /** * Add reward to block- and every uncle coinbase * assuming the entire block is valid. * * @param block object containing the header and uncles */ private Map<byte[], BigInteger> addReward(Repository track, Block block, List<<API key>> summaries) { Map<byte[], BigInteger> rewards = new HashMap<>(); BigInteger blockReward = config.getBlockchainConfig().getConfigForBlock(block.getNumber()).getConstants().getBLOCK_REWARD(); BigInteger inclusionReward = blockReward.divide(BigInteger.valueOf(32)); // Add extra rewards based on number of uncles if (block.getUncleList().size() > 0) { for (BlockHeader uncle : block.getUncleList()) { BigInteger uncleReward = blockReward .multiply(BigInteger.valueOf(MAGIC_REWARD_OFFSET + uncle.getNumber() - block.getNumber())) .divide(BigInteger.valueOf(MAGIC_REWARD_OFFSET)); track.addBalance(uncle.getCoinbase(),uncleReward); BigInteger existingUncleReward = rewards.get(uncle.getCoinbase()); if (existingUncleReward == null) { rewards.put(uncle.getCoinbase(), uncleReward); } else { rewards.put(uncle.getCoinbase(), existingUncleReward.add(uncleReward)); } } } BigInteger minerReward = blockReward.add(inclusionReward.multiply(BigInteger.valueOf(block.getUncleList().size()))); BigInteger totalFees = BigInteger.ZERO; for (<API key> summary : summaries) { totalFees = totalFees.add(summary.getFee()); } rewards.put(block.getCoinbase(), minerReward.add(totalFees)); track.addBalance(block.getCoinbase(), minerReward); // fees are already given to the miner during tx execution return rewards; } @Override public synchronized void storeBlock(Block block, List<TransactionReceipt> receipts) { if (fork) blockStore.saveBlock(block, totalDifficulty, false); else blockStore.saveBlock(block, totalDifficulty, true); for (int i = 0; i < receipts.size(); i++) { transactionStore.put(new TransactionInfo(receipts.get(i), block.getHash(), i)); } if (pruneManager != null) { pruneManager.blockCommitted(block.getHeader()); } logger.debug("Block saved: number: {}, hash: {}, TD: {}", block.getNumber(), block.getShortHash(), totalDifficulty); setBestBlock(block); if (logger.isDebugEnabled()) logger.debug("block added to the blockChain: index: [{}]", block.getNumber()); if (block.getNumber() % 100 == 0) logger.info("*** Last block added [ #{} ]", block.getNumber()); } public boolean hasParentOnTheChain(Block block) { return getParent(block.getHeader()) != null; } @Override public List<Chain> getAltChains() { return altChains; } @Override public List<Block> getGarbage() { return garbage; } public TransactionStore getTransactionStore() { return transactionStore; } @Override public void setBestBlock(Block block) { bestBlock = block; repository = repository.getSnapshotTo(block.getStateRoot()); } @Override public synchronized Block getBestBlock() { // the method is synchronized since the bestBlock might be // temporarily switched to the fork while importing non-best block return bestBlock; } @Override public synchronized void close() { blockStore.close(); } @Override public BigInteger getTotalDifficulty() { return totalDifficulty; } @Override public synchronized void <API key>(Block block) { totalDifficulty = totalDifficulty.add(block.getDifficultyBI()); logger.debug("TD: updated to {}", totalDifficulty); } @Override public void setTotalDifficulty(BigInteger totalDifficulty) { this.totalDifficulty = totalDifficulty; } private void recordBlock(Block block) { if (!config.recordBlocks()) return; String dumpDir = config.databaseDir() + "/" + config.dumpDir(); File dumpFile = new File(dumpDir + "/blocks-rec.dmp"); FileWriter fw = null; BufferedWriter bw = null; try { dumpFile.getParentFile().mkdirs(); if (!dumpFile.exists()) dumpFile.createNewFile(); fw = new FileWriter(dumpFile.getAbsoluteFile(), true); bw = new BufferedWriter(fw); if (bestBlock.isGenesis()) { bw.write(Hex.toHexString(bestBlock.getEncoded())); bw.write("\n"); } bw.write(Hex.toHexString(block.getEncoded())); bw.write("\n"); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException e) { e.printStackTrace(); } } } public void <API key>(int startFrom) { // no synchronization here not to lock instance for long period while(true) { synchronized (this) { ((IndexedBlockStore) blockStore).<API key>(startFrom); if (startFrom == bestBlock.getNumber()) { totalDifficulty = blockStore.<API key>(bestBlock.getHash()); break; } startFrom++; } } } public void setRepository(Repository repository) { this.repository = repository; } public void <API key>(<API key> factory) { this.<API key> = factory; } public void setExitOn(long exitOn) { this.exitOn = exitOn; } public void setMinerCoinbase(byte[] minerCoinbase) { this.minerCoinbase = minerCoinbase; } @Override public byte[] getMinerCoinbase() { return minerCoinbase; } public void setMinerExtraData(byte[] minerExtraData) { this.minerExtraData = minerExtraData; } public boolean isBlockExist(byte[] hash) { return blockStore.isBlockExist(hash); } public void <API key>(<API key> <API key>) { this.<API key> = <API key>; } public void setPendingState(PendingState pendingState) { this.pendingState = pendingState; } public PendingState getPendingState() { return pendingState; } /** * Returns up to limit headers found with following search parameters * [Synchronized only in blockstore, not using any synchronized BlockchainImpl methods] * @param identifier Identifier of start block, by number of by hash * @param skip Number of blocks to skip between consecutive headers * @param limit Maximum number of headers in return * @param reverse Is search reverse or not * @return {@link BlockHeader}'s list or empty list if none found */ @Override public List<BlockHeader> <API key>(BlockIdentifier identifier, int skip, int limit, boolean reverse) { // Identifying block we'll move from Block startBlock; if (identifier.getHash() != null) { startBlock = blockStore.getBlockByHash(identifier.getHash()); } else { startBlock = blockStore.<API key>(identifier.getNumber()); } // If nothing found or provided hash is not on main chain, return empty array if (startBlock == null) { return emptyList(); } if (identifier.getHash() != null) { Block mainChainBlock = blockStore.<API key>(startBlock.getNumber()); if (!startBlock.equals(mainChainBlock)) return emptyList(); } List<BlockHeader> headers; if (skip == 0) { long bestNumber = blockStore.getBestBlock().getNumber(); headers = <API key>(bestNumber, startBlock.getNumber(), limit, reverse); } else { headers = getGapedHeaders(startBlock, skip, limit, reverse); } return headers; } /** * Finds up to limit blocks starting from blockNumber on main chain * @param bestNumber Number of best block * @param blockNumber Number of block to start search (included in return) * @param limit Maximum number of headers in response * @param reverse Order of search * @return headers found by query or empty list if none */ private List<BlockHeader> <API key>(long bestNumber, long blockNumber, int limit, boolean reverse) { int qty = getQty(blockNumber, bestNumber, limit, reverse); byte[] startHash = getStartHash(blockNumber, qty, reverse); if (startHash == null) { return emptyList(); } List<BlockHeader> headers = blockStore.<API key>(startHash, qty); // blocks come with falling numbers if (!reverse) { Collections.reverse(headers); } return headers; } /** * Gets blocks from main chain with gaps between * @param startBlock Block to start from (included in return) * @param skip Number of blocks skipped between every header in return * @param limit Maximum number of headers in return * @param reverse Order of search * @return headers found by query or empty list if none */ private List<BlockHeader> getGapedHeaders(Block startBlock, int skip, int limit, boolean reverse) { List<BlockHeader> headers = new ArrayList<>(); headers.add(startBlock.getHeader()); int offset = skip + 1; if (reverse) offset = -offset; long currentNumber = startBlock.getNumber(); boolean finished = false; while(!finished && headers.size() < limit) { currentNumber += offset; Block nextBlock = blockStore.<API key>(currentNumber); if (nextBlock == null) { finished = true; } else { headers.add(nextBlock.getHeader()); } } return headers; } private int getQty(long blockNumber, long bestNumber, int limit, boolean reverse) { if (reverse) { return blockNumber - limit + 1 < 0 ? (int) (blockNumber + 1) : limit; } else { if (blockNumber + limit - 1 > bestNumber) { return (int) (bestNumber - blockNumber + 1); } else { return limit; } } } private byte[] getStartHash(long blockNumber, int qty, boolean reverse) { long startNumber; if (reverse) { startNumber = blockNumber; } else { startNumber = blockNumber + qty - 1; } Block block = blockStore.<API key>(startNumber); if (block == null) { return null; } return block.getHash(); } /** * Returns list of block bodies by block hashes, stopping on first not found block * [Synchronized only in blockstore, not using any synchronized BlockchainImpl methods] * @param hashes List of hashes * @return List of RLP encoded block bodies */ @Override public List<byte[]> <API key>(List<byte[]> hashes) { List<byte[]> bodies = new ArrayList<>(hashes.size()); for (byte[] hash : hashes) { Block block = blockStore.getBlockByHash(hash); if (block == null) break; bodies.add(block.getEncodedBody()); } return bodies; } private class State { // Repository savedRepo = repository; byte[] root = repository.getRoot(); Block savedBest = bestBlock; BigInteger savedTD = totalDifficulty; } public void setPruneManager(PruneManager pruneManager) { this.pruneManager = pruneManager; } }
package org.cytoscape.FileWatcher.internal; import org.cytoscape.task.<API key>; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.work.TaskFactory; import org.cytoscape.work.TaskIterator; public class FileWatcherFactory implements <API key> { FileManager mgr; public FileWatcherFactory( FileManager mgr) { this.mgr = mgr; } @Override public TaskIterator createTaskIterator(CyNetworkView arg0) { return new TaskIterator(new <API key>(mgr)); } @Override public boolean isReady(CyNetworkView arg0) { // TODO Auto-generated method stub return arg0 != null && arg0.getModel() != null; } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApp1 { public static class ValidatorExtension { public static bool ValidateControl<T>(this Control container, T instance, ErrorProvider errorProvider) where T : class, new() { ICollection<ValidationResult> validationResults = null; return ValidateControl(container, instance, errorProvider, out validationResults); } public static bool ValidateControl<T>(this Control container, T instance, ErrorProvider errorProvider, out ICollection<ValidationResult> validationResults) where T : class, new() { var innerControls = new Dictionary<string, Control>(); container.GetAllInnerControls<T>(ref innerControls); errorProvider.Clear(); var validationContext = new ValidationContext(instance, null, null); validationResults = new List<ValidationResult>(); var isValid = Validator.TryValidateObject(instance, validationContext, validationResults, true); if (isValid) { return isValid; } foreach (var validationResult in validationResults) { foreach (var member in validationResult.MemberNames) { if (!innerControls.ContainsKey(member)) { continue; } var control = innerControls[member]; errorProvider.SetError(control, validationResult.ErrorMessage); } } return isValid; } private static void <API key><T>(Control innerControl, ref Dictionary<string, Control> existControls) { var underLine = '_'; var propertyInfos = typeof(T).GetProperties(); var columnName = innerControl.Name.Split(underLine)[0]; var findProperty = propertyInfos.FirstOrDefault(p => p.Name == columnName); var hasProperty = findProperty != null; var isMatch = hasProperty && columnName == findProperty.Name; if (!isMatch) { return; } if (!existControls.ContainsKey(columnName)) { existControls.Add(columnName, innerControl); } } private static void GetAllInnerControls<T>(this Control container, ref Dictionary<string, Control> existControls) { foreach (var innerControl in container.Controls.Cast<Control>()) { if (innerControl.Controls.Count > 0) { GetAllInnerControls<T>(innerControl, ref existControls); } <API key><T>(innerControl, ref existControls); } } } }
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*- #include "DataElement.hpp" #include <kdm/code/ComputationalObject.hpp> #include <kdm/kdm/Attribute.hpp> #include <kdm/kdm/Annotation.hpp> #include <kdm/kdm/Stereotype.hpp> #include <kdm/kdm/ExtendedValue.hpp> #include <kdm/source/SourceRef.hpp> #include <kdm/code/CommentUnit.hpp> #include <kdm/code/<API key>.hpp> #include <kdm/code/Datatype.hpp> #include <kdm/core/KDMRelationship.hpp> #include <kdm/core/<API key>.hpp> #include <kdm/core/KDMEntity.hpp> #include <kdm/kdm/KDMModel.hpp> #include <ecore/EObject.hpp> #include <ecore/EClass.hpp> #include "kdm/code/CodePackage.hpp" #include <ecorecpp/mapping.hpp> #ifdef <API key> #include <ecorecpp/notify.hpp> #endif /*PROTECTED REGION ID(DataElement.cpp) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ using namespace ::kdm::code; // Default constructor DataElement::DataElement() : m_type(0) { m_codeElement.reset( new ::ecorecpp::mapping::ReferenceEListImpl< ::kdm::code::Datatype_ptr, -1, true, false >(this, ::kdm::code::CodePackage::_instance()-><API key>())); /*PROTECTED REGION ID(<API key>) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ #ifdef <API key> m_eDeliver = false; #endif } DataElement::~DataElement() { } // Attributes ::kdm::core::String DataElement::getExt() const { return m_ext; } void DataElement::setExt(::kdm::core::String _ext) { #ifdef <API key> ::kdm::core::String _old_ext = m_ext; #endif m_ext = _ext; #ifdef <API key> if (<API key>()) { ::ecorecpp::notify::Notification notification( ::ecorecpp::notify::Notification::SET, _this(), ::kdm::code::CodePackage::_instance()->getDataElement__ext(), _old_ext, m_ext ); eNotify(&notification); } #endif } ::kdm::core::Integer DataElement::getSize() const { return m_size; } void DataElement::setSize(::kdm::core::Integer _size) { #ifdef <API key> ::kdm::core::Integer _old_size = m_size; #endif m_size = _size; #ifdef <API key> if (<API key>()) { ::ecorecpp::notify::Notification notification( ::ecorecpp::notify::Notification::SET, _this(), ::kdm::code::CodePackage::_instance()-><API key>(), _old_size, m_size ); eNotify(&notification); } #endif } // References ::kdm::code::Datatype_ptr DataElement::getType() const { return m_type; } void DataElement::setType(::kdm::code::Datatype_ptr _type) { #ifdef <API key> ::kdm::code::Datatype_ptr _old_type = m_type; #endif m_type = _type; #ifdef <API key> if (<API key>()) { ::ecorecpp::notify::Notification notification( ::ecorecpp::notify::Notification::SET, _this(), ::kdm::code::CodePackage::_instance()-><API key>(), _old_type, m_type ); eNotify(&notification); } #endif } const ::ecorecpp::mapping::EList< ::kdm::code::Datatype_ptr >& DataElement::getCodeElement() const { return *m_codeElement; } ::ecorecpp::mapping::EList< ::kdm::code::Datatype_ptr >& DataElement::getCodeElement() { return *m_codeElement; }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Catharsis.Commons: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Catharsis.Commons &#160;<span id="projectnumber">4.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('functions_i.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a id="index_i"></a>- i -</h3><ul> <li>Implements() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.ObjectExtensions</a> </li> <li>Implements&lt; T &gt;() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.ObjectExtensions</a> </li> <li>Inherits() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.ObjectExtensions</a> </li> <li>Int16() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.ConvertExtensions</a> </li> <li>Int32() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.ConvertExtensions</a> </li> <li>Int64() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.ConvertExtensions</a> </li> <li>Is&lt; T &gt;() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.ObjectExtensions</a> </li> <li>IsAssignableTo&lt; T &gt;() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.<API key></a> </li> <li>IsBoolean() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> <li>IsDateTime() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> <li>IsDouble() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> <li>IsEmpty() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> <li>IsGuid() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> <li>IsInteger() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> <li>IsMatch() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> <li>ISO8601() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.DateExtensions</a> </li> <li>IsProtected() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.<API key></a> </li> <li>IsPublic() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.<API key></a> </li> <li>IsSameDate() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.DateExtensions</a> </li> <li>IsSameTime() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.DateExtensions</a> </li> <li>IsUri() : <a class="el" href="<API key>.html#<API key>">Catharsis.Commons.StringExtensions</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Fri Dec 21 2018 12:03:33 for Catharsis.Commons by <a href="http: <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.14 </li> </ul> </div> </body> </html>
package fi.dy.masa.minihud.gui.widget; import com.google.common.collect.ImmutableList; import fi.dy.masa.malilib.gui.config.ConfigWidgetContext; import fi.dy.masa.malilib.gui.widget.<API key>; import fi.dy.masa.malilib.gui.widget.<API key>; import fi.dy.masa.malilib.gui.widget.button.BooleanConfigButton; import fi.dy.masa.malilib.gui.widget.button.KeyBindConfigButton; import fi.dy.masa.malilib.gui.widget.list.entry.config.BaseConfigWidget; import fi.dy.masa.minihud.config.StructureToggle; public class <API key> extends BaseConfigWidget<StructureToggle> { protected final StructureToggle config; protected final ImmutableList<Integer> initialHotkeyValue; protected final BooleanConfigButton booleanButton; protected final KeyBindConfigButton hotkeyButton; protected final <API key> settingsWidget; protected final <API key> <API key>; protected final <API key> <API key>; protected final boolean initialBooleanValue; protected final int initialMainColor; protected final int <API key>; public <API key>(int x, int y, int width, int height, int listIndex, int originalListIndex, StructureToggle config, ConfigWidgetContext ctx) { super(x, y, width, 22, listIndex, originalListIndex, config, ctx); this.config = config; this.initialBooleanValue = config.isEnabled(); this.initialMainColor = config.getColorMain().getIntegerValue(); this.<API key> = config.getColorComponents().getIntegerValue(); this.initialHotkeyValue = config.getKeyBind().getKeys(); this.booleanButton = new BooleanConfigButton(-1, 20, config.getBooleanConfig()); this.booleanButton.setActionListener(() -> { this.config.getBooleanConfig().toggleBooleanValue(); this.updateButtonStates(); }); this.hotkeyButton = new KeyBindConfigButton(120, 20, config.getKeyBind(), ctx.<API key>()); this.hotkeyButton.<API key>(this::updateButtonStates); this.settingsWidget = new <API key>(config.getKeyBind(), config.getDisplayName()); this.<API key> = new <API key>(18, 18, this.config.getColorMain(), (newValue) -> { this.config.getColorMain().setValue(newValue); this.updateButtonStates(); }); this.<API key>.getHoverInfoFactory().<API key>(90, "minihud.hover.structures.color_main"); this.<API key> = new <API key>(18, 18, this.config.getColorComponents(), (newValue) -> { this.config.getColorComponents().setValue(newValue); this.updateButtonStates(); }); this.<API key>.getHoverInfoFactory().<API key>(90, "minihud.hover.structures.color_components"); this.resetButton.setActionListener(() -> { this.config.resetToDefault(); this.updateButtonStates(); }); } @Override public void reAddSubWidgets() { super.reAddSubWidgets(); this.addWidget(this.booleanButton); this.addWidget(this.hotkeyButton); this.addWidget(this.settingsWidget); this.addWidget(this.<API key>); this.addWidget(this.<API key>); this.addWidget(this.resetButton); } @Override public void <API key>() { super.<API key>(); int x = this.<API key>(); int y = this.getY() + 1; int w = this.getElementWidth() - this.booleanButton.getWidth() - 66; this.hotkeyButton.setWidth(w); this.booleanButton.setPosition(x, y); this.hotkeyButton.setPosition(this.booleanButton.getRight() + 2, y); this.settingsWidget.setPosition(this.hotkeyButton.getRight() + 2, y); this.<API key>.setPosition(this.settingsWidget.getRight() + 3, y + 1); this.<API key>.setPosition(this.<API key>.getRight() + 3, y + 1); this.updateResetButton(this.<API key>.getRight() + 4, y); this.updateButtonStates(); } @Override public boolean wasModified() { return this.config.isEnabled() != this.initialBooleanValue || this.config.getColorMain().getIntegerValue() != this.initialMainColor || this.config.getColorComponents().getIntegerValue() != this.<API key> || this.config.getKeyBind().getKeys().equals(this.initialHotkeyValue) == false; } protected void updateButtonStates() { this.booleanButton.setEnabled(this.config.getBooleanConfig().isLocked() == false); this.booleanButton.updateButtonState(); this.booleanButton.updateHoverStrings(); this.hotkeyButton.updateButtonState(); this.hotkeyButton.updateHoverStrings(); this.resetButton.setEnabled(this.config.isModified() && this.config.getBooleanConfig().isLocked() == false); } }
{# Display edit-workspace #} {% load i18n workspaces %} <div id="edit-workspace" class="sidebarbox workspace" data-workspace-id="{{ workspace_edit.id }}" <API key>="{% url <API key> %}" <API key>="{% url <API key> %}" <API key>="{% url <API key> %}" <API key>="{% url <API key> %}" <API key>="{% url lizard_map.search_coordinates %}" <API key>="{% url lizard_map.search_name %}" <API key>="{% url lizard_map_collage %}" <API key>="{% url <API key> %}" > {% comment %} <h2> <span title="{% trans 'This is your workspace. Hover your mouse over the containing items to see options.' %}"> {% trans 'Layers' %} </span> </h2> {% endcomment %} <ul class="workspace-items unstyled"> {% for workspace_item in workspace_edit.workspace_items.all %} <li id="workspace-item-{{ workspace_item.id }}" class="workspace-item" data-object-id="{{ workspace_item.id }}" data-adapter-class="{{ workspace_item.adapter_class }}" <API key>='{{ workspace_item.adapter_layer_json }}' data-visible="{{ workspace_item.visible }}"> <div> {# Symbol, appears left. #} {% if workspace_item.adapter.symbol_url %} {% comment %} <img class="<API key>" src="{{ workspace_item.adapter.symbol_url }}" width="16" height="16" /> {% endcomment %} {% else %} {% endif %} <span class="<API key>" title="{% trans 'Click to toggle visibility' %}"> <i class="icon-check"></i><i class="icon-check-empty"></i> {% firstof workspace_item.name '(noname)' %} </span> </div> {% comment %} <div style="height:28px;"> <div class="btn-group pull-right"> {% if workspace_item.has_extent %} <button class="btn btn-small btn-info <API key>" title="{% trans 'Zoom to extent' %}"> <i class="icon-search"></i> </button> {% endif %} <button class="btn btn-small <API key>" title="{% trans 'Move up' %}"> <i class="icon-arrow-up"></i> </button> <button class="btn btn-small <API key>" title="{% trans 'Move down' %}"> <i class="icon-arrow-down"></i> </button> <button class="btn btn-small btn-danger <API key>" title="{% trans 'Delete item' %}"> <i class="icon-trash icon-white"></i> </button> </div> </div> {% endcomment %} </li> {% empty %} {# No workspace items #} <li> {% trans 'No map layers selected.' %} </li> {% endfor %} </ul> {% comment %} <hr noshade style="border-color: #7FA9AE; color: #7FA9AE; background-color: #7FA9AE;" /> {% endcomment %} <div class="btn-group" style="display: block; width: 78px; margin-left: auto; margin-right: auto;"> <button id="workspace-empty" href="{% url <API key> %}" class="btn <API key> <API key>" title="{% trans 'Empty your workspace' %}"> <i class="icon-trash icon-white"></i> </button> <button id="workspace-save" href="{% url <API key> %}" class="btn <API key> <API key>" data-size="xs" title="{% trans 'Save your workspace' %}" {% if not workspace_edit.workspace_items.exists %} disabled="disabled" {% endif %}> <i class="icon-save"></i> </button> </div> {% comment %} The added value of next link might not be obvious to a user, because workspace-load seems to offer comparable functionality. A subtle difference is that it reveals a URL to a read-only workspace, which you can send around via email. {% endcomment %} {% comment %} <a id="<API key>" href="{% url <API key> %}" title="{% trans 'Stored workspaces...' %}" class="title ss_sprite ss_database <API key> ajax-dialog" data-size="xs">&nbsp;</a> {% endcomment %} {% comment %} <a id="workspace-load" href="{% url <API key> %}" title="{% trans 'Load workspace...' %}" class="title ss_sprite ss_database_go <API key> ajax-dialog" data-size="xs">&nbsp;</a> {% endcomment %} </ul> </div>
import {StaticContent} from "./StaticContent"; export class GlobalConfiguration { port: number; staticContent: Array<StaticContent>; }
<?php namespace Services; use \Illuminate\Support\Facades\Facade; /** * Facade class to be called whenever the class AddressService is called */ class GroupFacade extends Facade { /** * Get the registered name of the component. This tells $this->app what record to return * * @return string */ protected static function getFacadeAccessor() { return 'GroupService'; } }
# Sonar, entreprise quality control tool. # mailto:contact AT sonarsource DOT com # Sonar is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # Sonar is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # You should have received a copy of the GNU Lesser General Public # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 module Severity INFO = "INFO" MINOR = "MINOR" MAJOR = "MAJOR" CRITICAL = "CRITICAL" BLOCKER = "BLOCKER" KEYS=[BLOCKER, CRITICAL, MAJOR, MINOR, INFO] def self.valid?(value) KEYS.include?(value) end end
use <API key>::bench::bucketers::<API key>; use <API key>::bench::{run_benchmark, BenchmarkType}; use <API key>::generators::common::{GenConfig, GenMode}; use <API key>::generators::<API key>; use <API key>::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_demo!(runner, <API key>); register_bench!(runner, <API key>); } fn <API key>(gm: GenMode, config: GenConfig, limit: usize) { for xs in <API key>::<u8>() .get(gm, &config) .take(limit) { if xs.is_empty() { println!("{} is empty", xs); } else { println!("{} is not empty", xs); } } } fn <API key>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) { run_benchmark( "RationalSequence.is_empty()", BenchmarkType::Single, <API key>::<u8>().get(gm, &config), gm.name(), limit, file_name, &<API key>("xs"), &mut [("Malachite", &mut |xs| no_out!(xs.is_empty()))], ); }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using <API key> = Bosphorus.ServiceModel.Hosting.Model.Configuration.<API key>; namespace Bosphorus.ServiceModel.Hosting.Hosting.Core { public interface <API key> { ServiceHost Get(<API key> <API key>, params Uri[] baseAddresses); } }
package org.fuin.srcgen4j.core.xtext; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import javax.xml.bind.JAXBContext; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.xtext.linking.lazy.LazyLinkingResource; import org.fuin.srcgen4j.commons.DefaultContext; import org.fuin.srcgen4j.commons.ParserConfig; import org.fuin.srcgen4j.commons.SrcGen4JConfig; import org.fuin.srcgen4j.core.emf.EMFGeneratorConfig; import org.fuin.utils4j.classpath.Handler; import org.fuin.utils4j.jaxb.JaxbUtils; import org.fuin.utils4j.jaxb.UnmarshallerBuilder; import org.fuin.xsample.xSampleDsl.Greeting; import org.fuin.xsample.xSampleDsl.impl.GreetingImpl; import org.fuin.xsample.xSampleDsl.impl.ModelImpl; import org.junit.jupiter.api.Test; /** * Test for {@link XtextParser}. */ public class XtextParserTest { // CHECKSTYLE:OFF @Test public void testParse() throws Exception { Handler.add(); final DefaultContext context = new DefaultContext(); final File dir = new File("src/test/resources/domain"); final File file = new File(dir, "xtext-test-config.xml"); final JAXBContext jaxbContext = JAXBContext.newInstance(SrcGen4JConfig.class, XtextParserConfig.class, EMFGeneratorConfig.class); final SrcGen4JConfig srcGen4JConfig = JaxbUtils .unmarshal( new UnmarshallerBuilder() .withContext(jaxbContext).addClasspathSchemas("/<API key>.xsd", "/<API key>.xsd", "/<API key>.xsd", "/<API key>.xsd") .build(), file); srcGen4JConfig.init(context, new File(".")); final ParserConfig config = srcGen4JConfig.getParsers().getList().get(0); final XtextParser testee = new XtextParser(); testee.initialize(context, config); // TEST final ResourceSet resourceSet = testee.parse(); // VERIFY assertThat(resourceSet).isNotNull(); final TreeIterator<Notifier> it = resourceSet.getAllContents(); assertThat(it.next()).isInstanceOf(LazyLinkingResource.class); assertThat(it.next()).isInstanceOf(ModelImpl.class); final Notifier notifier = it.next(); assertThat(notifier).isInstanceOf(GreetingImpl.class); final Greeting greeting = (Greeting) notifier; assertThat(greeting.getName()).isEqualTo("World"); } // CHECKSTYLE:ON }
package com.silicolife.textmining.processes.ir.patentpipeline.components.metainfomodules.wipo; import com.silicolife.textmining.core.interfaces.core.configuration.IProxy; import com.silicolife.textmining.processes.ir.patentpipeline.core.metainfomodule.<API key>; public class <API key> extends <API key> implements <API key> { private String username; private String pwd; public <API key>(String username, String pwd,IProxy proxy) { super(proxy); this.username=username; this.pwd=pwd; } @Override public String getUserName() { return username; } @Override public String getPassword() { return pwd; } }
// Created file "tmp\src\dxguid\dxguid" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(CLSID_DP8SP_MODEM, 0x6d4a3650, 0x628d, 0x11d2, 0xae, 0x0f, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11);
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_22) on Wed Nov 09 19:32:53 IST 2011 --> <TITLE> <API key> </TITLE> <META NAME="date" CONTENT="2011-11-09"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="<API key>"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../microsoft/exchange/webservices/data/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html" title="class in microsoft.exchange.webservices.data"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html" title="class in microsoft.exchange.webservices.data"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?microsoft/exchange/webservices/data/<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> <FONT SIZE="-1"> microsoft.exchange.webservices.data</FONT> <BR> Class <API key></H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.lang.Throwable <IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.lang.Exception <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html" title="class in microsoft.exchange.webservices.data">microsoft.exchange.webservices.data.<API key></A> <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>microsoft.exchange.webservices.data.<API key></B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable</DD> </DL> <HR> <DL> <DT><PRE>public class <B><API key></B><DT>extends <A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html" title="class in microsoft.exchange.webservices.data"><API key></A></DL> </PRE> <P> Represents an exception that is thrown when the Autodiscover service returns an error. <P> <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../serialized-form.html#microsoft.exchange.webservices.data.<API key>">Serialized Form</A></DL> <HR> <P> <A NAME="constructor_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html#<API key>(microsoft.exchange.webservices.data.AutodiscoverError)"><API key></A></B>(<A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A>&nbsp;error)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Initializes a new instance of the class.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected </CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html#<API key>(java.lang.String, microsoft.exchange.webservices.data.AutodiscoverError)"><API key></A></B>(java.lang.String&nbsp;message, <A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A>&nbsp;error)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Initializes a new instance of the class.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html#<API key>(java.lang.String, microsoft.exchange.webservices.data.AutodiscoverError, java.lang.Exception)"><API key></A></B>(java.lang.String&nbsp;message, <A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A>&nbsp;error, java.lang.Exception&nbsp;innerException)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Initializes a new instance of the class.</TD> </TR> </TABLE> &nbsp; <A NAME="method_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html#getError()">getError</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the error.</TD> </TR> </TABLE> &nbsp;<A NAME="<API key>.lang.Throwable"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="<API key>"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Throwable</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="<API key>.lang.Object"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="<API key>"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <A NAME="constructor_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="<API key>(microsoft.exchange.webservices.data.AutodiscoverError)"></A><H3> <API key></H3> <PRE> public <B><API key></B>(<A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A>&nbsp;error)</PRE> <DL> <DD>Initializes a new instance of the class. <P> <DL> <DT><B>Parameters:</B><DD><CODE>error</CODE> - the error</DL> </DL> <HR> <A NAME="<API key>(java.lang.String, microsoft.exchange.webservices.data.AutodiscoverError)"></A><H3> <API key></H3> <PRE> protected <B><API key></B>(java.lang.String&nbsp;message, <A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A>&nbsp;error)</PRE> <DL> <DD>Initializes a new instance of the class. <P> <DL> <DT><B>Parameters:</B><DD><CODE>message</CODE> - the message<DD><CODE>error</CODE> - the error</DL> </DL> <HR> <A NAME="<API key>(java.lang.String, microsoft.exchange.webservices.data.AutodiscoverError, java.lang.Exception)"></A><H3> <API key></H3> <PRE> public <B><API key></B>(java.lang.String&nbsp;message, <A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A>&nbsp;error, java.lang.Exception&nbsp;innerException)</PRE> <DL> <DD>Initializes a new instance of the class. <P> <DL> <DT><B>Parameters:</B><DD><CODE>message</CODE> - the message<DD><CODE>error</CODE> - the error<DD><CODE>innerException</CODE> - the inner exception</DL> </DL> <A NAME="method_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getError()"></A><H3> getError</H3> <PRE> public <A HREF="../../../../microsoft/exchange/webservices/data/AutodiscoverError.html" title="class in microsoft.exchange.webservices.data">AutodiscoverError</A> <B>getError</B>()</PRE> <DL> <DD>Gets the error. <value>The error.</value> <P> <DD><DL> <DT><B>Returns:</B><DD>the error</DL> </DD> </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../microsoft/exchange/webservices/data/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html" title="class in microsoft.exchange.webservices.data"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../microsoft/exchange/webservices/data/<API key>.html" title="class in microsoft.exchange.webservices.data"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?microsoft/exchange/webservices/data/<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
package net.minecraft.entity; import java.util.Collection; import java.util.Iterator; import java.util.UUID; import net.minecraft.entity.ai.attributes.Attribute; import net.minecraft.entity.ai.attributes.AttributeInstance; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.BaseAttributeMap; import net.minecraft.entity.ai.attributes.RangedAttribute; import net.minecraft.logging.ILogAgent; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; public class <API key> { public static final Attribute field_111267_a = (new RangedAttribute("generic.maxHealth", 20.0D, 0.0D, Double.MAX_VALUE)).func_111117_a("Max Health").func_111112_a(true); public static final Attribute field_111265_b = (new RangedAttribute("generic.followRange", 32.0D, 0.0D, 2048.0D)).func_111117_a("Follow Range"); public static final Attribute field_111266_c = (new RangedAttribute("generic.knockbackResistance", 0.0D, 0.0D, 1.0D)).func_111117_a("Knockback Resistance"); public static final Attribute field_111263_d = (new RangedAttribute("generic.movementSpeed", 0.699999988079071D, 0.0D, Double.MAX_VALUE)).func_111117_a("Movement Speed").func_111112_a(true); public static final Attribute field_111264_e = new RangedAttribute("generic.attackDamage", 2.0D, 0.0D, Double.MAX_VALUE); public static NBTTagList func_111257_a(BaseAttributeMap p_111257_0_) { NBTTagList var1 = new NBTTagList(); Iterator var2 = p_111257_0_.func_111146_a().iterator(); while(var2.hasNext()) { AttributeInstance var3 = (AttributeInstance)var2.next(); var1.func_74742_a(func_111261_a(var3)); } return var1; } private static NBTTagCompound func_111261_a(AttributeInstance p_111261_0_) { NBTTagCompound var1 = new NBTTagCompound(); Attribute var2 = p_111261_0_.func_111123_a(); var1.func_74778_a("Name", var2.func_111108_a()); var1.func_74780_a("Base", p_111261_0_.func_111125_b()); Collection var3 = p_111261_0_.func_111122_c(); if(var3 != null && !var3.isEmpty()) { NBTTagList var4 = new NBTTagList(); Iterator var5 = var3.iterator(); while(var5.hasNext()) { AttributeModifier var6 = (AttributeModifier)var5.next(); if(var6.func_111165_e()) { var4.func_74742_a(func_111262_a(var6)); } } var1.func_74782_a("Modifiers", var4); } return var1; } private static NBTTagCompound func_111262_a(AttributeModifier p_111262_0_) { NBTTagCompound var1 = new NBTTagCompound(); var1.func_74778_a("Name", p_111262_0_.func_111166_b()); var1.func_74780_a("Amount", p_111262_0_.func_111164_d()); var1.func_74768_a("Operation", p_111262_0_.func_111169_c()); var1.func_74772_a("UUIDMost", p_111262_0_.func_111167_a().<API key>()); var1.func_74772_a("UUIDLeast", p_111262_0_.func_111167_a().<API key>()); return var1; } public static void func_111260_a(BaseAttributeMap p_111260_0_, NBTTagList p_111260_1_, ILogAgent p_111260_2_) { for(int var3 = 0; var3 < p_111260_1_.func_74745_c(); ++var3) { NBTTagCompound var4 = (NBTTagCompound)p_111260_1_.func_74743_b(var3); AttributeInstance var5 = p_111260_0_.func_111152_a(var4.func_74779_i("Name")); if(var5 != null) { func_111258_a(var5, var4); } else if(p_111260_2_ != null) { p_111260_2_.func_98236_b("Ignoring unknown attribute \'" + var4.func_74779_i("Name") + "\'"); } } } private static void func_111258_a(AttributeInstance p_111258_0_, NBTTagCompound p_111258_1_) { p_111258_0_.func_111128_a(p_111258_1_.func_74769_h("Base")); if(p_111258_1_.func_74764_b("Modifiers")) { NBTTagList var2 = p_111258_1_.func_74761_m("Modifiers"); for(int var3 = 0; var3 < var2.func_74745_c(); ++var3) { AttributeModifier var4 = func_111259_a((NBTTagCompound)var2.func_74743_b(var3)); AttributeModifier var5 = p_111258_0_.func_111127_a(var4.func_111167_a()); if(var5 != null) { p_111258_0_.func_111124_b(var5); } p_111258_0_.func_111121_a(var4); } } } public static AttributeModifier func_111259_a(NBTTagCompound p_111259_0_) { UUID var1 = new UUID(p_111259_0_.func_74763_f("UUIDMost"), p_111259_0_.func_74763_f("UUIDLeast")); return new AttributeModifier(var1, p_111259_0_.func_74779_i("Name"), p_111259_0_.func_74769_h("Amount"), p_111259_0_.func_74762_e("Operation")); } }
package com.exter.eveindcalc.materials; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import com.exter.controls.BigDecimalEditText; import com.exter.eveindcalc.EICApplication; import com.exter.eveindcalc.R; import com.exter.eveindcalc.<API key>; import com.exter.eveindcalc.TaskHelper; import com.exter.eveindcalc.data.EveDatabase; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import exter.eveindustry.market.Market; public class <API key> extends DialogFragment { private class <API key> implements Spinner.<API key> { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { int i = system_ids.get(pos); if(i == -1 ) { <API key> dialog = new <API key>(); dialog.show(getActivity().<API key>(), "<API key>"); } else { market = new Market(i, market.order, market.manual, market.broker, market.transaction); } } @Override public void onNothingSelected(AdapterView<?> parent) { } } private class PriceChangeWatcher implements BigDecimalEditText.ValueListener { @Override public void valueChanged(int tag, BigDecimal new_value) { market = new Market(market.system, market.order,new_value, market.broker, market.transaction); } } private class BrokerChangeWatcher implements BigDecimalEditText.ValueListener { @Override public void valueChanged(int tag, BigDecimal new_value) { market = new Market(market.system, market.order, market.manual,new_value, market.transaction); } } private class TaxChangeWatcher implements BigDecimalEditText.ValueListener { @Override public void valueChanged(int tag, BigDecimal new_value) { market = new Market(market.system, market.order, market.manual, market.broker,new_value); } } private <API key> accept_listener; private Spinner sp_system; private BigDecimalEditText ed_broker; private BigDecimalEditText ed_tax; private BigDecimalEditText ed_manual; private Market market; private List<Integer> system_ids; static final int TYPE_ITEM = 0; static final int TYPE_PRODUCED = 1; static final int TYPE_REQUIRED = 2; private int type; private int item; private EICApplication application; private EveDatabase provider; private class <API key> implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { if(accept_listener != null) { switch(type) { case TYPE_ITEM: accept_listener.onAcceptItem(item, market); break; case TYPE_PRODUCED: accept_listener.onAcceptProduced(market); break; case TYPE_REQUIRED: accept_listener.onAcceptRequired(market); break; } } } } private class SellClickListener implements RadioButton.OnClickListener { @Override public void onClick(View v) { market = new Market(market.system,Market.Order.SELL, market.manual, market.broker, market.transaction); enableBuySell(); } } private class BuyClickListener implements RadioButton.OnClickListener { @Override public void onClick(View v) { market = new Market(market.system,Market.Order.BUY, market.manual, market.broker, market.transaction); enableBuySell(); } } private class ManualClickListener implements RadioButton.OnClickListener { @Override public void onClick(View v) { market = new Market(market.system,Market.Order.MANUAL, market.manual, market.broker, market.transaction); enableManual(); } } private void enableBuySell() { sp_system.setEnabled(true); ed_broker.setEnabled(true); ed_tax.setEnabled(true); ed_manual.setEnabled(false); } private void enableManual() { sp_system.setEnabled(false); ed_broker.setEnabled(false); ed_tax.setEnabled(false); ed_manual.setEnabled(true); } public interface <API key> { void onAcceptItem(int item, Market price); void onAcceptRequired(Market price); void onAcceptProduced(Market price); } @NonNull @SuppressLint("InflateParams") @Override public Dialog onCreateDialog(Bundle savedInstanceState) { application = (EICApplication)getActivity().getApplication(); provider = application.database; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.market_fetch, null); builder.setView(view); builder.setPositiveButton("Set", new <API key>()); builder.setNegativeButton("Cancel", null); Bundle args = getArguments(); sp_system = (Spinner) view.findViewById(R.id.sp_fetch_system); RadioGroup rg_source = (RadioGroup) view.findViewById(R.id.rg_fetch_source); RadioButton rb_sell = (RadioButton) view.findViewById(R.id.rb_fetch_sell); RadioButton rb_buy = (RadioButton) view.findViewById(R.id.rb_fetch_buy); RadioButton rb_manual = (RadioButton) view.findViewById(R.id.rb_fetch_manual); ed_manual = new BigDecimalEditText((EditText) view.findViewById(R.id.ed_fetch_manual), -1, BigDecimal.ZERO, new BigDecimal("1000000000000"), BigDecimal.ZERO, new PriceChangeWatcher()); ed_broker = new BigDecimalEditText((EditText) view.findViewById(R.id.ed_fetch_broker), -1, BigDecimal.ZERO, new BigDecimal("100"), BigDecimal.ZERO, new BrokerChangeWatcher()); ed_tax = new BigDecimalEditText((EditText) view.findViewById(R.id.ed_fetch_tax), -1, BigDecimal.ZERO, new BigDecimal("100"), BigDecimal.ZERO, new TaxChangeWatcher()); LinearLayout ly_manual = (LinearLayout) view.findViewById(R.id.ly_fetch_manual); market = TaskHelper.priceFromBundle(args); type = args.getInt("type"); if(type == TYPE_ITEM) { item = args.getInt("item"); } else { item = -1; ly_manual.setVisibility(View.GONE); if(market.order == Market.Order.MANUAL) { market = new Market(market.system,Market.Order.SELL,BigDecimal.ZERO, market.broker, market.transaction); } } ed_manual.setValue(market.manual); ed_broker.setValue(market.broker); ed_tax.setValue(market.transaction); switch(market.order) { case SELL: rg_source.check(R.id.rb_fetch_sell); enableBuySell(); break; case BUY: rg_source.check(R.id.rb_fetch_buy); enableBuySell(); break; case MANUAL: rg_source.check(R.id.rb_fetch_manual); enableManual(); break; } rb_sell.setOnClickListener(new SellClickListener()); rb_buy.setOnClickListener(new BuyClickListener()); rb_manual.setOnClickListener(new ManualClickListener()); provider.da_recentsystems.putSystem(market.system); updateSystem(); return builder.create(); } public void setSystem(int id) { market = new Market(id, market.order, market.manual, market.broker, market.transaction); updateSystem(); } private void updateSystem() { sp_system.<API key>(null); provider.da_recentsystems.putSystem(market.system); system_ids = new ArrayList<>(); List<String> system_names = new ArrayList<>(); for(int id:provider.da_recentsystems.getSystems()) { system_ids.add(id); system_names.add(application.factory.solarsystems.get(id).name); } system_ids.add(-1); system_names.add("[ Other ... ]"); ArrayAdapter<String> sys_spinner_adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, system_names); sys_spinner_adapter.<API key>(android.R.layout.<API key>); sp_system.setAdapter(sys_spinner_adapter); sp_system.setSelection(system_ids.indexOf(market.system)); sp_system.<API key>(new <API key>()); } void setOnAcceptListener(<API key> listener) { accept_listener = listener; } }
//<version>V0.5</verion> //<createdate>2012-10-08</createdate> //<author>libsh</author> //<email>libsh@tunynet.com</email> //<log date="2012-10-08" version="0.5"></log> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Spacebuilder.Common; using Tunynet; using Tunynet.Common; using Tunynet.Common.Configuration; using Tunynet.UI; using System.Text.RegularExpressions; namespace Spacebuilder.Microblog { <summary> </summary> [ManageAuthorize(CheckCookie = false)] [TitleFilter(IsAppendSiteName = true, TitlePart = "")] [Themed(<API key>.ControlPanel, IsApplication = true)] public class <API key> : Controller { private string tenantTypeId = TenantTypeIds.Instance().Microblog(); #region Service public <API key> pageResourceManager { get; set; } public MicroblogService microblogService { get; set; } private TagService tagService = new TagService(TenantTypeIds.Instance().Microblog()); #endregion #region #region <summary> </summary> <param name="microblogIds">ID</param> <param name="isApproved"></param> <returns></returns> [HttpPost] public JsonResult <API key>(string microblogIds, bool isApproved) { if (!string.IsNullOrEmpty(microblogIds)) { IEnumerable<long> updatecategoryIds = microblogIds.TrimEnd(',').Split(',').Select(t => Convert.ToInt64(t)); foreach (var microblogId in updatecategoryIds) { microblogService.UpdateAuditStatus(microblogId, isApproved); } return Json(new StatusMessageData(StatusMessageType.Success, "")); } else { return Json(new StatusMessageData(StatusMessageType.Error, "")); } } <summary> </summary> <param name="microblogIds">ID</param> <returns></returns> [HttpPost] public JsonResult DeleteMicroblogs(string microblogIds) { if (string.IsNullOrEmpty(microblogIds)) { return Json(new StatusMessageData(StatusMessageType.Error, "")); } var ids = microblogIds.TrimEnd(',').Split(','); foreach (var microblogId in ids) { microblogService.Delete(long.Parse(microblogId)); } return Json(new StatusMessageData(StatusMessageType.Success, "")); } #endregion #region <summary> </summary> <returns></returns> [HttpGet] public ActionResult ManageMicroblogs(int pageIndex = 1, string userId = null, string keyword = null, MediaType? mediaType = null, AuditStatus? auditStatus = null, DateTime? startdate = null, DateTime? enddate = null, int pageSize = 20, string tenantTypeId = null, long? ownerId = null) { pageResourceManager.InsertTitlePart(""); #region MicroblogQuery query = new MicroblogQuery(); long? id = null; if (!string.IsNullOrEmpty(userId)) { userId = userId.TrimStart(',').TrimEnd(','); if (!string.IsNullOrEmpty(userId)) { id = long.Parse(userId); } } query.OwnerId = ownerId; query.Keyword = keyword; query.UserId = id; query.MediaType = mediaType; query.AuditStatus = auditStatus; query.TenantTypeId = tenantTypeId; if (startdate != DateTime.MinValue) query.StartDate = startdate; if (enddate != DateTime.MinValue && enddate.HasValue) query.EndDate = enddate.Value.AddDays(1); #endregion ViewData["userId"] = id; PagingDataSet<MicroblogEntity> microblogs = microblogService.GetMicroblogs(query, pageSize, pageIndex); if (tenantTypeId == null) { tenantTypeId = TenantTypeIds.Instance().User(); } ViewData["tenantTypeId"] = tenantTypeId; return View(microblogs); } #endregion #endregion #region #region <summary> / </summary> <returns></returns> [HttpGet] public ActionResult EditTopic(long topicId = 0) { TagEditModel tagEditModel = null; if (topicId == 0) { tagEditModel = new TagEditModel(); SelectList topicGroups = <API key>(0, TenantTypeIds.Instance().Microblog()); ViewData["topicGroups"] = topicGroups; ViewData["editTopicTitle"] = ""; pageResourceManager.InsertTitlePart(""); } else { Tag tag = tagService.Get(topicId); tagEditModel = tag.AsTagEditModel(); SelectList topicGroups = <API key>(tagEditModel.TopicGroupId, tagEditModel.TenantTypeId); ViewData["topicGroups"] = topicGroups; string users = tagEditModel.RelatedObjectIds.TrimStart(',').TrimEnd(','); if (!string.IsNullOrEmpty(users)) { IEnumerable<long> seletedUserIds = tagEditModel.RelatedObjectIds.TrimStart(',').TrimEnd(',').Split(',').Select(t => Convert.ToInt64(t)); ViewData["seletedUserIds"] = seletedUserIds; } ViewData["editTopicTitle"] = ""; pageResourceManager.InsertTitlePart(""); } return View(tagEditModel); } <summary> / </summary> <returns></returns> [HttpPost] public ActionResult EditTopic(TagEditModel tagEditModel) { System.IO.Stream stream = null; bool isCreate = tagEditModel.TagId == 0; if (isCreate) { ViewData["editTopicTitle"] = ""; } else { ViewData["editTopicTitle"] = ""; } TagService tagService = new TagService(tagEditModel.TenantTypeId); IEnumerable<long> userIds = Request.Form.Gets<long>("RelatedObjectIds"); if (tagEditModel.IsFeatured) { HttpPostedFileBase tagLogo = Request.Files["tagLogo"]; string fileName = tagLogo == null ? "" : tagLogo.FileName; if (string.IsNullOrEmpty(fileName) && string.IsNullOrEmpty(tagEditModel.FeaturedImage)) { SelectList topicGroups = <API key>(tagEditModel.TopicGroupId, tagEditModel.TenantTypeId); ViewData["topicGroups"] = topicGroups; ViewData["seletedUserIds"] = userIds; ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Error, ""); return View(tagEditModel); } else if (!string.IsNullOrEmpty(fileName)) { LogoSettings logoSettings = DIContainer.Resolve<ISettingsManager<LogoSettings>>().Get(); if (!logoSettings.<API key>(fileName)) { SelectList topicGroups = <API key>(tagEditModel.TopicGroupId, tagEditModel.TenantTypeId); ViewData["topicGroups"] = topicGroups; ViewData["seletedUserIds"] = userIds; ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Error, " .gif .jpg .jpeg .png "); return View(tagEditModel); } TenantLogoSettings tenantLogoSettings = TenantLogoSettings.<API key>(TenantTypeIds.Instance().Tag()); if (!tenantLogoSettings.ValidateFileLength(tagLogo.ContentLength)) { SelectList topicGroups = <API key>(tagEditModel.TopicGroupId, tagEditModel.TenantTypeId); ViewData["topicGroups"] = topicGroups; ViewData["seletedUserIds"] = userIds; ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Error, string.Format("{0}KB", tenantLogoSettings.MaxLogoLength)); return View(tagEditModel); } stream = tagLogo.InputStream; tagEditModel.FeaturedImage = fileName; } } IEnumerable<long> seletedUserIds = userIds; if (isCreate) { Tag tag = tagEditModel.AsTag(); tagService.Create(tag, stream); if (tagEditModel.TopicGroupId > 0) { tagService.BatchAddGroupsToTag(new List<long>() { tagEditModel.TopicGroupId }, tagEditModel.TagName); } } else { Tag tag = tagEditModel.AsTag(); tagService.Update(tag, stream); if (tagEditModel.TopicGroupId > 0) { tagService.BatchAddGroupsToTag(new List<long>() { tagEditModel.TopicGroupId }, tagEditModel.TagName); } } return RedirectToAction("<API key>"); } <summary> </summary> <param name="topicIds">ID</param> <returns></returns> public JsonResult DeleteTopics(string topicIds) { if (!string.IsNullOrEmpty(topicIds)) { var ids = topicIds.TrimEnd(',').Split(','); foreach (var topicId in ids) { tagService.Delete(long.Parse(topicId)); } return Json(new StatusMessageData(StatusMessageType.Success, ""), JsonRequestBehavior.AllowGet); } else { return Json(new StatusMessageData(StatusMessageType.Error, ""), JsonRequestBehavior.AllowGet); } } <summary> </summary> <returns></returns> [HttpGet] public ActionResult _SetTopicGroup(string topicIds = null) { SelectList topicGroups = <API key>(0, TenantTypeIds.Instance().Microblog()); ViewData["topicGroups"] = topicGroups; return View(); } <summary> </summary> <param name="topicIds">ID</param> <param name="groupId">ID</param> <returns></returns> [HttpPost] public JsonResult _SetTopicGroup(string topicIds, long groupId) { if (!string.IsNullOrEmpty(topicIds)) { var ids = topicIds.TrimEnd(',').Split(','); foreach (var id in ids) { Tag topic = tagService.Get(long.Parse(id)); tagService.BatchAddGroupsToTag(new List<long>() { groupId }, topic.TagName); } return Json(new StatusMessageData(StatusMessageType.Success, ""), JsonRequestBehavior.AllowGet); } else { return Json(new StatusMessageData(StatusMessageType.Error, ""), JsonRequestBehavior.AllowGet); } } #endregion #region <summary> </summary> public ActionResult <API key>(string keyword = "", bool? isFeatured = null, int pageIndex = 1, int pageSize = 30) { pageResourceManager.InsertTitlePart(""); TagQuery tagQuery = new TagQuery(); tagQuery.TenantTypeId = TenantTypeIds.Instance().Microblog(); tagQuery.Keyword = keyword; tagQuery.IsFeatured = isFeatured; PagingDataSet<Tag> topics = tagService.GetTags(tagQuery, pageIndex, pageSize); return View(topics); } <summary> </summary> private SelectList <API key>(long groupId, string tenantTypeId) { IEnumerable<TagGroup> tagGroups = tagService.GetGroups(tenantTypeId); SelectList groupList = null; if (tagGroups.Count() == 0) { groupList = new SelectList(new List<SelectListItem>() { new SelectListItem() { Text = "", Value = "0" } }, "value", "text"); } else { TagGroup tagGroupEntity = new TagGroup(); tagGroupEntity.GroupName = ""; tagGroupEntity.GroupId = 0; List<TagGroup> tagGroupsList = tagGroups.ToList<TagGroup>(); tagGroupsList.Insert(0, tagGroupEntity); groupList = new SelectList(tagGroupsList.Select(n => new { text = n.GroupName, value = n.GroupId }), "value", "text", groupId); } return groupList; } #endregion #endregion #region #region <summary> / </summary> <returns></returns> [HttpGet] public ActionResult _EditTopicGroup(long topicGroupId = 0) { TagGroupEditModel topicGroupEditModel = null; if (topicGroupId == 0) { topicGroupEditModel = new TagGroupEditModel(); topicGroupEditModel.TenantTypeId = tenantTypeId; } else { topicGroupEditModel = tagService.GetGroup(topicGroupId).AsTagGroupEditModel(); } return View(topicGroupEditModel); } <summary> / </summary> <returns></returns> [HttpPost] public ActionResult _EditTopicGroup(TagGroupEditModel topicGroupEditModel) { if (topicGroupEditModel.GroupId == 0) { tagService.CreateGroup(topicGroupEditModel.AsTagGroup()); return Json(new StatusMessageData(StatusMessageType.Success, ""), JsonRequestBehavior.AllowGet); } else { tagService.UpdateGroup(topicGroupEditModel.AsTagGroup()); return Json(new StatusMessageData(StatusMessageType.Success, ""), JsonRequestBehavior.AllowGet); } } <summary> </summary> <param name="topicGroupIds">ID</param> <returns></returns> public JsonResult DeleteTopicGroups(string topicGroupIds) { if (!string.IsNullOrEmpty(topicGroupIds)) { foreach (var topicGroupId in topicGroupIds.TrimEnd(',').Split(',')) { tagService.ClearTagsFromGroup(long.Parse(topicGroupId)); tagService.DeleteGroup(tagService.GetGroup((long.Parse(topicGroupId)))); } return Json(new StatusMessageData(StatusMessageType.Success, ""), JsonRequestBehavior.AllowGet); } else { return Json(new StatusMessageData(StatusMessageType.Error, ""), JsonRequestBehavior.AllowGet); } } #endregion #region <summary> </summary> <returns></returns> public ActionResult ManageTopicGroups() { pageResourceManager.InsertTitlePart(""); IEnumerable<TagGroup> topicGroups = tagService.GetGroups(tenantTypeId); return View(topicGroups); } #endregion #endregion } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Petri Net API: pnapi::io::__woflan::output</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Petri Net API &#160;<span id="projectnumber">Version 4.02</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.1.2 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="a00178.html">pnapi</a></li><li class="navelem"><a class="el" href="a00181.html">io</a></li><li class="navelem"><a class="el" href="a00187.html">__woflan</a></li> </ul> </div> </div><!-- top --> <div class="contents"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td valign="top"> <div class="navtab"> <table> <tr><td class="navtab"><a class="qindex" href="<API key>.html#<API key>">output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="<API key>.html#<API key>">output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="<API key>.html#<API key>">output</a></td></tr> <tr><td class="navtab"><a class="qindexHL" href="<API key>.html#<API key>">output</a></td></tr> </table> </div> </td> <td valign="top" class="mempage"> <a class="anchor" id="<API key>"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">std::ostream &amp; pnapi::io::__woflan::output </td> <td>(</td> <td class="paramtype">std::ostream &amp;&#160;</td> <td class="paramname"><em>os</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const Arc &amp;&#160;</td> <td class="paramname"><em>arc</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>arc output </p> <p>Definition at line <a class="el" href="a00114_source.html#l01575">1575</a> of file <a class="el" href="a00114_source.html">io-format.cc</a>.</p> <p>References <a class="el" href="a00100_source.html#l00127">pnapi::Node::getName()</a>, <a class="el" href="a00100_source.html#l00879">pnapi::Arc::getPlace()</a>, and <a class="el" href="a00100_source.html#l00894">pnapi::Arc::getWeight()</a>.</p> <div class="fragment"><div class="line">{</div> <div class="line"> <span class="keywordflow">for</span>(<span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> i = 0; i &lt; arc.getWeight(); ++i)</div> <div class="line"> {</div> <div class="line"> os &lt;&lt; <span class="stringliteral">&quot;\&quot;&quot;</span> &lt;&lt; arc.getPlace().getName() &lt;&lt; <span class="stringliteral">&quot;\&quot; &quot;</span>;</div> <div class="line"> }</div> <div class="line"> </div> <div class="line"> <span class="keywordflow">return</span> os;</div> <div class="line">}</div> </div><!-- fragment --> <p><div class="dynheader"> Here is the call graph for this function:</div> <div class="dyncontent"> <div class="center"><img src="a00187_ae7183af56bb6b753766ce8bfe39757cf_ae7183af56bb6b753766ce8bfe39757cf_cgraph.png" border="0" usemap="#a00187_ae7183af56bb6b753766ce8bfe39757cf_ae7183af56bb6b753766ce8bfe39757cf_cgraph" alt=""/></div> <map name="a00187_ae7183af56bb6b753766ce8bfe39757cf_ae7183af56bb6b753766ce8bfe39757cf_cgraph" id="a00187_ae7183af56bb6b753766ce8bfe39757cf_ae7183af56bb6b753766ce8bfe39757cf_cgraph"> <area shape="rect" id="node3" href="<API key>.html#<API key>" title="returns the name of the node" alt="" coords="181,5,331,33"/><area shape="rect" id="node5" href="<API key>.html#<API key>" title="place" alt="" coords="188,55,324,83"/><area shape="rect" id="node7" href="<API key>.html#<API key>" title="weight" alt="" coords="185,106,327,134"/></map> </div> </p> </div> </div> </td> </tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Thu Sep 17 2015 15:58:17 for Petri Net API by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1.2 </small></address> </body> </html>
// Created file "Lib\src\dxguid\X64\d3dxguid" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_ID3DXFileData, 0xcef08cfd, 0x7b4f, 0x4429, 0x96, 0x24, 0x2a, 0x69, 0x0a, 0x93, 0x32, 0x01);
#include "tree_widget.hh" #include "ui_tree_widget.h" namespace editor { Tree_Widget::Tree_Widget( QWidget *parent) : QWidget(parent), ui(new Ui::Tree_Widget) { ui->setupUi(this); connect(ui->tree_view, &Tree_View::something_selected, this, &Tree_Widget::something_selected); connect(ui->tree_view, &Tree_View::current_changed, [this](const QModelIndex &current, const QModelIndex &previous) { init_slider_bar(current); }); connect(ui->slider_bar, &Slider_Bar::jump_requested, this, &Tree_Widget::jump_to_rank); } void Tree_Widget::init_slider_bar(const QModelIndex &current) { auto m = ui->tree_view->model(); if (!m) return; auto n = m->rowCount(current.parent()); auto pos = current.row()+1; ui->slider_bar->init(pos, n); } void Tree_Widget::jump_to_rank(int value) { if (value < 1) return; auto i = ui->tree_view->currentIndex().sibling(value-1, 0); jump_to_index(i); } void Tree_Widget::jump_to_index(const QModelIndex &i) { if (!i.isValid()) return; // also selects: ui->tree_view->setCurrentIndex(i); // does not set the current index: //ui->tree_view->selectionModel()->select(i, // QItemSelectionModel::ClearAndSelect); ui->tree_view->scrollTo(i, QAbstractItemView::PositionAtCenter); } Tree_Widget::~Tree_Widget() { delete ui; } Tree_View &Tree_Widget::tree_view() { return *ui->tree_view; } }
#ifndef <API key> #define <API key> #include "core/CommandHandler.h" #include "core/use_cases/register_sprint/<API key>.h" #include "qt_gui/presentation/<API key>.h" namespace sprint_timer::ui { class <API key> : public contracts::<API key>::Presenter { public: using <API key> = CommandHandler<use_cases::<API key>>; explicit <API key>( <API key>& <API key>); void <API key>(const std::string& taskUuid, dw::DateTime firstSprintStart, int32_t numSprints, std::chrono::minutes sprintDuration) override; void registerSprintBulk( const std::string& taskUuid, const std::vector<dw::DateTimeRange>& timeRanges) override; private: <API key>& <API key>; }; } // namespace sprint_timer::ui #endif /* end of include guard: <API key> */
package org.molgenis.script; import com.google.common.collect.Lists; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.<API key>; import org.apache.commons.lang3.RandomStringUtils; import org.molgenis.data.Entity; import org.molgenis.data.meta.model.EntityType; import org.molgenis.data.support.StaticEntity; import org.molgenis.file.FileStore; import java.io.*; import java.util.Collections; import java.util.List; import java.util.Map; import static java.nio.charset.StandardCharsets.UTF_8; import static org.molgenis.script.ScriptMetaData.*; public class Script extends StaticEntity { public Script(Entity entity) { super(entity); } public Script(EntityType entityType) { super(entityType); } public Script(String name, EntityType entityType) { super(entityType); setName(name); } public String getName() { return getString(NAME); } public void setName(String name) { set(NAME, name); } public ScriptType getScriptType() { return getEntity(TYPE, ScriptType.class); } public void setScriptType(ScriptType scriptType) { set(TYPE, scriptType); } public String getContent() { return getString(CONTENT); } public void setContent(String content) { set(CONTENT, content); } public String <API key>() { return getString(<API key>); } public void <API key>(String resultFileExtension) { set(<API key>, resultFileExtension); } public List<ScriptParameter> getParameters() { Iterable<ScriptParameter> params = getEntities(PARAMETERS, ScriptParameter.class); if (params == null) return Collections.emptyList(); return Lists.newArrayList(params); } public boolean isGenerateToken() { Boolean generateToken = getBoolean(GENERATE_TOKEN); return generateToken != null && generateToken.booleanValue(); } public void setGenerateToken(Boolean generateToken) { set(GENERATE_TOKEN, generateToken); } public String generateScript(Map<String, Object> parameterValues) { StringWriter stringWriter = new StringWriter(); String script; try { generateScript(parameterValues, stringWriter); script = stringWriter.toString(); } finally { try { stringWriter.close(); } catch (IOException e) { throw new RuntimeException(e); } } return script; } public File generateScript(FileStore fileStore, String fileExtension, Map<String, Object> parameterValues) { String name = RandomStringUtils.randomAlphanumeric(10) + "." + fileExtension; File rScriptFile = fileStore.getFile(name); Writer w = null; try { w = new <API key>(rScriptFile, UTF_8); generateScript(parameterValues, w); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(w); } return rScriptFile; } private void generateScript(Map<String, Object> parameterValues, Writer writer) { try { Template template = new Template(null, new StringReader(getContent()), new Configuration()); template.process(parameterValues, writer); } catch (TemplateException | IOException e) { throw new <API key>( "Error processing parameters for script [" + getName() + "]. " + e.getMessage()); } } }
package org.sonar.server.platform.monitoring; import com.google.common.collect.ImmutableSortedMap; import java.util.Map; import java.util.SortedMap; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.Settings; import static org.apache.commons.lang.StringUtils.abbreviate; public class SettingsMonitor implements Monitor { static final int MAX_VALUE_LENGTH = 500; private final Settings settings; public SettingsMonitor(Settings settings) { this.settings = settings; } @Override public String name() { return "Settings"; } @Override public SortedMap<String, Object> attributes() { PropertyDefinitions definitions = settings.getDefinitions(); ImmutableSortedMap.Builder<String, Object> builder = ImmutableSortedMap.naturalOrder(); for (Map.Entry<String, String> prop : settings.getProperties().entrySet()) { String key = prop.getKey(); PropertyDefinition def = definitions.get(key); if (def == null || def.type() != PropertyType.PASSWORD) { builder.put(key, abbreviate(prop.getValue(), MAX_VALUE_LENGTH)); } } return builder.build(); } }
#include "cwd_tx.h" #include "picotm/picotm-error.h" #include "picotm/picotm-lib-array.h" #include "picotm/picotm-lib-tab.h" #include "picotm/picotm-module.h" #include <assert.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include "compat/<API key>.h" #include "cwd_log.h" static void init_rwstates(struct picotm_rwstate* beg, const struct picotm_rwstate* end) { while (beg < end) { picotm_rwstate_init(beg); ++beg; } } static void uninit_rwstates(struct picotm_rwstate* beg, const struct picotm_rwstate* end) { while (beg < end) { <API key>(beg); ++beg; } } static void unlock_rwstates(struct picotm_rwstate* beg, const struct picotm_rwstate* end, struct cwd* cwd) { enum cwd_field field = 0; while (beg < end) { cwd_unlock_field(cwd, field, beg); ++field; ++beg; } } void cwd_tx_init(struct cwd_tx* self, struct cwd_log* log, struct cwd* cwd) { assert(self); assert(cwd); self->log = log; self->cwd = cwd; init_rwstates(picotm_arraybeg(self->rwstate), picotm_arrayend(self->rwstate)); } void cwd_tx_uninit(struct cwd_tx* self) { assert(self); uninit_rwstates(picotm_arraybeg(self->rwstate), picotm_arrayend(self->rwstate)); } void <API key>(struct cwd_tx* self, enum cwd_field field, struct picotm_error* error) { assert(self); <API key>(self->cwd, field, self->rwstate + field, error); } void <API key>(struct cwd_tx* self, enum cwd_field field, struct picotm_error* error) { assert(self); <API key>(self->cwd, field, self->rwstate + field, error); } /* * chdir() */ int cwd_tx_chdir_exec(struct cwd_tx* self, const char* path, struct picotm_error* error) { assert(self); <API key>(self, CWD_FIELD_STRING, error); if (picotm_error_is_set(error)) { return -1; } char* cwd = <API key>(); if (!cwd) { <API key>(error, errno); return -1; } int res = chdir(path); if (res < 0) { <API key>(error, errno); goto err_chdir; } cwd_log_append(self->log, CWD_OP_CHDIR, cwd, error); if (picotm_error_is_set(error)) { goto err_append_event; } return res; err_append_event: res = chdir(cwd); if (res < 0) { /* We keep the original error code. We mark the error * as non-recoverable, because the function's clean-up * block failed. */ <API key>(error); } err_chdir: free(cwd); return -1; } void apply_chdir(struct cwd_tx* self, char* old_cwd, struct picotm_error* error) { free(old_cwd); } void undo_chdir(struct cwd_tx* self, char* old_cwd, struct picotm_error* error) { assert(old_cwd); /* The old working directory might have been deleted by an external * process. We cannot do much about it, but signal a transaction error. */ int res = chdir(old_cwd); if (res < 0) { <API key>(error, errno); } free(old_cwd); } /* * getcwd() */ char* cwd_tx_getcwd_exec(struct cwd_tx* self, char* buf, size_t size, struct picotm_error* error) { assert(self); <API key>(self, CWD_FIELD_STRING, error); if (picotm_error_is_set(error)) { return NULL; } char* cwd = getcwd(buf, size); if (!cwd) { <API key>(error, errno); return NULL; } char* alloced_cwd; if (!buf && cwd) { /* Some implementations of getcwd() return a newly allocated * buffer if 'buf' is NULL. We free this buffer during a roll- * back. */ alloced_cwd = cwd; } else { alloced_cwd = NULL; } cwd_log_append(self->log, CWD_OP_GETCWD, alloced_cwd, error); if (picotm_error_is_set(error)) { goto err_append_event; } return cwd; err_append_event: if (!buf && cwd) { free(cwd); } return NULL; } void apply_getcwd(struct cwd_tx* self, char* alloced_cwd, struct picotm_error* error) { assert(self); } void undo_getcwd(struct cwd_tx* self, char* alloced_cwd, struct picotm_error* error) { assert(self); free(alloced_cwd); } /* * realpath() */ char* <API key>(struct cwd_tx* self, const char* path, char* resolved_path, struct picotm_error* error) { assert(self); <API key>(self, CWD_FIELD_STRING, error); if (picotm_error_is_set(error)) { return NULL; } char* res = realpath(path, resolved_path); if (!res) { <API key>(error, errno); return NULL; } char* alloced_res; if (!resolved_path && res) { /* Calls to realpath() return a newly allocated buffer if * 'resolved_path' is NULL. We free this buffer during a roll- * back. */ alloced_res = res; } else { alloced_res = NULL; } cwd_log_append(self->log, CWD_OP_REALPATH, alloced_res, error); if (picotm_error_is_set(error)) { goto err_append_event; } return res; err_append_event: if (!resolved_path && res) { free(res); } return NULL; } void apply_realpath(struct cwd_tx* self, char* alloced_res, struct picotm_error* error) { assert(self); } void undo_realpath(struct cwd_tx* self, char* alloced_res, struct picotm_error* error) { assert(self); free(alloced_res); } /* * Module interface */ void cwd_tx_apply_event(struct cwd_tx* self, enum cwd_op op, char* alloced, struct picotm_error* error) { static void (* const apply[])(struct cwd_tx*, char*, struct picotm_error*) = { apply_chdir, apply_getcwd, apply_realpath }; apply[op](self, alloced, error); if (picotm_error_is_set(error)) { return; } } void cwd_tx_undo_event(struct cwd_tx* self, enum cwd_op op, char* alloced, struct picotm_error* error) { static void (* const undo[])(struct cwd_tx*, char*, struct picotm_error*) = { undo_chdir, undo_getcwd, undo_realpath }; undo[op](self, alloced, error); if (picotm_error_is_set(error)) { return; } } void cwd_tx_finish(struct cwd_tx* self) { assert(self); /* release reader/writer locks on current working directory */ unlock_rwstates(picotm_arraybeg(self->rwstate), picotm_arrayend(self->rwstate), self->cwd); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Utilities; using System.Linq.Expressions; using Signum.Utilities.ExpressionTrees; namespace Signum.Entities.Basics { [Serializable] public class DateSpanEmbedded : EmbeddedEntity { public int Years { get; set; } public int Months { get; set; } public int Days { get; set; } public bool IsZero() { return Years == 0 && Months == 0 && Days == 0; } static Expression<Func<DateSpanEmbedded, DateTime, DateTime>> AddExpression = (ds, dt) => dt.AddYears(ds.Years).AddMonths(ds.Months).AddDays(ds.Days); [ExpressionField] public DateTime Add(DateTime date) { return AddExpression.Evaluate(this, date); } static Expression<Func<DateSpanEmbedded, DateTime, DateTime>> SubtractExpression = (ds, dt) => dt.AddYears(-ds.Years).AddMonths(-ds.Months).AddDays(-ds.Days); [ExpressionField] public DateTime Subtract(DateTime date) { return SubtractExpression.Evaluate(this, date); } public DateSpan ToDateSpan() { return new DateSpan(Years, Months, Days); } public override string ToString() { return ToDateSpan().ToString(); } public DateSpanEmbedded Clone() { DateSpanEmbedded ds = new DateSpanEmbedded { Days = this.Days, Months = this.Months, Years = this.Years, }; return ds; } } [Serializable] public class TimeSpanEmbedded : EmbeddedEntity { public int Days { get; set; } public int Hours { get; set; } public int Minutes { get; set; } public int Seconds { get; set; } public bool IsZero() { return Days == 0 && Hours == 0 && Minutes == 0 && Seconds == 0; } static Expression<Func<TimeSpanEmbedded, DateTime, DateTime>> AddExpression = (ds, dt) => dt.AddDays(ds.Days).AddHours(ds.Hours).AddMinutes(ds.Minutes).AddMinutes(ds.Seconds); [ExpressionField] public DateTime Add(DateTime date) { return AddExpression.Evaluate(this, date); } static Expression<Func<TimeSpanEmbedded, DateTime, DateTime>> SubtractExpression = (ds, dt) => dt.AddDays(-ds.Days).AddHours(-ds.Hours).AddMinutes(-ds.Minutes).AddMinutes(-ds.Seconds); [ExpressionField] public DateTime Subtract(DateTime date) { return SubtractExpression.Evaluate(this, date); } public TimeSpan ToTimeSpan() { return new TimeSpan(Days, Hours, Minutes, Seconds); } public override string ToString() { return ToTimeSpan().ToString(); } public TimeSpanEmbedded Clone() { TimeSpanEmbedded ds = new TimeSpanEmbedded { Days = this.Days, Hours = this.Hours, Minutes = this.Minutes, Seconds = this.Seconds, }; return ds; } } }
package repack.org.bouncycastle.asn1.esf; import repack.org.bouncycastle.asn1.*; import repack.org.bouncycastle.asn1.x509.DisplayText; import repack.org.bouncycastle.asn1.x509.NoticeReference; import java.util.Enumeration; public class SPUserNotice { private NoticeReference noticeRef; private DisplayText explicitText; public static SPUserNotice getInstance( Object obj) { if (obj == null || obj instanceof SPUserNotice) { return (SPUserNotice) obj; } else if (obj instanceof ASN1Sequence) { return new SPUserNotice((ASN1Sequence) obj); } throw new <API key>( "unknown object in 'SPUserNotice' factory : " + obj.getClass().getName() + "."); } public SPUserNotice( ASN1Sequence seq) { Enumeration e = seq.getObjects(); while (e.hasMoreElements()) { DEREncodable object = (DEREncodable) e.nextElement(); if (object instanceof NoticeReference) { noticeRef = NoticeReference.getInstance(object); } else if (object instanceof DisplayText) { explicitText = DisplayText.getInstance(object); } else { throw new <API key>("Invalid element in 'SPUserNotice'."); } } } public SPUserNotice( NoticeReference noticeRef, DisplayText explicitText) { this.noticeRef = noticeRef; this.explicitText = explicitText; } public NoticeReference getNoticeRef() { return noticeRef; } public DisplayText getExplicitText() { return explicitText; } /** * <pre> * SPUserNotice ::= SEQUENCE { * noticeRef NoticeReference OPTIONAL, * explicitText DisplayText OPTIONAL } * </pre> */ public DERObject toASN1Object() { ASN1EncodableVector v = new ASN1EncodableVector(); if (noticeRef != null) { v.add(noticeRef); } if (explicitText != null) { v.add(explicitText); } return new DERSequence(v); } }
import math, M2Crypto, base64 from lostexhaust.models.carpool import Carpool from lostexhaust.models.household import Household def geo_distance(latitude, longitude, other_latitude, other_longitude): lat = math.radians(latitude) lon = math.radians(longitude) lat2 = math.radians(other_latitude) lon2 = math.radians(other_longitude) deltaLat = lat2 - lat deltaLon = lon2 - lon sinPart = (math.sin(deltaLat / 2.0)) cosPart = (math.cos(lat) * math.cos(lat2) * math.sin(deltaLon / 2.0)) angle = 2.0 * math.asin(math.sqrt(sinPart * sinPart + cosPart * cosPart)) return 3960.0 * angle; def get_sorted_carpools(origin, other_households): return sorted([Carpool(origin.household_id, o.household_id, geo_distance(origin.latitude, origin.longitude, o.latitude, o.longitude)).__dict__ for o in other_households], key=lambda e: e["distance"]) def m2crypto_load_der(filename): raw = open(filename, 'rb').read() data = TEMPLATE % base64.encodestring(raw).rstrip() key = M2Crypto.RSA.load_key_string(data) return key def print_file(filename, message): with open(filename, 'a') as myfile: myfile.write(message + '\n')
tai.give_item = function (player, item) local player_name = player:get_player_name() local inventory = player:get_inventory() local s = ItemStack(item) if inventory:room_for_item("main", s) then inventory:add_item("main", {name = item, count = s:get_stack_max()}) minetest.chat_send_player(player_name, 'TAI: '..s:get_stack_max()..' '..item..' given to '..player_name..'.') else minetest.chat_send_player(player_name, 'TAI: Your inventory is full.') end end tai.is_allowed_item = function(name) local l = tai.config.whitelist for _,v in ipairs(l) do if name:find(v, 1, true) then return true end end return false end tai.inv_button = function (id, x, y, caption) local dx, dy = 0.792, 0.9 return 'image_button['..tostring(x * dx)..','..tostring(y * dy)..';0.9,0.85;tai_slot.png;'..id..';'..minetest.formspec_escape(caption)..';false;false;tai_slot_active.png]' end tai.inv_item_button = function (id, posx, posy, itemname) local dx, dy = 0.792, 0.9 local x = posx * dx local y = posy * dy local w, h = 0.9, 0.85 local formspec = {} local itemcaption, def, groups if itemname:find('group:', 1, true) then groups = itemname:sub(itemname:find(':', 1, true)+1):split(',') itemcaption = minetest.formspec_escape(core.colorize('#00FF00', string.gsub(itemname, ',', '\ngroup:'))) if #groups > 1 then formspec[#formspec + 1] = 'item_image['..tostring(x + 0.1)..','..tostring(y + 0.1)..';'..tostring(w - 0.27)..','..tostring(h - 0.25)..';'..tai.get_items_in_group(groups)[1]..']' else formspec[#formspec + 1] = 'item_image['..tostring(x + 0.1)..','..tostring(y + 0.1)..';'..tostring(w - 0.27)..','..tostring(h - 0.25)..';'..tai.groups[groups[1]]..']' end else def = minetest.registered_items[itemname] if def and def.description and def.description ~= '' then itemcaption = minetest.formspec_escape(def.description..'\n'..core.colorize('#00FF00',itemname)) else itemcaption = minetest.formspec_escape('Unknown\n'..core.colorize('#FF0000',itemname)) end formspec[#formspec + 1] = 'item_image['..tostring(x + 0.1)..','..tostring(y + 0.1)..';'..tostring(w - 0.27)..','..tostring(h - 0.25)..';'..itemname..']' end formspec[#formspec + 1] = 'image_button['..x..','..y..';'..w..','..h..';tai_slot.png;'..id..';;false;false;tai_slot_active.png]' formspec[#formspec + 1] = 'tooltip['..id..';'..itemcaption..']' return table.concat(formspec, '') end tai.inv_button_big = function (id, x, y, caption) local dx, dy = 0.792, 0.9 return 'image_button['..tostring(x * dx)..','..tostring(y * dy)..';3.6,0.85;tai_button.png;'..id..';'..minetest.formspec_escape(caption)..';false;false;tai_button_active.png]' end -- return small grid (10x9) coords tai.inv_coords = function (args) local dx, dy = 0.792, 0.9 local maxx, maxy = 9, 8 local coords = {} if args.x then coords.x = dx * args.x end if args.y then coords.y = dy * args.y end return coords end tai.inv_items_list = function (items, args) local dx, dy = 0.792, 0.9 local w, h = 0.9, 0.85 local cols = args.cols local index, l local x, y = args.x, args.y local startx = x local formspec = {} if args.index then index = args.index else index = 1 end if args.length then l = args.length else l = #items end for i=index,l do itemname = items[i] if itemname and itemname ~= '' then formspec[#formspec + 1] = tai.inv_item_button('tai_item:'..itemname, x, y, itemname) else if args.empty then formspec[#formspec + 1] = 'image['..tostring(x * dx)..','..tostring(y * dy)..';'..w..','..h..';tai_slot.png]' end end x = x + 1 if i % cols == 0 then x = startx y = y + 1 end end return table.concat(formspec, '') end