Esempio n. 1
0
bool transaction::fetch_inputs(
    db_tx & dbtx, const std::map<sha256, transaction_index> & test_pool,
    const bool & best_block, const bool & create_block,
    transaction::previous_t & inputs, bool & invalid
    )
{
    /**
     * If the transaction is invalid this will be set to true.
     */
    invalid = false;

    /**
     * Coinbase transactions have no inputs to fetch.
     */
    if (is_coin_base())
    {
        return true;
    }
    
    for (auto i = 0; i < m_transactions_in.size(); i++)
    {
        auto previous_out = m_transactions_in[i].previous_out();
        
        if (inputs.count(previous_out.get_hash()) > 0)
        {
            continue;
        }
        
        /**
         * Read the transaction index.
         */
        auto & tx_index = inputs[previous_out.get_hash()].first;
        
        bool found = true;
        
        if (
            (best_block || create_block) &&
            test_pool.count(previous_out.get_hash()) > 0
            )
        {
            /**
             * Get the transaction index from the current proposed changes.
             */
            tx_index = test_pool.find(previous_out.get_hash())->second;
        }
        else
        {
            /**
             * Read transaction index from transaction database.
             */
            found = dbtx.read_transaction_index(
                previous_out.get_hash(), tx_index
            );
        }
        
        if (found == false && (best_block || create_block))
        {
            if (create_block)
            {
                return false;
            }
            else
            {
                log_error(
                    "Transaction " << get_hash().to_string().substr(0, 10) <<
                    " previous transaction " <<
                    previous_out.get_hash().to_string().substr(0, 10) <<
                    " index entry not found."
                );

                return false;
            }
        }
        
        /**
         * Read previous transaction.
         */
        auto & tx_prev = inputs[previous_out.get_hash()].second;
        
        if (
            found == false ||
            tx_index.get_transaction_position() == transaction_position(1, 1, 1)
            )
        {
            if (
                transaction_pool::instance().exists(
                previous_out.get_hash()) == false
                )
            {
                log_debug(
                    "Transaction failed to fetch inputs, " <<
                    get_hash().to_string().substr(0, 10) <<
                    " pool previous transaction not found " <<
                    previous_out.get_hash().to_string().substr(0, 10) << "."
                );
                
                return false;
            }
            
            tx_prev = transaction_pool::instance().lookup(
                previous_out.get_hash()
            );
           
            if (found == false)
            {
                tx_index.spent().resize(tx_prev.transactions_out().size());
            }
        }
        else
        {
            /**
             * Read previous transaction from disk.
             */
            if (
                tx_prev.read_from_disk(
                tx_index.get_transaction_position()) == false
                )
            {
                log_error(
                    "Transaction " << get_hash().to_string().substr(0, 10) <<
                    " failed to read previous transaction " <<
                    previous_out.get_hash().to_string().substr(0, 10) <<
                    " from disk."
                );
                
                return false;
            }
        }
    }
    
    /**
     * Check that all previous out's n indexes are valid.
     */
    for (auto i = 0; i < m_transactions_in.size(); i++)
    {
        const auto & previous_out = m_transactions_in[i].previous_out();
        
        assert(inputs.count(previous_out.get_hash()) != 0);
        
        auto & tx_index = inputs[previous_out.get_hash()].first;
        
        auto & tx_prev = inputs[previous_out.get_hash()].second;
        
        if (
            previous_out.n() >= tx_prev.transactions_out().size() ||
            previous_out.n() >= tx_index.spent().size()
            )
        {
            /**
             * Revisit this if/when transaction replacement is implemented
             * and allows adding inputs.
             */
            invalid = true;
            
            log_error(
                "Transaction " << get_hash().to_string().substr(0, 10) <<
                " previous out n out of range " << previous_out.n() << ":" <<
                tx_prev.transactions_out().size() << ":" <<
                tx_index.spent().size() << " previous transaction " <<
                previous_out.get_hash().to_string().substr(0, 10) << "\n" <<
                tx_prev.to_string() << "."
            );
            
            return false;
        }
    }

    return true;
}
Esempio n. 2
0
/// Microsoft helper function for getting the contents of a registry key
void queryKey(const std::string& hive,
              const std::string& key,
              QueryData& results) {
  if (kRegistryHives.count(hive) != 1) {
    return;
  }

  HKEY hRegistryHandle;
  auto ret = RegOpenKeyEx(kRegistryHives.at(hive),
                          TEXT(key.c_str()),
                          0,
                          KEY_READ,
                          &hRegistryHandle);

  if (ret != ERROR_SUCCESS) {
    return;
  }

  const DWORD maxKeyLength = 255;
  const DWORD maxValueName = 16383;
  TCHAR achClass[MAX_PATH] = TEXT("");
  DWORD cchClassName = MAX_PATH;
  DWORD cSubKeys = 0;
  DWORD cbMaxSubKey;
  DWORD cchMaxClass;
  DWORD cValues;
  DWORD cchMaxValueName;
  DWORD cbMaxValueData;
  DWORD cbSecurityDescriptor;
  DWORD retCode;
  FILETIME ftLastWriteTime;
  retCode = RegQueryInfoKey(hRegistryHandle,
                            achClass,
                            &cchClassName,
                            nullptr,
                            &cSubKeys,
                            &cbMaxSubKey,
                            &cchMaxClass,
                            &cValues,
                            &cchMaxValueName,
                            &cbMaxValueData,
                            &cbSecurityDescriptor,
                            &ftLastWriteTime);

  TCHAR achKey[maxKeyLength];
  DWORD cbName;

  // Process registry subkeys
  if (cSubKeys > 0) {
    for (DWORD i = 0; i < cSubKeys; i++) {
      cbName = maxKeyLength;
      retCode = RegEnumKeyEx(hRegistryHandle,
                             i,
                             achKey,
                             &cbName,
                             nullptr,
                             nullptr,
                             nullptr,
                             &ftLastWriteTime);
      if (retCode != ERROR_SUCCESS) {
        continue;
      }
      Row r;
      fs::path keyPath(key);
      r["hive"] = hive;
      r["key"] = keyPath.string();
      r["subkey"] = (keyPath / achKey).string();
      r["name"] = "(Default)";
      r["type"] = "REG_SZ";
      r["data"] = "(value not set)";
      r["mtime"] = std::to_string(filetimeToUnixtime(ftLastWriteTime));
      results.push_back(r);
    }
  }

  if (cValues <= 0) {
    return;
  }

  BYTE* bpDataBuff = new BYTE[cbMaxValueData];
  DWORD cchValue = maxKeyLength;
  TCHAR achValue[maxValueName];

  // Process registry values
  for (size_t i = 0, retCode = ERROR_SUCCESS; i < cValues; i++) {
    size_t cnt = 0;
    ZeroMemory(bpDataBuff, cbMaxValueData);
    cchValue = maxValueName;
    achValue[0] = '\0';

    retCode = RegEnumValue(hRegistryHandle,
                           static_cast<DWORD>(i),
                           achValue,
                           &cchValue,
                           nullptr,
                           nullptr,
                           nullptr,
                           nullptr);

    if (retCode != ERROR_SUCCESS) {
      continue;
    }

    DWORD lpData = cbMaxValueData;
    DWORD lpType;
    retCode = RegQueryValueEx(
        hRegistryHandle, achValue, 0, &lpType, bpDataBuff, &lpData);

    if (retCode != ERROR_SUCCESS) {
      continue;
    }

    Row r;
    fs::path keyPath(key);
    r["hive"] = hive;
    r["key"] = keyPath.string();
    r["subkey"] = keyPath.string();
    r["name"] = achValue;
    if (kRegistryTypes.count(lpType) > 0) {
      r["type"] = kRegistryTypes.at(lpType);
    } else {
      r["type"] = "UNKNOWN";
    }
    r["mtime"] = std::to_string(filetimeToUnixtime(ftLastWriteTime));

    bpDataBuff[cbMaxValueData - 1] = 0x00;

    /// REG_LINK is a Unicode string, which in Windows is wchar_t
    char* regLinkStr = nullptr;
    if (lpType == REG_LINK) {
      regLinkStr = new char[cbMaxValueData];
      const size_t newSize = cbMaxValueData;
      size_t convertedChars = 0;
      wcstombs_s(&convertedChars,
                 regLinkStr,
                 newSize,
                 (wchar_t*)bpDataBuff,
                 _TRUNCATE);
    }

    BYTE* bpDataBuffTmp = bpDataBuff;
    std::vector<std::string> multiSzStrs;
    std::vector<char> regBinary;
    std::string data;

    switch (lpType) {
    case REG_FULL_RESOURCE_DESCRIPTOR:
    case REG_RESOURCE_LIST:
    case REG_BINARY:
      for (unsigned int i = 0; i < cbMaxValueData; i++) {
        regBinary.push_back((char)bpDataBuff[i]);
      }
      boost::algorithm::hex(
          regBinary.begin(), regBinary.end(), std::back_inserter(data));
      r["data"] = data;
      break;
    case REG_DWORD:
      r["data"] = std::to_string(*((int*)bpDataBuff));
      break;
    case REG_DWORD_BIG_ENDIAN:
      r["data"] = std::to_string(_byteswap_ulong(*((int*)bpDataBuff)));
      break;
    case REG_EXPAND_SZ:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    case REG_LINK:
      r["data"] = std::string(regLinkStr);
      break;
    case REG_MULTI_SZ:
      while (*bpDataBuffTmp != 0x00) {
        std::string s((char*)bpDataBuffTmp);
        bpDataBuffTmp += s.size() + 1;
        multiSzStrs.push_back(s);
      }
      r["data"] = boost::algorithm::join(multiSzStrs, ",");
      break;
    case REG_NONE:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    case REG_QWORD:
      r["data"] = std::to_string(*((unsigned long long*)bpDataBuff));
      break;
    case REG_SZ:
      r["data"] = std::string((char*)bpDataBuff);
      break;
    default:
      r["data"] = "";
      break;
    }
    results.push_back(r);
    if (regLinkStr != nullptr) {
      delete (regLinkStr);
    }
  }
  delete (bpDataBuff);
  RegCloseKey(hRegistryHandle);
};
Esempio n. 3
0
const char* conTCPObjectConnect(Linker::SimObject *obj, S32 argc, const char *argv[])
{
	if (sRunningTCPObjects.count(obj->mId) >= 1)
		TCPObject_Disconnect(sRunningTCPObjects[obj->mId].get());
		
	DX::TCPObject *operand = new DX::TCPObject((unsigned int)obj);

	// Copy the hostname over
	char *desired_hostname = (char*)malloc(strlen(argv[2]) + 1);
	memcpy(desired_hostname, argv[2], strlen(argv[2]) + 1);

	// Create the connection info
	ConnectionInformation *connection = new ConnectionInformation;
	connection->target_hostname = desired_hostname;
	connection->buffer_length = 0;
	connection->is_connected = false;
	connection->socket = 0;

	// Hack: Store the Ptr to our connection information struct in the old unused state value
	operand->state = (unsigned int)connection;

	//ConnectionInformation *connection = (ConnectionInformation*)parameters;
	char *target_hostname = strlwr(connection->target_hostname);

	// Is it an IP we got?
	if (strstr(target_hostname, "ip:"))
		target_hostname += 3; // Chop off the 'ip:' segment

	// Did we get a port #?
	unsigned int desired_port = 0;
	char *port_delineator = strstr(target_hostname, ":");
	if (port_delineator)
	{
		port_delineator[0] = 0x00; // NULL Terminate the IP Segment
		port_delineator += 1;
		desired_port = atoi(port_delineator);
	}
	else
	{
		Con::errorf(0, "No Port");
		operand->CallMethod("onConnectFailed", 1, S32ToCharPtr(1));
		return "NO_PORT";
	}

	// Perform a DNS Lookup
	wchar_t hostname_dns[128];
	std::mbstowcs(hostname_dns, target_hostname, strlen(target_hostname) + 1);

	PDNS_RECORD dns_record;
	if (DnsQuery(hostname_dns, DNS_TYPE_A, DNS_QUERY_BYPASS_CACHE, NULL, &dns_record, NULL))
	{
		Con::errorf(0, "DNS Resolution Failed");
		operand->CallMethod("onDNSFailed", 0);
		return "FAILED_DNS";
	}
	IN_ADDR result_address;
	result_address.S_un.S_addr = dns_record->Data.A.IpAddress;

	DNS_FREE_TYPE freetype;
	DnsRecordListFree(dns_record, freetype);

	target_hostname = inet_ntoa(result_address);

	SOCKADDR_IN target_host;
	target_host.sin_family = AF_INET;
	target_host.sin_port = htons(desired_port);
	target_host.sin_addr.s_addr = inet_addr(target_hostname);

	Con::errorf(0, "Target %s on port %u SimID %u", target_hostname, desired_port, operand->identifier);

	// Create the Socket
	connection->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (connection->socket == INVALID_SOCKET)
	{
		Con::errorf(0, "Failed to create Socket!");
		operand->CallMethod("onConnectFailed", 2, S32ToCharPtr(2), S32ToCharPtr(WSAGetLastError()));
		return "FAILED_SOCKET_CREATION";
	}

	// Set Blocking Mode (a non-zero for imode = non-blocking)
	u_long imode = 1;
	ioctlsocket(connection->socket, FIONBIO, &imode);

	sRunningTCPObjects[obj->mId] = std::unique_ptr<DX::TCPObject>(operand);

	// Attempt the Connection
	connect(connection->socket, (SOCKADDR*)&target_host, sizeof(target_host));

	if (getsockopt(connection->socket, SOL_SOCKET, SO_ERROR, NULL, NULL) < 0)
	{
		operand->CallMethod("onConnectFailed", 2, S32ToCharPtr(3), S32ToCharPtr(WSAGetLastError()));
		return "CANNOT_CONNECT";
	}
	else
	{
		operand->CallMethod("onConnected", 0);
		return "SUCCESS";
	}

	return "UNKNOWN_ERROR";
}
 void Analyze(ControlCenter* Data)
 {
     while(!Library.empty())
     {
         Information Tem=GetInformation();
         bool Reflesh=false;
         if(Tem.Target==RegeditID)
         {
             switch(Tem.Category1)
             {
                 case VIEWLOCATION:
                     Location.X=Tem.Data1.f;
                     Location.Y=Tem.Data2.f;
                     Location.Z=Tem.Data3.f;
                     Reflesh=true;
                     break;
                 case VIEWANGLE:
                     AngleUp=Tem.Data1;
                     AngleRight=Tem.Data2;
                     Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
                     Up.Set(-sin(AngleUp)*sin(AngleRight),cos(AngleUp),sin(AngleUp)*cos(AngleRight));
                     Reflesh=true;
                     break;
             }
             if(Reflesh)
             {
                 Information Tr=Tem;
                 Tr.Target=Tem.Resource;
                 Tr.Resource=Tem.Target;
                 Out(Tr);
             }
         }
         if(OwnKey)
         {
             if(Tem.Target==INFALL&&Tem.Category1==INFEVENT)
             {
                 if(Tem.Category2==INFKEY)
                 {
                     if(Tem.Category3==INFKEYDOWN)
                     {
                         if(Key.count(Tem.Data1)>0)
                         {
                             Key[Tem.Data1]=true;
                         }
                     }else if(Tem.Category3==INFKEYUP)
                     {
                         if(Key.count(Tem.Data1)>0)
                         {
                             Key[Tem.Data1]=false;
                         }
                     }
                 }
             }
         }
     }
     if(Key['w'])
     {
         Location=Location+Front.Uint(MOVESPEED);
     }
     if(Key['s'])
     {
         Location=Location-Front.Uint(MOVESPEED);
     }
     if(Key['a'])
     {
         AngleRight-=MOVESPEEDANGLE;
         Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
     }
     if(Key['d'])
     {
         AngleRight+=MOVESPEEDANGLE;
         Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
     }
     if(Key['q'])
     {
         Location=Location+(Up&Front).Uint(MOVESPEED);
     }
     if(Key['e'])
     {
         Location=Location-(Up&Front).Uint(MOVESPEED);
     }
     if(Key['r'])
     {
         Location=Location+Up.Uint(MOVESPEED);
     }
     if(Key['f'])
     {
         Location=Location-Up.Uint(MOVESPEED);
     }
 }
Esempio n. 5
0
/**
 *Works through cached vehicle definitions and creates vehicle objects from them.
 */
void game::finalize_vehicles()
{
    int part_x = 0, part_y = 0;
    std::string part_id = "";
    vehicle *next_vehicle;

    std::map<point, bool> cargo_spots;

    while (!vehprototypes.empty()) {
        cargo_spots.clear();
        vehicle_prototype *proto = vehprototypes.front();
        vehprototypes.pop();

        next_vehicle = new vehicle(proto->id.c_str());
        next_vehicle->name = _(proto->name.c_str());

        for (size_t i = 0; i < proto->parts.size(); ++i) {
            point p = proto->parts[i].first;
            part_x = p.x;
            part_y = p.y;

            part_id = proto->parts[i].second;
            if (vehicle_part_types.count(part_id) == 0) {
                debugmsg("unknown vehicle part %s in %s", part_id.c_str(), proto->id.c_str());
                continue;
            }

            if(next_vehicle->install_part(part_x, part_y, part_id) < 0) {
                debugmsg("init_vehicles: '%s' part '%s'(%d) can't be installed to %d,%d",
                         next_vehicle->name.c_str(), part_id.c_str(),
                         next_vehicle->parts.size(), part_x, part_y);
            }
            if ( vehicle_part_types[part_id].has_flag("CARGO") ) {
                cargo_spots[p] = true;
            }
        }

        for (auto &i : proto->item_spawns) {
            if (cargo_spots.find(point(i.x, i.y)) == cargo_spots.end()) {
                debugmsg("Invalid spawn location (no CARGO vpart) in %s (%d, %d): %d%%",
                         proto->name.c_str(), i.x, i.y, i.chance);
            }
            for (auto &j : i.item_ids) {
                if( !item::type_is_defined( j ) ) {
                    debugmsg("unknown item %s in spawn list of %s", j.c_str(), proto->id.c_str());
                }
            }
            for (auto &j : i.item_groups) {
                if (!item_group::group_is_defined(j)) {
                    debugmsg("unknown item group %s in spawn list of %s", j.c_str(), proto->id.c_str());
                }
            }
        }
        next_vehicle->item_spawns = proto->item_spawns;

        if (vtypes.count(next_vehicle->type) > 0) {
            delete vtypes[next_vehicle->type];
        }
        vtypes[next_vehicle->type] = next_vehicle;
        delete proto;
    }
}
Esempio n. 6
0
void IfcPPModel::collectDependentEntities( shared_ptr<IfcPPEntity>& entity, std::map<IfcPPEntity*, shared_ptr<IfcPPEntity> >& target_map )
{
	if( !entity )
	{
		return;
	}
	//if( entity->m_id < 0 )
	//{
	//	entity->setId( next_entity_id );
	//	++next_entity_id;
	//}

	auto ele_assembly = dynamic_pointer_cast<IfcElementAssembly>( entity );
	if( ele_assembly )
	{
		int assembly_id = ele_assembly->m_id;
		std::vector<weak_ptr<IfcRelAggregates> >& vec_is_decomposed_by = ele_assembly->m_IsDecomposedBy_inverse;
		for( size_t ii = 0; ii < vec_is_decomposed_by.size(); ++ii )
		{
			const weak_ptr<IfcRelAggregates>& is_decomposed_weak_ptr = vec_is_decomposed_by[ii];
			if( auto is_decomposed_ptr = is_decomposed_weak_ptr.lock() )
			{
				int rel_aggregates_id = is_decomposed_ptr->m_id;

				shared_ptr<IfcPPEntity> as_ifcpp_entity = is_decomposed_ptr;
				collectDependentEntities( as_ifcpp_entity, target_map );
			}
		}
	}

	std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > > vec_attributes;
	entity->getAttributes( vec_attributes );
	for( size_t ii = 0; ii < vec_attributes.size(); ++ii )
	{
		shared_ptr<IfcPPObject>& attribute = vec_attributes[ii].second;
		if( !attribute )
		{
			// empty attribute
			continue;
		}
		shared_ptr<IfcPPEntity> attribute_entity = dynamic_pointer_cast<IfcPPEntity>( attribute );
		if( attribute_entity )
		{
			if( target_map.count( attribute_entity.get() ) == 0 )
			{
				target_map[attribute_entity.get()] = attribute_entity;
				collectDependentEntities( attribute_entity, target_map );
			}
			continue;
		}

		auto attribute_object_vector = dynamic_pointer_cast<IfcPPAttributeObjectVector>( attribute );
		if( attribute_object_vector )
		{
			std::vector<shared_ptr<IfcPPObject> >& vec_of_attributes = attribute_object_vector->m_vec;

			for( size_t jj = 0; jj < vec_of_attributes.size(); ++jj )
			{
				shared_ptr<IfcPPObject>& attribute_object = vec_of_attributes[jj];

				auto attribute_entity = dynamic_pointer_cast<IfcPPEntity>( attribute_object );
				if( attribute_entity )
				{
					if( target_map.count( attribute_entity.get() ) == 0 )
					{
						target_map[attribute_entity.get()] = attribute_entity;
						collectDependentEntities( attribute_entity, target_map );
					}
				}
			}
		}
	}

	if( target_map.count( entity.get() ) == 0 )
	{
		target_map[entity.get()] = entity;
	}
}
Esempio n. 7
0
/**
 * Create a VG grpah from a pinch thread set.
 */
vg::VG pinchToVG(stPinchThreadSet* threadSet, std::map<int64_t, std::string>& threadSequences) {
    // Make an empty graph
    vg::VG graph;
    
    // Remember what nodes have been created for what segments. Only the first
    // segment in a block (the "leader") gets a node. Segments without blocks
    // are also themselves leaders and get nodes.
    std::map<stPinchSegment*, vg::Node*> nodeForLeader;
    
    std::cerr << "Making pinch graph into vg graph with " << threadSequences.size() << " relevant threads" << std::endl;
    
    // This is the cleverest way to loop over Benedict's iterators.
    auto segmentIterator = stPinchThreadSet_getSegmentIt(threadSet);
    while(auto segment = stPinchThreadSetSegmentIt_getNext(&segmentIterator)) {
        // For every segment, we need to make a VG node for it or its block (if
        // it has one).
        
#ifdef debug
        std::cerr << "Found segment " << segment << std::endl;
#endif
        
        // See if the segment is in a block
        auto block = stPinchSegment_getBlock(segment);
        
        // Get the leader segment: first in the block, or this segment if no block
        auto leader = getLeader(segment);
        
        if(nodeForLeader.count(leader)) {
            // A node has already been made for this block.
            continue;
        }
        
        // Otherwise, we need the sequence
        std::string sequence;
        
        if(block) {
            // Get the sequence by scanning through the block for the first sequence
            // that isn't all Ns, if any.
            auto segmentIterator = stPinchBlock_getSegmentIterator(block);
            while(auto sequenceSegment = stPinchBlockIt_getNext(&segmentIterator)) {
                if(!threadSequences.count(stPinchSegment_getName(sequenceSegment))) {
                    // This segment is part of a staple. Pass it up
                    continue;
                }
                
                // Go get the sequence of the thread, and clip out the part relevant to this segment.
                sequence = threadSequences.at(stPinchSegment_getName(sequenceSegment)).substr(
                    stPinchSegment_getStart(sequenceSegment), stPinchSegment_getLength(sequenceSegment));
                    
                // If necessary, flip the segment around
                if(getOrientation(sequenceSegment)) {
                    sequence = vg::reverse_complement(sequence);
                }
                
                if(std::count(sequence.begin(), sequence.end(), 'N') +
                    std::count(sequence.begin(), sequence.end(), 'n') < sequence.size()) {\
                    
                    // The sequence has some non-N characters
                    // If it's not all Ns, break
                    break;
                }
                
                // Otherwise try the next segment
            }
        } else {
            // Just pull the sequence from the lone segment
            sequence = threadSequences.at(stPinchSegment_getName(segment)).substr(
                stPinchSegment_getStart(segment), stPinchSegment_getLength(segment));
                
            // It doesn't need to flip, since it can't be backwards in a block
        }
        
            
        // Make a node in the graph to represent the block
        vg::Node* node = graph.create_node(sequence);
        
        // Remember it
        nodeForLeader[leader] = node;
#ifdef debug
        std::cerr << "Made node: " << pb2json(*node) << std::endl;
#endif
            
    }
    
    // Now go through the segments again and wire them up.
    segmentIterator = stPinchThreadSet_getSegmentIt(threadSet);
    while(auto segment = stPinchThreadSetSegmentIt_getNext(&segmentIterator)) {
        // See if the segment is in a block
        auto block = stPinchSegment_getBlock(segment);
        
        // Get the leader segment: first in the block, or this segment if no block
        auto leader = getLeader(segment);
        
        // We know we have a node already
        auto node = nodeForLeader.at(leader);
        
        // What orientation is this node in for the purposes of this edge
        // TODO: ought to always be false if the segment isn't in a block. Is this true?
        auto orientation = getOrientation(segment);
#ifdef debug
        std::cerr << "Revisited segment: " << segment << " for node " << node->id() <<
            " in orientation " << (orientation ? "reverse" : "forward") << std::endl;
#endif
        
        // Look at the segment 5' of here. We know it's not a staple and
        // thus has a vg node.
        auto prevSegment = stPinchSegment_get5Prime(segment);
        
        if(prevSegment) {
            // Get the node IDs and orientations
            auto prevNode = nodeForLeader.at(getLeader(prevSegment));
            auto prevOrientation = getOrientation(prevSegment);
#ifdef debug
            std::cerr << "Found prev node " << prevNode->id() << " in orientation " << 
                (prevOrientation ? "reverse" : "forward") << std::endl;
#endif
            
            // Make an edge
            vg::Edge prevEdge;
            prevEdge.set_from(prevNode->id());
            prevEdge.set_from_start(prevOrientation);
            prevEdge.set_to(node->id());
            prevEdge.set_to_end(orientation);
            
            // Add it in. vg::VG deduplicates for us
            graph.add_edge(prevEdge);
#ifdef debug
            std::cerr << "Made edge: " << pb2json(prevEdge) << std::endl;
#endif
        }
        
        // Now do the same thing for the 3' side
        auto nextSegment = stPinchSegment_get3Prime(segment);
        
        if(nextSegment) {
            // Get the node IDs and orientations
            auto nextNode = nodeForLeader.at(getLeader(nextSegment));
            auto nextOrientation = getOrientation(nextSegment);
#ifdef debug
            std::cerr << "Found next node " << nextNode->id() << " in orientation " << 
                (nextOrientation ? "reverse" : "forward") << std::endl;
#endif
            
            // Make an edge
            vg::Edge nextEdge;
            nextEdge.set_from(node->id());
            nextEdge.set_from_start(orientation);
            nextEdge.set_to(nextNode->id());
            nextEdge.set_to_end(nextOrientation);
            
            // Add it in. vg::VG deduplicates for us
            graph.add_edge(nextEdge);
#ifdef debug
            std::cerr << "Made edge: " << pb2json(nextEdge) << std::endl;
#endif
        }
    }
    
    // Spit out the graph.
    return graph;

}
Esempio n. 8
0
bool kernel::select_block_from_candidates(
    std::vector<std::pair<std::int64_t, sha256> > & sorted_by_timestamp,
    std::map<sha256, block_index *> & selected_blocks,
    const std::int64_t & selection_interval_stop,
    const std::uint64_t & previous_stake_modifier,
    const block_index ** index_selected
    )
{
    bool selected = false;
    
    sha256 hash_best = 0;
    
    *index_selected = 0;
    
    for (auto & item : sorted_by_timestamp)
    {
        if (globals::instance().block_indexes().count(item.second) == 0)
        {
            log_error(
                "Kernel, select block from candidates failed to find block "
                "index for candidate block " << item.second.to_string() << "."
            );
            
            return false;
        }
        
        const auto & index = globals::instance().block_indexes()[item.second];
        
        if (selected && index->time() > selection_interval_stop)
        {
            break;
        }
        
        if (selected_blocks.count(index->get_block_hash()) > 0)
        {
            continue;
        }
        
        /*
         * Compute the selection hash by hashing its proof-hash and the
         * previous proof-of-stake modifier.
         */
        sha256 hash_proof =
            index->is_proof_of_stake() ?
            index->hash_proof_of_stake() : index->get_block_hash()
        ;
        
        /**
         * Allocate the buffer to calculate the hash of the
         * selection.
         */
        data_buffer buffer;
        
        /**
         * Write the hash of the proof.
         */
        buffer.write_sha256(hash_proof);
        
        /**
         * Write the previous stake modifier.
         */
        buffer.write_uint64(previous_stake_modifier);
        
        /**
         * Calculate the sha256d hash of the hash of the proof and
         * the previous stake modifier.
         */
        auto hash_selection = sha256::from_digest(&hash::sha256d(
            reinterpret_cast<std::uint8_t *>(buffer.data()),
            buffer.size())[0]
        );

        /**
         * Divide by 2**32 so that Proof-of-Stake blocks are favored over
         * Proof-of-Work blocks.
         */
        if (index->is_proof_of_stake())
        {
            hash_selection >>= 32;
        }
        
        if (selected && hash_selection < hash_best)
        {
            hash_best = hash_selection;
            
            *index_selected = reinterpret_cast<const block_index *> (index);
        }
        else if (selected == false)
        {
            selected = true;
            
            hash_best = hash_selection;
            
            *index_selected = reinterpret_cast<const block_index *> (index);
        }
    }
Esempio n. 9
0
 bool has_map_type(const std::string& map_type_name) const {
     return m_callbacks.count(map_type_name) != 0;
 }
Esempio n. 10
0
void WorldServer::Process(){
	WorldConnection::Process();
	if (!Connected())
		return;

	ServerPacket *pack = nullptr;
	while((pack = tcpc.PopPacket())){
		Log.Out(Logs::General, Logs::Netcode, "Received Opcode: %4X", pack->opcode);
		//DumpPacket(pack);
		switch(pack->opcode) {
			case 0: { break; }
			case ServerOP_KeepAlive: { break; }
			case ServerOP_WIRemoteCallResponse: {
				char *id = nullptr;
				char *session_id = nullptr;
				char *error = nullptr;

				id = new char[pack->ReadUInt32() + 1];
				pack->ReadString(id);

				session_id = new char[pack->ReadUInt32() + 1];
				pack->ReadString(session_id);

				error = new char[pack->ReadUInt32() + 1];
				pack->ReadString(error);

				uint32 param_count = pack->ReadUInt32();
				std::map<std::string, std::string> params;
				for(uint32 i = 0; i < param_count; ++i) {
					char *first = new char[pack->ReadUInt32() + 1];
					pack->ReadString(first);

					char *second = new char[pack->ReadUInt32() + 1];
					pack->ReadString(second);

					params[first] = second;

					safe_delete_array(first);
					safe_delete_array(second);
				}

				//send the response to client...
				rapidjson::StringBuffer s;
				rapidjson::Writer<rapidjson::StringBuffer> writer(s);

				writer.StartObject();
				writer.String("id");
				if(strlen(id) == 0) {
					writer.Null();
				} else {
					writer.String(id);
				}

				if(strlen(error) != 0) {
					writer.String("error");
					writer.Bool(true);

					writer.String("result");
					writer.String(error);
				} else {
					writer.String("error");
					writer.Null();
					writer.String("result");
					writer.StartObject();
					auto iter = params.begin();
					while(iter != params.end()) {
						writer.String(iter->first.c_str());
						writer.String(iter->second.c_str());
						++iter;
					}
					writer.EndObject();
				}
				writer.EndObject();

				if(sessions.count(session_id) != 0) {
					per_session_data_eqemu *session = sessions[session_id];
					session->send_queue->push_back(s.GetString());
				}

				safe_delete_array(id);
				safe_delete_array(session_id);
				safe_delete_array(error);
				break;
			}

			case ServerOP_WIRemoteCallToClient:
			{
				char *session_id = nullptr;
				char *method = nullptr;

				session_id = new char[pack->ReadUInt32() + 1];
				pack->ReadString(session_id);

				method = new char[pack->ReadUInt32() + 1];
				pack->ReadString(method);

				uint32 param_count = pack->ReadUInt32();
				std::vector<std::string> params(param_count);
				for(uint32 i = 0; i < param_count; ++i) {
					char *p = new char[pack->ReadUInt32() + 1];
					pack->ReadString(p);
					params[i] = p;

					safe_delete_array(p);
				}

				rapidjson::StringBuffer s;
				rapidjson::Writer<rapidjson::StringBuffer> writer(s);

				writer.StartObject();
				writer.String("id");
				writer.Null();

				writer.String("method");
				writer.String(method);

				writer.String("params");
				writer.StartArray();

				for(uint32 i = 0; i < param_count; ++i) {
					writer.String(params[i].c_str());
				}

				writer.EndArray();
				
				writer.EndObject();

				if(sessions.count(session_id) != 0) {
					per_session_data_eqemu *session = sessions[session_id];
					session->send_queue->push_back(s.GetString());
				}

				safe_delete_array(session_id);
				safe_delete_array(method);
				break;
			}

			case ServerOP_WIRemoteOpcodeToClient:
			{
				char *session_id = nullptr;
				session_id = new char[pack->ReadUInt32() + 1];
				pack->ReadString(session_id);

				char *method = nullptr;
				method = new char[pack->ReadUInt32() + 1];
				pack->ReadString(method);


				uint32 zone_id = pack->ReadUInt32();
				uint32 instance_id = pack->ReadUInt32();
				uint32 opcode = pack->ReadUInt32();
				uint32 datasize = pack->ReadUInt32();
				char *p = new char[datasize];
				pack->ReadData(p, datasize);
				rapidjson::StringBuffer s;
				rapidjson::Writer<rapidjson::StringBuffer> writer(s);

				writer.StartObject();
				writer.String("id");
				writer.Null();

				writer.String("method");
				writer.String(method);

				writer.String("zoneid");
				writer.Uint(zone_id);

				writer.String("instance_id");
				writer.Uint(instance_id);

				writer.String("opcode");
				writer.Uint(opcode);
				writer.String("datasize");
				writer.Uint(datasize);

				std::string enc;
				Base64::encode(p, datasize, enc, false);


				writer.String("data");
				writer.String(enc.c_str());

				writer.EndObject();

				if(sessions.count(session_id) != 0) {
					per_session_data_eqemu *session = sessions[session_id];
					session->send_queue->push_back(s.GetString());
				}

				safe_delete_array(session_id);
				safe_delete_array(method);
				safe_delete_array(p);

				break;
			}
		}
	}

	safe_delete(pack);
	return;
}
bool string_id<requirement_data>::is_valid() const
{
    return requirements_all.count( *this );
}
Esempio n. 12
0
static tree
build_common_decl (gfc_common_head *com, tree union_type, bool is_init)
{
  tree decl, identifier;

  identifier = gfc_sym_mangled_common_id (com);
  decl = gfc_map_of_all_commons.count(identifier)
	 ? gfc_map_of_all_commons[identifier] : NULL_TREE;

  /* Update the size of this common block as needed.  */
  if (decl != NULL_TREE)
    {
      tree size = TYPE_SIZE_UNIT (union_type);

      /* Named common blocks of the same name shall be of the same size
	 in all scoping units of a program in which they appear, but
	 blank common blocks may be of different sizes.  */
      if (!tree_int_cst_equal (DECL_SIZE_UNIT (decl), size)
	  && strcmp (com->name, BLANK_COMMON_NAME))
	gfc_warning ("Named COMMON block '%s' at %L shall be of the "
		     "same size as elsewhere (%lu vs %lu bytes)", com->name,
		     &com->where,
		     (unsigned long) TREE_INT_CST_LOW (size),
		     (unsigned long) TREE_INT_CST_LOW (DECL_SIZE_UNIT (decl)));

      if (tree_int_cst_lt (DECL_SIZE_UNIT (decl), size))
	{
	  DECL_SIZE (decl) = TYPE_SIZE (union_type);
	  DECL_SIZE_UNIT (decl) = size;
	  DECL_MODE (decl) = TYPE_MODE (union_type);
	  TREE_TYPE (decl) = union_type;
	  layout_decl (decl, 0);
	}
     }

  /* If this common block has been declared in a previous program unit,
     and either it is already initialized or there is no new initialization
     for it, just return.  */
  if ((decl != NULL_TREE) && (!is_init || DECL_INITIAL (decl)))
    return decl;

  /* If there is no backend_decl for the common block, build it.  */
  if (decl == NULL_TREE)
    {
      if (com->is_bind_c == 1 && com->binding_label)
	decl = build_decl (input_location, VAR_DECL, identifier, union_type);
      else
	{
	  decl = build_decl (input_location, VAR_DECL, get_identifier (com->name),
			     union_type);
	  gfc_set_decl_assembler_name (decl, identifier);
	}

      TREE_PUBLIC (decl) = 1;
      TREE_STATIC (decl) = 1;
      DECL_IGNORED_P (decl) = 1;
      if (!com->is_bind_c)
	DECL_ALIGN (decl) = BIGGEST_ALIGNMENT;
      else
        {
	  /* Do not set the alignment for bind(c) common blocks to
	     BIGGEST_ALIGNMENT because that won't match what C does.  Also,
	     for common blocks with one element, the alignment must be
	     that of the field within the common block in order to match
	     what C will do.  */
	  tree field = NULL_TREE;
	  field = TYPE_FIELDS (TREE_TYPE (decl));
	  if (DECL_CHAIN (field) == NULL_TREE)
	    DECL_ALIGN (decl) = TYPE_ALIGN (TREE_TYPE (field));
	}
      DECL_USER_ALIGN (decl) = 0;
      GFC_DECL_COMMON_OR_EQUIV (decl) = 1;

      gfc_set_decl_location (decl, &com->where);

      if (com->threadprivate)
	DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);

      /* Place the back end declaration for this common block in
         GLOBAL_BINDING_LEVEL.  */
      gfc_map_of_all_commons[identifier] = pushdecl_top_level (decl);
    }

  /* Has no initial values.  */
  if (!is_init)
    {
      DECL_INITIAL (decl) = NULL_TREE;
      DECL_COMMON (decl) = 1;
      DECL_DEFER_OUTPUT (decl) = 1;
    }
  else
    {
      DECL_INITIAL (decl) = error_mark_node;
      DECL_COMMON (decl) = 0;
      DECL_DEFER_OUTPUT (decl) = 0;
    }
  return decl;
}
Esempio n. 13
0
bool ZoneDatabase::LoadTributes() {
	char errbuf[MYSQL_ERRMSG_SIZE];
	MYSQL_RES *result;
	MYSQL_ROW row;

	TributeData t;
	memset(&t.tiers, 0, sizeof(t.tiers));
	t.tier_count = 0;

	tribute_list.clear();

	const char *query = "SELECT id,name,descr,unknown,isguild FROM tributes";
	if (RunQuery(query, strlen(query), errbuf, &result)) {
		int r;
		while ((row = mysql_fetch_row(result))) {
			r = 0;
			uint32 id = atoul(row[r++]);
			t.name = row[r++];
			t.description = row[r++];
			t.unknown = strtoul(row[r++], nullptr, 10);
			t.is_guild = atol(row[r++])==0?false:true;

			tribute_list[id] = t;
		}
		mysql_free_result(result);
	} else {
		LogFile->write(EQEMuLog::Error, "Error in LoadTributes first query '%s': %s", query, errbuf);
		return false;
	}


	const char *query2 = "SELECT tribute_id,level,cost,item_id FROM tribute_levels ORDER BY tribute_id,level";
	if (RunQuery(query2, strlen(query2), errbuf, &result)) {
		int r;
		while ((row = mysql_fetch_row(result))) {
			r = 0;
			uint32 id = atoul(row[r++]);

			if(tribute_list.count(id) != 1) {
				LogFile->write(EQEMuLog::Error, "Error in LoadTributes: unknown tribute %lu in tribute_levels", (unsigned long)id);
				continue;
			}

			TributeData &cur = tribute_list[id];

			if(cur.tier_count >= MAX_TRIBUTE_TIERS) {
				LogFile->write(EQEMuLog::Error, "Error in LoadTributes: on tribute %lu: more tiers defined than permitted", (unsigned long)id);
				continue;
			}

			TributeLevel_Struct &s = cur.tiers[cur.tier_count];

			s.level = atoul(row[r++]);
			s.cost = atoul(row[r++]);
			s.tribute_item_id = atoul(row[r++]);
			cur.tier_count++;
		}
		mysql_free_result(result);
	} else {
		LogFile->write(EQEMuLog::Error, "Error in LoadTributes level query '%s': %s", query, errbuf);
		return false;
	}

	return true;
}
Esempio n. 14
0
bool transaction::connect_inputs(
    db_tx & tx_db,
    std::map<sha256, std::pair<transaction_index, transaction> > & inputs,
    std::map<sha256, transaction_index> & test_pool,
    const transaction_position & position_tx_this,
    const block_index * ptr_block_index,
    const bool & connect_block, const bool & create_new_block,
    const bool & strict_pay_to_script_hash, const bool & check_signature,
    std::vector<script_checker> * script_checker_checks
    )
{
    if (is_coin_base() == false)
    {
        std::int64_t value_in = 0;
        std::int64_t fees = 0;
        
        for (auto i = 0; i < m_transactions_in.size(); i++)
        {
            auto & prev_out = m_transactions_in[i].previous_out();
            
            assert(inputs.count(prev_out.get_hash()) > 0);
            
            auto & tx_index = inputs[prev_out.get_hash()].first;
            
            auto & tx_previous = inputs[prev_out.get_hash()].second;

            if (
                prev_out.n() >= tx_previous.transactions_out().size() ||
                prev_out.n() >= tx_index.spent().size()
                )
            {
                log_error(
                    "Transaction connect inputs failed, " <<
                    get_hash().to_string().substr(0, 10) <<
                    " previous out n is out of range [" << prev_out.n() <<
                    "-" << tx_previous.transactions_out().size() << "]" <<
                    " previous transaction " <<
                    prev_out.get_hash().to_string() << "\n" <<
                    tx_previous.to_string()
                );
                
                return false;
            }
            
            /**
             * If previous is coinbase or coinstake, check that it's matured.
             */
            if (tx_previous.is_coin_base() || tx_previous.is_coin_stake())
            {
                for (
                    auto pindex = ptr_block_index;
                    pindex && ptr_block_index->height() - pindex->height() <
                    (constants::test_net ?
                    static_cast<std::int32_t> (constants::coinbase_maturity_test_network) :
                    static_cast<std::int32_t> (constants::coinbase_maturity));
                    pindex = pindex->block_index_previous()
                    )
                {
                    if (
                        pindex->block_position() ==
                        tx_index.get_transaction_position().block_position() &&
                        pindex->file() ==
                        tx_index.get_transaction_position().file_index()
                        )
                    {
                        log_error(
                            "Transaction connect inputs failed, tried to "
                            "spend " << (tx_previous.is_coin_base() ?
                            "coinbase" : "coinstake") << " at depth " <<
                            pindex->height() << "."
                        );
                        
                        return false;
                    }
                }
            }
            
            /**
             * Check the transaction timestamp (ppcoin).
             */
            if (tx_previous.time() > m_time)
            {
                log_error(
                    "Transaction connect inputs failed, timestamp is earlier "
                    "than the input transaction."
                );
                
                return false;
            }
            
            /**
             * Check for negative or overflow input values.
             */
            value_in += tx_previous.transactions_out()[prev_out.n()].value();
            
            if (
                utility::money_range(
                tx_previous.transactions_out()[prev_out.n()].value()) == false ||
                utility::money_range(value_in) == false
                )
            {
                log_error(
                    "Transaction connect inputs failed, transaction in "
                    "values out of range."
                );
                
                return false;
            }

        }
        
        /**
         * Reserve memory for the script_checker's.
         */
        if (script_checker_checks)
        {
            script_checker_checks->reserve(m_transactions_in.size());
        }
        
        /**
         * Only if all inputs pass do we perform expensive ECDSA signature
         * checks. This may help prevent CPU exhaustion attacks.
         */
        for (auto i = 0; i < m_transactions_in.size(); i++)
        {
            auto & prev_out = m_transactions_in[i].previous_out();
            
            assert(inputs.count(prev_out.get_hash()) > 0);
            
            auto & tx_index = inputs[prev_out.get_hash()].first;
            
            auto & tx_previous = inputs[prev_out.get_hash()].second;

            /**
             * Check for conflicts (double-spend).
             */
            if (tx_index.spent()[prev_out.n()].is_null() == false)
            {
                if (create_new_block)
                {
                    return false;
                }
                else
                {
                    log_debug(
                        "Transaction connect inputs failed, " <<
                        get_hash().to_string().substr(0, 10) <<
                        " previous transaction already used at " <<
                        tx_index.spent()[prev_out.n()].to_string() << "."
                    );
                    
                    return false;
                }
            }
            
            /**
             * Skip ECDSA signature verification when connecting blocks before
             * the last blockchain checkpoint. This is safe because block
             * merkle hashes are  still computed and checked, and any change
             * will be caught at the next checkpoint.
             */
            if (
                (connect_block && (globals::instance().best_block_height() <
                checkpoints::instance().get_total_blocks_estimate())) == false
                )
            {
                if (check_signature == true)
                {
                    /**
                     * Allocate the script_checker.
                     */
                    script_checker checker(
                        tx_previous, *this, i, strict_pay_to_script_hash, 0
                    );
                    
                    /**
                     * If we were passsed a script_checker array use it.
                     */
                    if (script_checker_checks)
                    {
                        script_checker_checks->push_back(checker);
                    }
                    else if (checker.check() == false)
                    {
                        if (strict_pay_to_script_hash == true)
                        {
                            /**
                             * Allocate the script_checker.
                             */
                            script_checker checker(
                                tx_previous, *this, i, false, 0
                            );
                    
                            /**
                             * Only during transition phase for P2SH.
                             * @note true means failure here.
                             */
                            if (checker.check() == true)
                            {
                                log_error(
                                    "Transaction connect inputs failed, " <<
                                    get_hash().to_string().substr(0, 10) <<
                                    " P2SH signature verification vailed."
                                );
                                
                                return false;
                            }
                        }

                        log_error(
                            "Transaction connect inputs failed, " <<
                            get_hash().to_string().substr(0, 10) <<
                            " signature verification failed."
                        );
                        
                        return false;
                    }
                }
            }

            /**
             * Mark outpoints as spent.
             */
            tx_index.spent()[prev_out.n()] = position_tx_this;

            /**
             * Write back.
             */
            if (connect_block || create_new_block)
            {
                test_pool[prev_out.get_hash()] = tx_index;
            }
        }

        if (is_coin_stake())
        {
            /**
             * Coin stake transactions earn reward instead of paying fee
             * (ppcoin).
             */
            std::uint64_t coin_age;
            
            if (get_coin_age(tx_db, coin_age) == false)
            {
                log_error(
                    "Transaction connect inputs failed, " <<
                    get_hash().to_string().substr(0, 10) << " unable to get " <<
                    "coin age for coin stake."
                );
                
                return false;
            }
            
            std::int64_t stake_reward = get_value_out() - value_in;
            
            if (
                stake_reward > reward::get_proof_of_stake(coin_age,
                ptr_block_index->bits(), m_time, ptr_block_index->height()) -
                get_minimum_fee() + constants::min_tx_fee
                )
            {
                log_error(
                    "Transaction connect inputs failed, " <<
                    get_hash().to_string().substr(0, 10) <<
                    " stake reward exceeded."
                );
                
                return false;
            }
        }
        else
        {
            if (value_in < get_value_out())
            {
                log_error(
                    "Transaction connect inputs failed, " <<
                    get_hash().to_string().substr(0, 10) <<
                    " value in is less than value out."
                );
                
                return false;
            }
        }
    }

    return true;
}
void ProcessMessageInstantX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if(fLiteMode) return; //disable all sandstorm/stormnode related functionality
    if(!IsSporkActive(SPORK_2_INSTANTX)) return;
    if(!stormnodeSync.IsBlockchainSynced()) return;

    if (strCommand == "ix")
    {
        //LogPrintf("ProcessMessageInstantX::ix\n");
        CDataStream vMsg(vRecv);
        CTransaction tx;
        vRecv >> tx;

        CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
        pfrom->AddInventoryKnown(inv);

        if(mapTxLockReq.count(tx.GetHash()) || mapTxLockReqRejected.count(tx.GetHash())){
            return;
        }

        if(!IsIXTXValid(tx)){
            return;
        }

        BOOST_FOREACH(const CTxOut o, tx.vout){
            // IX supports normal scripts and unspendable scripts (used in SS collateral and Budget collateral).
            // TODO: Look into other script types that are normal and can be included
            if(!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()){
                LogPrintf("ProcessMessageInstantX::ix - Invalid Script %s\n", tx.ToString().c_str());
                return;
            }
        }

        int nBlockHeight = CreateNewLock(tx);

        bool fMissingInputs = false;
        //CValidationState state;

        bool fAccepted = false;
        {
            LOCK(cs_main);
            //TODO (Amir): Pass state to AcceptToMemoryPool
            fAccepted = AcceptToMemoryPool(mempool, tx, true, &fMissingInputs);
        }
        if (fAccepted)
        {
            RelayInv(inv);

            DoConsensusVote(tx, nBlockHeight);

            mapTxLockReq.insert(make_pair(tx.GetHash(), tx));

            LogPrintf("ProcessMessageInstantX::ix - Transaction Lock Request: %s %s : accepted %s\n",
                pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
                tx.GetHash().ToString().c_str()
            );

            return;

        } else {
            mapTxLockReqRejected.insert(make_pair(tx.GetHash(), tx));

            // can we get the conflicting transaction as proof?

            LogPrintf("ProcessMessageInstantX::ix - Transaction Lock Request: %s %s : rejected %s\n",
                pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
                tx.GetHash().ToString().c_str()
            );

            BOOST_FOREACH(const CTxIn& in, tx.vin){
                if(!mapLockedInputs.count(in.prevout)){
                    mapLockedInputs.insert(make_pair(in.prevout, tx.GetHash()));
                }
            }

            // resolve conflicts
            std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(tx.GetHash());
            if (i != mapTxLocks.end()){
                //we only care if we have a complete tx lock
                if((*i).second.CountSignatures() >= INSTANTX_SIGNATURES_REQUIRED){
                    if(!CheckForConflictingLocks(tx)){
                        LogPrintf("ProcessMessageInstantX::ix - Found Existing Complete IX Lock\n");

                        //reprocess the last 15 blocks
                        ReprocessBlocks(15);
                        mapTxLockReq.insert(make_pair(tx.GetHash(), tx));
                    }
                }
            }

            return;
        }
    }
Esempio n. 16
0
 /// Check if a grid function is part of the collection
 bool HasField(const char *name) {
     return field_map.count(name) == 1;
 }
Esempio n. 17
0
void Client::DoTributeUpdate() {
	EQApplicationPacket outapp(OP_TributeUpdate, sizeof(TributeInfo_Struct));
	TributeInfo_Struct *tis = (TributeInfo_Struct *) outapp.pBuffer;

	tis->active = m_pp.tribute_active ? 1 : 0;
	tis->tribute_master_id = tribute_master_id;	//Dont know what this is for

	int r;
	for (r = 0; r < EQEmu::legacy::TRIBUTE_SIZE; r++) {
		if(m_pp.tributes[r].tribute != TRIBUTE_NONE) {
			tis->tributes[r] = m_pp.tributes[r].tribute;
			tis->tiers[r] = m_pp.tributes[r].tier;
		} else {
			tis->tributes[r] = TRIBUTE_NONE;
			tis->tiers[r] = 0;
		}
	}
	QueuePacket(&outapp);

	SendTributeTimer();

	if(m_pp.tribute_active) {
		//send and equip tribute items...
		for (r = 0; r < EQEmu::legacy::TRIBUTE_SIZE; r++) {
			uint32 tid = m_pp.tributes[r].tribute;
			if(tid == TRIBUTE_NONE) {
				if (m_inv[EQEmu::legacy::TRIBUTE_BEGIN + r])
					DeleteItemInInventory(EQEmu::legacy::TRIBUTE_BEGIN + r, 0, false);
				continue;
			}

			if(tribute_list.count(tid) != 1) {
				if (m_inv[EQEmu::legacy::TRIBUTE_BEGIN + r])
					DeleteItemInInventory(EQEmu::legacy::TRIBUTE_BEGIN + r, 0, false);
				continue;
			}

			//sanity check
			if(m_pp.tributes[r].tier >= MAX_TRIBUTE_TIERS) {
				if (m_inv[EQEmu::legacy::TRIBUTE_BEGIN + r])
					DeleteItemInInventory(EQEmu::legacy::TRIBUTE_BEGIN + r, 0, false);
				m_pp.tributes[r].tier = 0;
				continue;
			}

			TributeData &d = tribute_list[tid];
			TributeLevel_Struct &tier = d.tiers[m_pp.tributes[r].tier];
			uint32 item_id = tier.tribute_item_id;

			//summon the item for them
			const ItemInst* inst = database.CreateItem(item_id, 1);
			if(inst == nullptr)
				continue;

			PutItemInInventory(EQEmu::legacy::TRIBUTE_BEGIN + r, *inst, false);
			SendItemPacket(EQEmu::legacy::TRIBUTE_BEGIN + r, inst, ItemPacketTributeItem);
			safe_delete(inst);
		}
	} else {
		//unequip tribute items...
		for (r = 0; r < EQEmu::legacy::TRIBUTE_SIZE; r++) {
			if (m_inv[EQEmu::legacy::TRIBUTE_BEGIN + r])
				DeleteItemInInventory(EQEmu::legacy::TRIBUTE_BEGIN + r, 0, false);
		}
	}
	CalcBonuses();
}
Esempio n. 18
0
	int input_evdev_init(EvdevController* controller, const char* device, const char* custom_mapping_fname = NULL)
	{
		load_libevdev();

		char name[256] = "Unknown";

		printf("evdev: Trying to open device at '%s'\n", device);

		int fd = open(device, O_RDWR);

		if (fd >= 0)
		{
			fcntl(fd, F_SETFL, O_NONBLOCK);
			if(ioctl(fd, EVIOCGNAME(sizeof(name)), name) < 0)
			{
				perror("evdev: ioctl");
				return -2;
			}
			else
			{
				printf("evdev: Found '%s' at '%s'\n", name, device);

				controller->fd = fd;

				const char* mapping_fname;

				if(custom_mapping_fname != NULL)
				{
					mapping_fname = custom_mapping_fname;
				}
				else
				{
					#if defined(TARGET_PANDORA)
						mapping_fname = "controller_pandora.cfg";
					#elif defined(TARGET_GCW0)
						mapping_fname = "controller_gcwz.cfg";
					#else
						if (strcmp(name, "Microsoft X-Box 360 pad") == 0 ||
							strcmp(name, "Xbox 360 Wireless Receiver") == 0 ||
							strcmp(name, "Xbox 360 Wireless Receiver (XBOX)") == 0)
						{
							mapping_fname = "controller_xpad.cfg";
						}
						else if (strstr(name, "Xbox Gamepad (userspace driver)") != NULL)
						{
							mapping_fname = "controller_xboxdrv.cfg";
						}
						else if (strstr(name, "keyboard") != NULL ||
								 strstr(name, "Keyboard") != NULL)
						{
							mapping_fname = "keyboard.cfg";
						}
						else
						{
							mapping_fname = "controller_generic.cfg";
						}
					#endif
				}
				if(loaded_mappings.count(string(mapping_fname)) == 0)
				{
					FILE* mapping_fd = NULL;
					if(mapping_fname[0] == '/')
					{
						// Absolute mapping
						mapping_fd = fopen(mapping_fname, "r");
					}
					else
					{
						// Mapping from ~/.reicast/mappings/
						size_t size_needed = snprintf(NULL, 0, EVDEV_MAPPING_PATH, mapping_fname) + 1;
						char* mapping_path = (char*)malloc(size_needed);
						sprintf(mapping_path, EVDEV_MAPPING_PATH, mapping_fname);
						mapping_fd = fopen(get_readonly_data_path(mapping_path).c_str(), "r");
						free(mapping_path);
					}
					
					if(mapping_fd != NULL)
					{
						printf("evdev: reading mapping file: '%s'\n", mapping_fname);
						loaded_mappings.insert(std::make_pair(string(mapping_fname), load_mapping(mapping_fd)));
						fclose(mapping_fd);

					}
					else
					{
						printf("evdev: unable to open mapping file '%s'\n", mapping_fname);
						perror("evdev");
						return -3;
					}
				}
				controller->mapping = &loaded_mappings.find(string(mapping_fname))->second;
				printf("evdev: Using '%s' mapping\n", controller->mapping->name);
				controller->init();

				return 0;
			}
		}
		else
		{
			perror("evdev: open");
			return -1;
		}
	}
Esempio n. 19
0
static void KMCount(const char *s)
{
    Kmer::k = 31;
    KmerIterator iter(s), end;
    
    // Number of k-mers that are sequins
    unsigned isSeq = 0;
    
    // Number of k-mers that are genome
    unsigned isGen = 0;
    
    for (int i = 0; iter != end; ++i, ++iter)
    {
        auto k = iter->first.rep().toString();
        
        /*
         * Does the k-mer span sequin variants?
         */
        
        if (__span__.count(k))
        {
            __span__[k]++;
        }

        /*
         * Is this one of the reference k-mers?
         */
        
        if (__all__.count(k))
        {
            std::vector<std::pair<KmerEntry, int> > v;
            __seqsIndex__->match(k.c_str(), 31, v);
            
            if (v.empty())
            {
                assert(false);
            }
            else
            {
               // std::cout << "GOOD" << std::endl;
            }
            
            __all__[k]++;
            isSeq++;
        }
        else
        {
            isGen++;
        }

#ifdef DEBUG
        __debug__[k]++;
#endif
    }
    
    if (isSeq > isGen)
    {
        __nSeq__++;
    }
    else
    {
        __nGen__++;
    }
}
Esempio n. 20
0
// Turns LLL tree into tree of code fragments
programData opcodeify(Node node,
                      programAux aux=Aux(),
                      int height=0,
                      std::map<std::string, int> dupvars=
                          std::map<std::string, int>()) {
    std::string symb = "_"+mkUniqueToken();
    Metadata m = node.metadata;
    // Numbers
    if (node.type == TOKEN) {
        return pd(aux, nodeToNumeric(node), 1);
    }
    else if (node.val == "ref" || node.val == "get" || node.val == "set") {
        std::string varname = node.args[0].val;
        if (!aux.vars.count(varname)) {
            aux.vars[varname] = unsignedToDecimal(aux.vars.size() * 32);
        }
        std::cout << aux.vars[varname] << " " << varname << " " << node.val << "\n";
        if (varname == "'msg.data") aux.calldataUsed = true;
        // Set variable
        if (node.val == "set") {
            programData sub = opcodeify(node.args[1], aux, height, dupvars);
            if (!sub.outs)
                err("Value to set variable must have nonzero arity!", m);
            if (dupvars.count(node.args[0].val)) {
                int h = height - dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                Node nodelist[] = {
                    sub.code,
                    token("SWAP"+unsignedToDecimal(h), m),
                    token("POP", m)
                };
                return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
            }
            Node nodelist[] = {
                sub.code,
                token(sub.aux.vars[varname], m),
                token("MSTORE", m),
            };
            return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
        }
        // Get variable
        else if (node.val == "get") {
             if (dupvars.count(node.args[0].val)) {
                 int h = height - dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                return pd(aux, token("DUP"+unsignedToDecimal(h)), 1);                   
            }
            Node nodelist[] = 
                 { token(aux.vars[varname], m), token("MLOAD", m) };
            std::cout << "<--- " << aux.vars[varname] << " " << varname << "\n";
            return pd(aux, multiToken(nodelist, 2, m), 1);
        }
        // Refer variable
        else {
            if (dupvars.count(node.args[0].val))
                err("Cannot ref stack variable!", m);
            return pd(aux, token(aux.vars[varname], m), 1);
        }
    }
    // Code blocks
    if (node.val == "lll" && node.args.size() == 2) {
        if (node.args[1].val != "0") aux.allocUsed = true;
        std::vector<Node> o;
        o.push_back(finalize(opcodeify(node.args[0])));
        programData sub = opcodeify(node.args[1], aux, height, dupvars);
        Node code = astnode("____CODE", o, m);
        Node nodelist[] = {
            token("$begincode"+symb+".endcode"+symb, m), token("DUP1", m),
            token("$begincode"+symb, m), sub.code, token("CODECOPY", m),
            token("$endcode"+symb, m), token("JUMP", m),
            token("~begincode"+symb, m), code, token("~endcode"+symb, m)
        };
        return pd(sub.aux, multiToken(nodelist, 10, m), 1);
    }
    // Stack variables
    if (node.val == "with") {
        std::map<std::string, int> dupvars2 = dupvars;
        dupvars2[node.args[0].val] = height;
        programData initial = opcodeify(node.args[1], aux, height, dupvars);
        if (!initial.outs)
            err("Initial variable value must have nonzero arity!", m);
        programData sub = opcodeify(node.args[2], initial.aux, height + 1, dupvars2);
        Node nodelist[] = {
            initial.code,
            sub.code
        };
        programData o = pd(sub.aux, multiToken(nodelist, 2, m), sub.outs);
        if (sub.outs)
            o.code.args.push_back(token("SWAP1", m));
        o.code.args.push_back(token("POP", m));
        return o;
    }
    // Seq of multiple statements
    if (node.val == "seq") {
        std::vector<Node> children;
        int lastOut = 0;
        for (unsigned i = 0; i < node.args.size(); i++) {
            programData sub = opcodeify(node.args[i], aux, height, dupvars);
            aux = sub.aux;
            if (sub.outs == 1) {
                if (i < node.args.size() - 1) sub.code = popwrap(sub.code);
                else lastOut = 1;
            }
            children.push_back(sub.code);
        }
        return pd(aux, astnode("_", children, m), lastOut);
    }
    // 2-part conditional (if gets rewritten to unless in rewrites)
    else if (node.val == "unless" && node.args.size() == 2) {
        programData cond = opcodeify(node.args[0], aux, height, dupvars);
        programData action = opcodeify(node.args[1], cond.aux, height, dupvars);
        aux = action.aux;
        if (!cond.outs) err("Condition of if/unless statement has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            cond.code,
            token("$endif"+symb, m), token("JUMPI", m),
            action.code,
            token("~endif"+symb, m)
        };
        return pd(aux, multiToken(nodelist, 5, m), 0);
    }
    // 3-part conditional
    else if (node.val == "if" && node.args.size() == 3) {
        programData ifd = opcodeify(node.args[0], aux, height, dupvars);
        programData thend = opcodeify(node.args[1], ifd.aux, height, dupvars);
        programData elsed = opcodeify(node.args[2], thend.aux, height, dupvars);
        aux = elsed.aux;
        if (!ifd.outs)
            err("Condition of if/unless statement has arity 0", m);
        // Handle cases where one conditional outputs something
        // and the other does not
        int outs = (thend.outs && elsed.outs) ? 1 : 0;
        if (thend.outs > outs) thend.code = popwrap(thend.code);
        if (elsed.outs > outs) elsed.code = popwrap(elsed.code);
        Node nodelist[] = {
            ifd.code,
            token("NOT", m), token("$else"+symb, m), token("JUMPI", m),
            thend.code,
            token("$endif"+symb, m), token("JUMP", m), token("~else"+symb, m),
            elsed.code,
            token("~endif"+symb, m)
        };
        return pd(aux, multiToken(nodelist, 10, m), outs);
    }
    // While (rewritten to this in rewrites)
    else if (node.val == "until") {
        programData cond = opcodeify(node.args[0], aux, height, dupvars);
        programData action = opcodeify(node.args[1], cond.aux, height, dupvars);
        aux = action.aux;
        if (!cond.outs)
            err("Condition of while/until loop has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            token("~beg"+symb, m),
            cond.code,
            token("$end"+symb, m), token("JUMPI", m),
            action.code,
            token("$beg"+symb, m), token("JUMP", m), token("~end"+symb, m)
        };
        return pd(aux, multiToken(nodelist, 8, m));
    }
    // Memory allocations
    else if (node.val == "alloc") {
        programData bytez = opcodeify(node.args[0], aux, height, dupvars);
        aux = bytez.aux;
        if (!bytez.outs)
            err("Alloc input has arity 0", m);
        aux.allocUsed = true;
        Node nodelist[] = {
            bytez.code,
            token("MSIZE", m), token("SWAP1", m), token("MSIZE", m),
            token("ADD", m), 
            token("0", m), token("SWAP1", m), token("MSTORE", m)
        };
        return pd(aux, multiToken(nodelist, 8, m), 1);
    }
    // Array literals
    else if (node.val == "array_lit") {
        aux.allocUsed = true;
        std::vector<Node> nodes;
        if (!node.args.size()) {
            nodes.push_back(token("MSIZE", m));
            return pd(aux, astnode("_", nodes, m));
        }
        nodes.push_back(token("MSIZE", m));
        nodes.push_back(token("0", m));
        nodes.push_back(token("MSIZE", m));
        nodes.push_back(token(unsignedToDecimal(node.args.size() * 32 - 1), m));
        nodes.push_back(token("ADD", m));
        nodes.push_back(token("MSTORE8", m));
        for (unsigned i = 0; i < node.args.size(); i++) {
            Metadata m2 = node.args[i].metadata;
            nodes.push_back(token("DUP1", m2));
            programData sub = opcodeify(node.args[i], aux, height + 2, dupvars);
            if (!sub.outs)
                err("Array_lit item " + unsignedToDecimal(i) + " has zero arity", m2);
            aux = sub.aux;
            nodes.push_back(sub.code);
            nodes.push_back(token("SWAP1", m2));
            if (i > 0) {
                nodes.push_back(token(unsignedToDecimal(i * 32), m2));
                nodes.push_back(token("ADD", m2));
            }
            nodes.push_back(token("MSTORE", m2));
        }
        return pd(aux, astnode("_", nodes, m), 1);
    }
    // All other functions/operators
    else {
        std::vector<Node>  subs2;
        int depth = opinputs(upperCase(node.val));
        if (node.val != "debug") {
            if (depth == -1)
                err("Not a function or opcode: "+node.val, m);
            if ((int)node.args.size() != depth)
                err("Invalid arity for "+node.val, m);
        }
        for (int i = node.args.size() - 1; i >= 0; i--) {
            programData sub = opcodeify(node.args[i],
                                        aux,
                                        height - i - 1 + node.args.size(),
                                        dupvars);
            aux = sub.aux;
            if (!sub.outs)
                err("Input "+unsignedToDecimal(i)+" has arity 0", sub.code.metadata);
            subs2.push_back(sub.code);
        }
        if (node.val == "debug") {
            subs2.push_back(token("DUP"+unsignedToDecimal(node.args.size()), m));
            for (int i = 0; i <= (int)node.args.size(); i++)
                subs2.push_back(token("POP", m));
        }
        else subs2.push_back(token(upperCase(node.val), m));
        int outdepth = node.val == "debug" ? 0 : opoutputs(upperCase(node.val));
        return pd(aux, astnode("_", subs2, m), outdepth);
    }
}
void event_msg_callback(const trigger_sync::EventConstPtr& event_msg)
{

  ros::Time t = ros::Time::now();

  trigger_sync::Event new_event_msg = *event_msg;
  // Check for time request
  if (
         event_msg->local_clock_id     != clock_name     // Event was not sent by us
      && event_msg->local_request_time != ros::Time(0)   // Request time is defined
      && event_msg->device_time        == ros::Time(0)   // Device time is undefined
      && event_msg->local_receive_time == ros::Time(0)   // Recieve time is undefined
      )
  {

    // Fill out the device time with our local time and republish
    new_event_msg.device_clock_id = clock_name;
    new_event_msg.device_time = t;
    event_pub->publish(new_event_msg);
    return;
  }

  // Check for time request
  if (
         event_msg->local_clock_id == clock_name         // Event was sent by us
      && event_msg->local_request_time != ros::Time(0)   // Request time is defined
      && event_msg->device_time        != ros::Time(0)   // Device  time is defined
      && event_msg->local_receive_time == ros::Time(0)   // Recieve time is undefined
      )
  {

    // Fill out the local recive time field of the messge
    new_event_msg.local_receive_time = t;

    // Add event to the appropriate clock estimator
    if (sync_map.count(event_msg->device_clock_id) == 0 )
    {
      sync_map[event_msg->device_clock_id].reset(new TriggerSync(event_msg->device_clock_id,event_msg->local_clock_id));

      double switch_period;
      ros::NodeHandle local_nh("~");
      local_nh.param("switch_period", switch_period, 30.0);
      sync_map[event_msg->device_clock_id]->setSwitchPeriod(ros::Duration(30.0));
    }

    // Add the event to the TriggerSync estimator
    new_event_msg.corrected_local_time = sync_map[event_msg->device_clock_id]->updateTwoWay(
          new_event_msg.local_request_time,
          new_event_msg.device_time,
          new_event_msg.local_receive_time);


    // Publish the event with the
    event_pub->publish(new_event_msg);


    printf(" offset_lb = %+15.1fus , offset_ub = %+15.1fus , offset_estimate = %+15.1fus \r",
             (new_event_msg.local_request_time   - new_event_msg.device_time ).toSec()*1.0e6,
             (new_event_msg.local_receive_time   - new_event_msg.device_time ).toSec()*1.0e6,
             (new_event_msg.corrected_local_time - new_event_msg.device_time ).toSec()*1.0e6
             )      ;

    fflush(stdout);


  }
}
Esempio n. 22
0
void processImage(cv::Mat& image) {
    if (image.empty())
        return;

#ifdef _OPENCV3
    pMOG->apply(image, fgMaskMOG, 0.05);
#else
    pMOG->operator()(image, fgMaskMOG, 0.05);
#endif
    cv::dilate(fgMaskMOG,fgMaskMOG,cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(15,15)));

    bin = new IplImage(fgMaskMOG);
    frame = new IplImage(image);
    labelImg = cvCreateImage(cvSize(image.cols,image.rows),IPL_DEPTH_LABEL,1);

    unsigned int result = cvLabel(bin, labelImg, blobs);
    cvRenderBlobs(labelImg, blobs, frame, frame, CV_BLOB_RENDER_BOUNDING_BOX|CV_BLOB_RENDER_CENTROID|CV_BLOB_RENDER_ANGLE);
    cvFilterByArea(blobs, 1500, 40000);
    cvUpdateTracks(blobs, tracks, 200., 5);
    cvRenderTracks(tracks, frame, frame, CV_TRACK_RENDER_ID);

    for (std::map<CvID, CvTrack*>::iterator track_it = tracks.begin(); track_it!=tracks.end(); track_it++) {
        CvID id = (*track_it).first;
        CvTrack* track = (*track_it).second;
        cur_pos = track->centroid;

        if (track->inactive == 0) {
            if (last_poses.count(id)) {
                std::map<CvID, CvPoint2D64f>::iterator pose_it = last_poses.find(id);
                last_pos = pose_it -> second;
                last_poses.erase(pose_it);
            }
            last_poses.insert(std::pair<CvID, CvPoint2D64f>(id, cur_pos));
            if (line_pos+25>cur_pos.y && cur_pos.y>line_pos && line_pos-25<last_pos.y && last_pos.y<line_pos) {
                count++;
                countUD++;
            }
            if (line_pos-25<cur_pos.y && cur_pos.y<line_pos && line_pos+25>last_pos.y && last_pos.y>line_pos) {
                count++;
                countDU++;
            }

            if ( cur_pos.y<line_pos+50 && cur_pos.y>line_pos-50) {
                avg_vel += abs(cur_pos.y-last_pos.y);
                count_active++;
            }

            //update heatmapfg
            heat_mapfg = cv::Mat::zeros(FR_H, FR_W, CV_8UC3);
            count_arr[lmindex] = count;
            avg_vel_arr[lmindex] = avg_vel/count_active ;
            for (int i=0; i<landmarks.size(); i++) {
                cv::circle(heat_mapfg, cv::Point((landmarks[i].y + 50)*2.4, (landmarks[i].x + 50)*2.4), count_arr[i]*3, cv::Scalar(0, 16*avg_vel_arr[i], 255 - 16*avg_vel_arr[i]), -1);
            }
            cv::GaussianBlur(heat_mapfg, heat_mapfg, cv::Size(15, 15), 5);
        } else {
            if (last_poses.count(id)) {
                last_poses.erase(last_poses.find(id));
            }
        }
    }

    cv::line(image, cv::Point(0, line_pos), cv::Point(FR_W, line_pos), cv::Scalar(0,255,0),2);
    cv::putText(image, "COUNT: "+to_string(count), cv::Point(10, 15), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
    cv::putText(image, "UP->DOWN: "+to_string(countUD), cv::Point(10, 30), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
    cv::putText(image, "DOWN->UP: "+to_string(countDU), cv::Point(10, 45), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
    cv::imshow("BLOBS", image);
    cv::imshow("HEATMAP", heat_map + heat_mapfg);
    cv::waitKey(33);
}
Esempio n. 23
0
int verify_ascanf_Address( void *p, ascanf_Function_type type )
{
	return( (ascanf_AddressMap.count((unsigned long)p) && ascanf_AddressMap[(unsigned long)p]==type)? 1 : 0 );
}
Esempio n. 24
0
 bool has(const char a){ return transitions.count(a); }
Esempio n. 25
0
/**
 * Reads in a vehicle part from a JsonObject.
 */
void game::load_vehiclepart(JsonObject &jo)
{
    vpart_info next_part;

    next_part.id = jo.get_string("id");
    next_part.name = _(jo.get_string("name").c_str());
    next_part.sym = jo.get_string("symbol")[0];
    next_part.color = color_from_string(jo.get_string("color"));
    next_part.sym_broken = jo.get_string("broken_symbol")[0];
    next_part.color_broken = color_from_string(jo.get_string("broken_color"));
    next_part.dmg_mod = jo.has_member("damage_modifier") ? jo.get_int("damage_modifier") : 100;
    next_part.durability = jo.get_int("durability");
    next_part.power = jo.get_int("power", 0);
    next_part.epower = jo.get_int("epower", 0);
    next_part.folded_volume = jo.get_int("folded_volume", 0);

    //Handle the par1 union as best we can by accepting any ONE of its elements
    int element_count = (jo.has_member("par1") ? 1 : 0)
                        + (jo.has_member("size") ? 1 : 0)
                        + (jo.has_member("wheel_width") ? 1 : 0)
                        + (jo.has_member("bonus") ? 1 : 0);

    if(element_count == 0) {
        //If not specified, assume 0
        next_part.par1 = 0;
    } else if(element_count == 1) {
        if(jo.has_member("par1")) {
            next_part.par1 = jo.get_int("par1");
        } else if(jo.has_member("size")) {
            next_part.par1 = jo.get_int("size");
        } else if(jo.has_member("wheel_width")) {
            next_part.par1 = jo.get_int("wheel_width");
        } else { //bonus
            next_part.par1 = jo.get_int("bonus");
        }
    } else {
        //Too many
        debugmsg("Error parsing vehicle part '%s': \
               Use AT MOST one of: par1, power, size, wheel_width, bonus",
                 next_part.name.c_str());
        //Keep going to produce more messages if other parts are wrong
        next_part.par1 = 0;
    }
    next_part.fuel_type = jo.has_member("fuel_type") ? jo.get_string("fuel_type") : "NULL";
    next_part.item = jo.get_string("item");
    next_part.difficulty = jo.get_int("difficulty");
    next_part.location = jo.has_member("location") ? jo.get_string("location") : "";

    next_part.bitflags = 0;
    JsonArray jarr = jo.get_array("flags");
    std::string nstring = "";
    while (jarr.has_more()) {
        nstring = jarr.next_string();
        next_part.flags.insert(nstring);
        if ( vpart_bitflag_map.find(nstring) != vpart_bitflag_map.end() ) {
            next_part.bitflags |= mfb( vpart_bitflag_map.find(nstring)->second );
        }
    }

    if (jo.has_member("FOLDABLE") && next_part.folded_volume == 0){
        debugmsg("Error: folded part %s has a volume of 0!", next_part.name.c_str());
    }

    JsonArray breaks_into = jo.get_array("breaks_into");
    while(breaks_into.has_more()) {
        JsonObject next_entry = breaks_into.next_object();
        break_entry next_break_entry;
        next_break_entry.item_id = next_entry.get_string("item");
        next_break_entry.min = next_entry.get_int("min");
        next_break_entry.max = next_entry.get_int("max");
        //Sanity check
        if(next_break_entry.max < next_break_entry.min) {
            debugmsg("For vehicle part %s: breaks_into item '%s' has min (%d) > max (%d)!",
                     next_part.name.c_str(), next_break_entry.item_id.c_str(),
                     next_break_entry.min, next_break_entry.max);
        }
        next_part.breaks_into.push_back(next_break_entry);
    }

    //Calculate and cache z-ordering based off of location
    // list_order is used when inspecting the vehicle
    if(next_part.location == "on_roof") {
        next_part.z_order = 9;
        next_part.list_order = 3;
    } else if(next_part.location == "on_cargo") {
        next_part.z_order = 8;
        next_part.list_order = 6;
    } else if(next_part.location == "center") {
        next_part.z_order = 7;
        next_part.list_order = 7;
    } else if(next_part.location == "under") {
        //Have wheels show up over frames
        next_part.z_order = 6;
        next_part.list_order = 10;
    } else if(next_part.location == "structure") {
        next_part.z_order = 5;
        next_part.list_order = 1;
    } else if(next_part.location == "engine_block") {
        //Should be hidden by frames
        next_part.z_order = 4;
        next_part.list_order = 8 ;
    } else if (next_part.location == "on_battery_mount"){
        //Should be hidden by frames
        next_part.z_order = 3;
        next_part.list_order = 10;
    } else if(next_part.location == "fuel_source") {
        //Should be hidden by frames
        next_part.z_order = 3;
        next_part.list_order = 9;
    } else if(next_part.location == "roof") {
        //Shouldn't be displayed
        next_part.z_order = -1;
        next_part.list_order = 4;
    } else if(next_part.location == "armor") {
        //Shouldn't be displayed (the color is used, but not the symbol)
        next_part.z_order = -2;
        next_part.list_order = 2;
    } else {
        //Everything else
        next_part.z_order = 0;
        next_part.list_order = 5;
    }

    if (vehicle_part_types.count(next_part.id) > 0) {
        next_part.loadid = vehicle_part_types[next_part.id].loadid;
        vehicle_part_int_types[next_part.loadid] = next_part;
    } else {
        next_part.loadid = vehicle_part_int_types.size();
        vehicle_part_int_types.push_back(next_part);
    }
    vehicle_part_types[next_part.id] = next_part;
}
Esempio n. 26
0
		MetadataElement::Type enumFromString(std::string strType) {
			if ( m_stringToEnum.count(strType)==0 ) {
				MR4C_THROW(std::invalid_argument, "No metadata element type named [" << strType << "]");
			}
			return m_stringToEnum[strType];
		}
Esempio n. 27
0
std::string searchAbbreviations(std::string in) // searches abbreviations, returns expansion if so, returns original if not
{
	if(abbreviations.count(in) > 0) return abbreviations[in];
	return in;
};
Esempio n. 28
0
		std::string enumToString(MetadataElement::Type type) {
			if ( m_enumToString.count(type)==0 ) {
				MR4C_THROW(std::invalid_argument, "No metadata element type enum = " << type);
			}
			return m_enumToString[type];
		}
bool ProductManager::addRequest(pioneer_control::ProductManagerAddRequest::Request &req, pioneer_control::ProductManagerAddRequest::Response &res)
{
	std::string pickUp = req.pickUp;
	std::string deliver = req.deliver;
	res.status = false;
	bool isTransportValid = true;

	if(!productAreasInformation.count(pickUp)) {
		ROS_INFO("ERROR! Product Area name \"%s\" is not valid.", pickUp.c_str());
		isTransportValid = false;
	}
	if(!productAreasInformation.count(deliver)) {
		ROS_INFO("ERROR! Product Area name \"%s\" is not valid.", deliver.c_str());
		isTransportValid = false;
	}
	if(!isTransportValid) return false;
	PAInformation* pickUpPAInfo = &productAreasInformation[pickUp];
	PAInformation* deliverPAInfo = &productAreasInformation[deliver];
	switch(pickUpPAInfo->status)
	{
		case PAStatus_PickUp: 
			ROS_INFO("Pick Up PA (%s): ERROR! Product in this PA already to be picked up.", pickUp.c_str());
			isTransportValid = false;
			break;
		case PAStatus_Deliver:
			ROS_INFO("Pick Up PA (%s): ERROR! PA to be occupied.", pickUp.c_str());
			isTransportValid = false;
			break;
		case PAStatus_Empty:
			ROS_INFO("Pick Up PA (%s): ERROR! PA empty, no product here.", pickUp.c_str());
			isTransportValid = false;
			break;
		case PAStatus_Idle:
			ROS_INFO("Pick Up PA (%s): OK! Product waiting to be transported!.", pickUp.c_str());
			break;
	}

	switch(deliverPAInfo->status)
	{
		case PAStatus_PickUp: 
			ROS_INFO("Deliver PA (%s): ERROR! Product in this PA already to be picked up.", deliver.c_str());
			isTransportValid = false;
			break;
		case PAStatus_Deliver:
			ROS_INFO("Deliver PA (%s): ERROR! PA to be occupied.", deliver.c_str());
			isTransportValid = false;
			break;
		case PAStatus_Empty:
			ROS_INFO("Deliver PA (%s): OK! PA empty, product can be delivered here!.", deliver.c_str());
			break;
		case PAStatus_Idle:
			ROS_INFO("Deliver PA (%s): ERROR! Product here, can't deliver here!.", deliver.c_str());
			isTransportValid = false;
			break;
	}

	if(!isTransportValid) return false;

	TransportInformation* transportInfo;
	transportInfo = new TransportInformation(transportCount, pickUpPAInfo, deliverPAInfo);
	transportsWaitingAccept.push_back(transportInfo);

	ROS_INFO("Product Manager: Transport request %d (%s to %s) added to request queue.", transportCount, pickUp.c_str(), deliver.c_str());
	//transportRequestMsg.id = transportInfo->id;
	//transportRequestMsg.pickUpPA.x = transportInfo->pickUpPA->pos.x;
	//transportRequestMsg.pickUpPA.y = transportInfo->pickUpPA->pos.y;
	//transportRequestMsg.deliverPA.x = transportInfo->deliverPA->pos.x;
	//transportRequestMsg.deliverPA.y = transportInfo->deliverPA->pos.y;
	//printf("Product Manager: Request %d pick up from (%d, %d) ", transportCount, transportRequestMsg.pickUpPA.x, transportRequestMsg.pickUpPA.y);
	//printf("deliver to (%d, %d) published\n", transportRequestMsg.deliverPA.x, transportRequestMsg.deliverPA.y);
	//transportRequestPub.publish(transportRequestMsg);

	transportCount++;
	res.status = true;
	return true;
}
Esempio n. 30
0
void compile(const std::string bf_program,
             std::vector<std::string> &asm_program,
             const std::map<std::string,std::string> &options) {

    std::stack<int> jump_label_nums;	//stack for [ and ] instructions
    //auto curr_inst = bf_program.begin(); //iterator over instructions
    auto label_num = 1;					//counter for label numbers to avoid conflicts

    //data register option
    if(options.count("data_reg")) {
        asm_program.push_back("clr " + options.at("data_reg") + "\n");

    } else {
        asm_program.push_back("clr r16\n");
    }


    if(options.count("memory_addr")) {
        asm_program.push_back("ldi r26, " + options.at("memory_addr") + "\n");

    } else {
        asm_program.push_back("ldi r26, 0x60\n");
    }

    asm_program.push_back("main:\n");


    for(const auto &curr_inst : bf_program) {
        switch(curr_inst) {
        case inc_ptr:
            asm_program.push_back(asm_inc_ptr);
            break;

        case dec_ptr:
            asm_program.push_back(asm_dec_ptr);
            break;

        case inc_deref:
            asm_program.push_back(asm_inc_deref);
            break;

        case dec_deref:
            asm_program.push_back(asm_dec_deref);
            break;

        case beg_loop:
        {
            const auto end_label = "loop_label_end" + std::to_string(label_num);
            const auto beg_label = "loop_label" + std::to_string(label_num);
            asm_program.push_back("cpi r16,0\nbreq " + end_label + "\n");
            asm_program.push_back(beg_label + ":\n\n");
            jump_label_nums.push(label_num);
            ++label_num;
        }
        break;

        case end_loop:
        {
            const auto curr_label_num = jump_label_nums.top();
            jump_label_nums.pop();
            const auto beg_label = "loop_label" + std::to_string(curr_label_num);
            const auto end_label = "loop_label_end" + std::to_string(curr_label_num);
            asm_program.push_back("cpi r16, 0\nbrne " + beg_label + "\n");
            asm_program.push_back(end_label + ":\n");
        }
        break;

        case read_char:
            asm_program.push_back(asm_read_char);
            break;

        case put_char:
            asm_program.push_back(asm_put_char);
            break;
        }
    }

}