//this function is called after each timeout, which iterates the CA
gint loopThrough(gpointer data) {
    //if autoReset is toggled, find if row is all black or all white,
    // and reset if it is either
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autoResetButton))) {
        int sum = ca1->getRowSum();
        if ((sum < ROW_LOWER_BOUND) || (sum > DEFAULT_WIDTH)) {
            ca1->resetCells();
        }
    }

    //if meta-rules have been loaded, apply them here
    if (rules.size() > 0) {
        if ((numLines % ruleChangeInterval == 0) && (numLines != 0)) {
            int seed = rand() % rules.size();
            ca1->setRule(rules[seed]);
            std::cout << "changing rule to " << rules[seed] << std::endl;
            if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(randomizeLengthButton))) {
                ruleChangeInterval=rand() % maxRuleChangeInterval + 1;
            }
        }
    }

    //calculate the new row, iterate the automaton
    ca1->calcNewRow();

    //redraw the image
    redrawImage();

    //if auto-saving pics, activate here
    if ((numLines % HEIGHT == 0) && savePics) {
        getPic(data);
    }
    return TRUE;
}
Example #2
0
void PViewDataList::_setLast(int ele, int dim, int nbnod, int nbcomp, int nbedg,
                             int type, std::vector<double> &list, int nblist)
{
  if(haveInterpolationMatrices()) {
    std::vector<fullMatrix<double> *> im;
    if(getInterpolationMatrices(type, im) == 4) nbnod = im[2]->size1();
  }

  _lastDimension = dim;
  _lastNumNodes = nbnod;
  _lastNumComponents = nbcomp;
  _lastNumEdges = nbedg;
  _lastType = type;
  int nb = list.size() / nblist; // number of coords and values for the element
  int nbAg =
    ele * nb; // number of coords and values before the ones of the element
  if(type == TYPE_POLYG || type == TYPE_POLYH) {
    int t = (type == TYPE_POLYG) ? 0 : 1;
    nb = list.size() / polyTotNumNodes[t] * nbnod;
    nbAg = polyAgNumNodes[t][ele] * nb / nbnod;
  }
  _lastNumValues = (nb - 3 * nbnod) / NbTimeStep;
  _lastXYZ = &list[nbAg];
  _lastVal = &list[nbAg + 3 * _lastNumNodes];
}
// Helper function for checking if a piece type has any available moves.
// Arguments are: a vector with the positions of the pieces of that type on the
// board; a pointer to a function that generates possible moves for that piece
// type; a bool for checking the color of the engine.
//
// Returns 1 if a valid move lead to victory, 0 if a simple valid move was
// found, -1 if no valid move was found.
int ChessBoard::random_piece_helper(std::vector<int> piece_positions,
								  std::vector<int> (* generate)(int, bool),
								  bool isWhite) {
	int chosen_piece, next_pos;			  
	while (piece_positions.size() != 0) {
		chosen_piece = rand() % piece_positions.size();
		std::vector<int> valid_final_moves =
							generate(piece_positions[chosen_piece], isWhite);
		
		while (valid_final_moves.size() != 0) {
			next_pos = rand() % valid_final_moves.size();
			if (try_moving_piece(piece_positions[chosen_piece],
								valid_final_moves[next_pos],
								isWhite)) {
				//if (winner(isWhite))
				//	return 1;
				return 0;
			}
			valid_final_moves.erase(valid_final_moves.begin() + next_pos);
		}
		if (table->pieces[piece_positions[chosen_piece]].name == 'K' ||
			table->pieces[piece_positions[chosen_piece]].name == 'k')
			return -1;
		piece_positions.erase(piece_positions.begin() + chosen_piece);
	}
	return -1;
}
Example #4
0
DenseVector stdToEigenVec(const std::vector<double> vec)
{
    DenseVector out = DenseVector::Zero(vec.size());
    for (unsigned int i = 0; i < vec.size(); i++)
        out(i) = vec.at(i);
    return out;
}
Example #5
0
void play_music( const std::string &playlist )
{
    const auto iter = playlists.find( playlist );
    if( iter == playlists.end() ) {
        return;
    }
    const music_playlist &list = iter->second;
    if( list.entries.empty() ) {
        return;
    }

    // Don't interrupt playlist that's already playing.
    if( playlist == current_playlist ) {
        return;
    }

    for( size_t i = 0; i < list.entries.size(); i++ ) {
        playlist_indexes.push_back( i );
    }
    if( list.shuffle ) {
        static auto eng = std::default_random_engine(
                              std::chrono::system_clock::now().time_since_epoch().count() );
        std::shuffle( playlist_indexes.begin(), playlist_indexes.end(), eng );
    }

    current_playlist = playlist;
    current_playlist_at = playlist_indexes.at( absolute_playlist_at );

    const auto &next = list.entries[current_playlist_at];
    play_music_file( next.file, next.volume );
}
 const std::vector<std::string>& InfraredTransparentMaterial_Impl::outputVariableNames() const
 {
   static std::vector<std::string> result;
   if (result.empty()){
   }
   return result;
 }
void MaterialShaderGraph::CalculateDependencyGraph(const std::vector<std::unique_ptr<MaterialShader>>& nodes,
													lemon::ListDigraph& depGraph,
													lemon::ListDigraph::NodeMap<MaterialShader*>& depMap)
{
	using namespace lemon;

	struct NodeMap {
		ListDigraph::Node graphNode;
		size_t index;
	};
	std::unordered_map<const MaterialShader*, NodeMap> nodeMap;

	for (auto i : Range(nodes.size())) {
		auto& node = nodes[i];
		ListDigraph::Node graphNode = depGraph.addNode();
		nodeMap[node.get()] = { graphNode, i };
		depMap[graphNode] = node.get();
	}

	for (auto destIdx : Range(nodes.size())) {
		auto destNode = nodes[destIdx].get();

		for (size_t inputPortIdx = 0; inputPortIdx < destNode->GetNumInputs(); ++inputPortIdx) {
			auto sourcePort = destNode->GetInput(inputPortIdx)->GetLink();
			auto sourceNode = sourcePort != nullptr ? sourcePort->GetParent() : nullptr;
			if (sourceNode != nullptr) {
				depGraph.addArc(nodeMap[sourceNode].graphNode, nodeMap[destNode].graphNode);
			}
		}
	}
}
TEST_F(OpcUaBinarySerialization, ReadResponse)
{

  using namespace OpcUa;
  using namespace OpcUa::Binary;

  ReadResponse resp;

  ASSERT_EQ(resp.TypeID.Encoding, EV_FOUR_BYTE);
  ASSERT_EQ(resp.TypeID.FourByteData.NamespaceIndex, 0);
  ASSERT_EQ(resp.TypeID.FourByteData.Identifier, OpcUa::READ_RESPONSE);

  FILL_TEST_RESPONSE_HEADER(resp.Header);

  resp.Result.Results.push_back(OpcUa::DataValue(QualifiedName(1, OpcUa::Names::Root)));

  ASSERT_NO_THROW(GetStream() << resp << flush);

  char encodingMask = static_cast<char>(OpcUa::DATA_VALUE);
  char variantMask = static_cast<char>(OpcUa::VariantType::QUALIFIED_NAME);
  const std::vector<char> expectedData = {
  1, 0, (char)0x7A, 0x2, // TypeID
  // RequestHeader
  TEST_RESPONSE_HEADER_BINARY_DATA,
  1,0,0,0,
  encodingMask,
  variantMask,
  1, 0,
  4, 0, 0, 0, 'R','o','o','t',
  0,0,0,0
  };

  ASSERT_EQ(expectedData, GetChannel().SerializedData) << PrintData(GetChannel().SerializedData) << std::endl << PrintData(expectedData);
  ASSERT_EQ(expectedData.size(), RawSize(resp));
}
TEST_F(OpcUaBinarySerialization, WriteResponse)
{
  using namespace OpcUa;
  using namespace OpcUa::Binary;

  WriteResponse resp;

  ASSERT_EQ(resp.TypeID.Encoding, EV_FOUR_BYTE);
  ASSERT_EQ(resp.TypeID.FourByteData.NamespaceIndex, 0);
  ASSERT_EQ(resp.TypeID.FourByteData.Identifier, OpcUa::WRITE_RESPONSE);

  FILL_TEST_RESPONSE_HEADER(resp.Header);

  resp.Result.StatusCodes.push_back(static_cast<StatusCode>(1));
 
  DiagnosticInfo info;
  info.EncodingMask = static_cast<DiagnosticInfoMask>(DIM_LOCALIZED_TEXT);
  info.LocalizedText = 4;
  resp.Result.Diagnostics.push_back(info);
 
  GetStream() << resp << flush;

  const std::vector<char> expectedData = {
  1, 0, (char)0xA4, 0x2, // TypeID
  // RequestHeader
  TEST_RESPONSE_HEADER_BINARY_DATA,

  1,0,0,0, 1,0,0,0,
  1,0,0,0, static_cast<DiagnosticInfoMask>(DIM_LOCALIZED_TEXT), 4,0,0,0
  };

  ASSERT_EQ(expectedData, GetChannel().SerializedData) << PrintData(GetChannel().SerializedData) << std::endl << PrintData(expectedData);
  ASSERT_EQ(expectedData.size(), RawSize(resp));
}
Example #10
0
void Tree::GetNodeNumPerLevelAndGiveLabel(std::vector<int>& node_num, std::vector<int>& base_index,Tree * root, std::vector<Tree *>& serialized_tree, std::vector<int>& label_to_index) { 
	Tree * right_root = root;
	int depth = root->Depth();
	node_num.resize(depth-1);
	base_index.resize(depth-1);
	for(int i = 0; i < depth-1; ++i)
	{
	  node_num[i] = right_root->children[right_root->children.size()-1]->GetIndex() - root->children[0]->GetIndex() + 1;
	  base_index[i] = root->children[0]->index;
	  root = root->children[0].get();
	  right_root = right_root->children[right_root->children.size()-1].get();

	  if( i < depth-2 ){ //label for last layer is already made
		  for(int j = base_index[i]; j < base_index[i]+node_num[i]; ++j)
			  serialized_tree[j]->label = j - base_index[i];
	  }
	  else {
		  label_to_index.resize(node_num[i]);
		  for(int index = 0; index < node_num[i]; ++index) {
			  int label = serialized_tree[index+base_index[i]]->GetLabel();
				label_to_index[label] = index;
		  }
	  }

	}
}
TEST_F(OpcUaBinarySerialization, AttributeValueID)
{

  using namespace OpcUa;
  using namespace OpcUa::Binary;
  using OpcUa::AttributeID;

  AttributeValueID attr;

  attr.Node.Encoding = EV_TWO_BYTE;
  attr.Node.TwoByteData.Identifier = 1;
  attr.Attribute = AttributeID::VALUE;
  attr.IndexRange = "1,2";
  attr.DataEncoding.NamespaceIndex = 2;
  attr.DataEncoding.Name = "test";

  GetStream() << attr << flush;

  const std::vector<char> expectedData = {
  0, 1,
  13,0,0,0,
  3,0,0,0, '1',',','2',
  2,0,
  4,0,0,0, 't','e','s','t'
  };

  ASSERT_EQ(expectedData.size(), RawSize(attr));
  ASSERT_EQ(expectedData, GetChannel().SerializedData) << PrintData(GetChannel().SerializedData) << std::endl << PrintData(expectedData);
}
Example #12
0
	template <class T> static void TokenizeTemplate(const T& haystack,
		std::vector<T>& tokens, const T& delimeters, bool skipDuplicates)
	{
		size_t lastPos = haystack.find_first_not_of(delimeters, 0);
		size_t pos = haystack.find_first_of(delimeters, lastPos);
		while (T::npos != pos || T::npos != lastPos)
		{
			T token(haystack.substr(lastPos, pos-lastPos));
			bool duplicate = false;

			if (skipDuplicates)
			{
				for (size_t i = 0; i < tokens.size(); i++)
				{
					if (tokens[i] == token)
					{
						duplicate = true;
						break;
					}
				}
			}

			if (!duplicate)
				tokens.push_back(token);

			lastPos = haystack.find_first_not_of(delimeters, pos);
			pos = haystack.find_first_of(delimeters, lastPos);
		}
	}
Example #13
0
void StackTrace::get(std::vector<std::shared_ptr<Frame>> &frames) const {
  frames.clear();
  for (auto btpi = m_bt_pointers.begin();
       btpi != m_bt_pointers.end(); ++btpi) {
    frames.push_back(Translate(*btpi));
  }
}
Example #14
0
    bool Rook::isMovingPossible(const std::string &strFromAddr,
                                const std::string &strToAddr,
                                std::vector<std::string>& path, bool bFlag) const
    {
        Pos fromPos(strFromAddr);
        Pos toPos(strToAddr);

        if( toPos.getX() == fromPos.getX() )
        {
            for(int y = fromPos.getY() + 1; y < toPos.getY(); y++)
                path.push_back(Pos(toPos.getX(), y));
            for(int y = fromPos.getY() - 1; y > toPos.getY(); y--)
                path.push_back(Pos(toPos.getX(), y));
            return true;
        }

        if( toPos.getY() == fromPos.getY())
        {
            for(int x = fromPos.getX() + 1; x < toPos.getX(); x++)
                path.push_back(Pos(x, toPos.getY()));
            for(int x = fromPos.getX() - 1; x > toPos.getX(); x--)
                path.push_back(Pos(x, toPos.getY()));
            return true;
        }

        return false;
    }
Example #15
0
template <typename PointT> inline void
pcl::getMinMax3D (const pcl::PointCloud<PointT> &cloud, const std::vector<int> &indices,
                  Eigen::Vector4f &min_pt, Eigen::Vector4f &max_pt)
{
    min_pt.setConstant (FLT_MAX);
    max_pt.setConstant (-FLT_MAX);

    // If the data is dense, we don't need to check for NaN
    if (cloud.is_dense)
    {
        for (size_t i = 0; i < indices.size (); ++i)
        {
            pcl::Array4fMapConst pt = cloud.points[indices[i]].getArray4fMap ();
            min_pt = min_pt.array ().min (pt);
            max_pt = max_pt.array ().max (pt);
        }
    }
    // NaN or Inf values could exist => check for them
    else
    {
        for (size_t i = 0; i < indices.size (); ++i)
        {
            // Check if the point is invalid
            if (!pcl_isfinite (cloud.points[indices[i]].x) ||
                    !pcl_isfinite (cloud.points[indices[i]].y) ||
                    !pcl_isfinite (cloud.points[indices[i]].z))
                continue;
            pcl::Array4fMapConst pt = cloud.points[indices[i]].getArray4fMap ();
            min_pt = min_pt.array ().min (pt);
            max_pt = max_pt.array ().max (pt);
        }
    }
}
Example #16
0
/*
Конструируем данныен полигональной сетки на основе переданной информации о ее вершинах и гранях
*/
CTriangleMeshData::CTriangleMeshData(std::vector<Vertex> const& vertices, std::vector<Face> const& faces, bool normalize)
:m_vertices(vertices)
{
	size_t const numVertices = m_vertices.size();
	if (normalize)
	{
		// При необходимости выполняем нормализацию нормалей в вершинах
		for (size_t i = 0; i < numVertices; ++i)
		{
			m_vertices[i].normal.Normalize();
		}
	}

	// Выделяем память под хранение всех треугольных граней
	m_triangles.reserve(faces.size());

	// Заполняем массив треугольных граней
	size_t const numFaces = faces.size();
	for (size_t i = 0; i < numFaces; ++i)
	{
		Face const& face = faces[i];

		size_t i0 = size_t(face.vertex0);
		size_t i1 = size_t(face.vertex1);
		size_t i2 = size_t(face.vertex2);
		assert(i0 <numVertices && i1 < numVertices && i2 < numVertices);

		CTriangle triangle(m_vertices[i0], m_vertices[i1], m_vertices[i2], face.isFlat);
		m_triangles.push_back(triangle);
	}
}
Example #17
0
	ImageGeneric(const std::vector<unsigned int>& stride, const std::vector<unsigned int>& rows, std::mt19937& rng) {

		// count planes
		assert(stride.size() == rows.size());
		unsigned int planes = stride.size();
		m_data.resize(planes);
		m_stride.resize(planes);

		// calculate stride and total size
		size_t totalsize = 0;
		for(unsigned int p = 0; p < planes; ++p) {
			m_stride[p] = grow_align16(stride[p]);
			totalsize += m_stride[p] * rows[p];
		}

		// allocate buffer
		m_buffer.Alloc(totalsize);
		for(unsigned int i = 0; i < totalsize; ++i) {
			m_buffer[i] = rng();
		}

		// set data
		uint8_t *data = m_buffer.GetData();
		for(unsigned int p = 0; p < planes; ++p) {
			m_data[p] = data;
			data += m_stride[p] * rows[p];
		}

	}
Example #18
0
void dnd_row (std::vector< std::vector<std::string> >& vec, int row, int count)
{
    std::cout << "dnd_row called" << std::endl;
    //temp_vec.clear();
    for (int i = 0; i < count; i++)
    {
        temp_vec.push_back(vec[row+i]);
    }
    std::cout << "vector copied" << std::endl;
    for (int i = 0; i < count; i++)
    {
        string temp = "";
        for (int j = 0; j < COLS; j++)
        {
            temp += temp_vec[i][j];
        }
        cout << temp << endl;
        //vector<int>::iterator it = vector1.begin();
    }
    vec.erase(vec.begin()+row, vec.begin()+row+count);
    std::cout << "row erased" << std::endl;
    for (int i = 0; i < count; i++)
    {
        //vector<int>::iterator it = vector1.begin();
        vec.insert(vec.begin()+row+i, temp_vec[i]);
    }
    //std::cout << "row inserted" << std::endl;
}
Example #19
0
/// lists files and directories in a given directory (adds them to res)
/// WARNING ! also returns ../ and ./
void	rob_dirlist			(const char* path,std::vector<std::string>& res,const bool bDirs,const bool bFiles) {
	#ifdef WIN32
		// WARNING ! this win part is not tested
		std::string pattern = std::string(path) + std::string("/*"); // warning !  / might be wrong, we should detect the slashtype from path
		WIN32_FIND_DATA finddata;
		HANDLE search = FindFirstFile(pattern.c_str(),&finddata);
		if (search == INVALID_HANDLE_VALUE) return;

		do {
			bool bIsDir = (finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
			if ((bIsDir && bDirs) || (!bIsDir && bFiles))
				res.push_back(std::string(finddata.cFileName));
		} while (FindNextFile(search,&finddata)) ;
	
	// TODO : #elseif MAC or something like that
	// TODO : #elseif LINUX or something like that
	#else
		// this is the linux code
		std::string sPath = (*path) ? path : ".";
		DIR *d = opendir(sPath.c_str());
		if (!d) return;
		struct dirent *e;
		e = readdir(d);
		while (e != NULL) {
			std::string subname(e->d_name);
			std::string path = sPath + "/" + subname + "/.";
			bool bIsDir = opendir(path.c_str()) != 0;
			//printf("bIsDir(%s)=%d\n",subname.c_str(),bIsDir?1:0);
			if ((bDirs && bIsDir) || (bFiles && !bIsDir)) res.push_back(subname);
			e = readdir(d);
		}
		closedir(d); 
	#endif
}
Example #20
0
// ------------------------------------------------------------------------------------
// shockwave_level_close()
//
//  Call at the close of each level (mission)
//
void shockwave_level_close()
{
	if ( !Shockwave_inited )
		return;

	shockwave_delete_all();
	
	uint i;

	// unload default shockwave, and erase all others
	for (i = 0; i < Shockwave_info.size(); i++) {
		if ( !i ) {
			if (Shockwave_info[i].bitmap_id >= 0)
				bm_unload( Shockwave_info[i].bitmap_id );
			else if (Shockwave_info[i].model_id >= 0)
				model_page_out_textures( Shockwave_info[i].model_id );

			continue;
		}

		if (Shockwave_info[i].bitmap_id >= 0)
			bm_release( Shockwave_info[i].bitmap_id );

		if (Shockwave_info[i].model_id >= 0)
			model_unload( Shockwave_info[i].model_id );

		Shockwave_info.erase( Shockwave_info.begin() + i );
	}

	Shockwave_inited = 0;
}
Example #21
0
void NetCDFFile::GetVariablesAttributes(std::vector< std::string > &attributeNames,
                                        std::vector< std::string > &attributeValues,
                                        const std::string &variableName) const
{
    const netCDF::NcVar var = getVariable( variableName );
    
    if( sofa::NcUtils::IsValid( var ) == true )
    {
        const std::map< std::string, netCDF::NcVarAtt > attributes = var.getAtts();
        
        const std::size_t size = attributes.size();
        attributeNames.resize( size );
        attributeValues.resize( size );
        
        std::size_t i = 0;
        for( std::multimap< std::string, netCDF::NcVarAtt >::const_iterator it = attributes.begin();
            it != attributes.end();
            ++it )
        {
            attributeNames[i]   = (*it).first;
            const netCDF::NcVarAtt att = (*it).second;
            
            attributeValues[i] = sofa::NcUtils::GetAttributeValueAsString( att );
            
            i++;
        }
    }
    else
    {
        attributeNames.clear();
        attributeValues.clear();
    }
}
Example #22
0
void setSaveDataFixed(std::vector<SaveDataEntry>& saveEntries, mem_ptr_t<CellSaveDataFixedSet> fixedSet)
{
	std::vector<SaveDataEntry>::iterator entry = saveEntries.begin();
	while (entry != saveEntries.end())
	{
		if (entry->dirName == (char*)Memory.VirtualToRealAddr(fixedSet->dirName_addr))
			entry = saveEntries.erase(entry);
		else
			entry++;
	}

	if (saveEntries.size() == 0)
	{
		SaveDataEntry entry;
		entry.dirName = (char*)Memory.VirtualToRealAddr(fixedSet->dirName_addr);
		entry.isNew = true;
		saveEntries.push_back(entry);
	}

	if (fixedSet->newIcon.GetAddr())
	{
		saveEntries[0].iconBuf = Memory.VirtualToRealAddr(fixedSet->newIcon->iconBuf_addr);
		saveEntries[0].iconBufSize = fixedSet->newIcon->iconBufSize;
		saveEntries[0].title = (char*)Memory.VirtualToRealAddr(fixedSet->newIcon->title_addr);
		saveEntries[0].subtitle = (char*)Memory.VirtualToRealAddr(fixedSet->newIcon->title_addr);
	}
}
void Chromosome::to_vector(std::vector<std::vector<double>>& vec) {
    // left side of network
    vector<double> neuron_params = vector<double>(PARAM_LEN);
    for (int j = 0; j < NEURONS_TO_SET_UP; j++) {
        for (int i = 0; i < PARAM_LEN; i++) {
            double param_val = m_genes[i + j * PARAM_LEN];
            if (i == 0) param_val = time_const_conversion(param_val);
            else if (i == 1) param_val = bias_conversion(param_val);
            else param_val = synaptic_weight_conversion(param_val);
            neuron_params[i] = param_val;
        }
        vec.push_back(neuron_params);
    }
    
    // right side of network
    for (int j = 0; j < NEURONS_TO_SET_UP; j++) {
        for (int i = 0; i < PARAM_LEN; i++) {
            int offset = 0;
            if (i > CONST_INDEX) {
                if (i < WEIGHT_MIDPOINT) offset = 5;
                else offset = -5;
            }
            double param_val = m_genes[offset + i + j * PARAM_LEN];
            if (i == 0) param_val = time_const_conversion(param_val);
            else if (i == 1) param_val = bias_conversion(param_val);
            else param_val = synaptic_weight_conversion(param_val);
            neuron_params[i] = param_val;
        }
        vec.push_back(neuron_params);
    }
}
Example #24
0
void posScaleToBbox(std::vector<kstate> kstates, std::vector<kstate>& trackedDetections)
{
	for (unsigned int i = 0; i < kstates.size(); i++)
	{
		if (kstates[i].active)
		{
			kstate tmp;
			tmp.pos.x = kstates[i].pos.x;// -(kstates[i].pos.width / 2);
			tmp.pos.y = kstates[i].pos.y;// -(kstates[i].pos.height / 2);
			tmp.pos.width = kstates[i].pos.width;
			tmp.pos.height = kstates[i].pos.height;
			tmp.color = kstates[i].color;
			tmp.id = kstates[i].id;
			tmp.score = kstates[i].score;
			tmp.lifespan = kstates[i].lifespan;
			tmp.real_data = kstates[i].real_data;
			tmp.range = kstates[i].range;
			tmp.min_height = kstates[i].min_height;
			tmp.max_height = kstates[i].max_height;

			//fill in also LAtentSvm object
			tmp.obj.rect = tmp.pos;
			tmp.obj.score = tmp.score;

			if (tmp.pos.x < 0)
				tmp.pos.x = 0;
			if (tmp.pos.y < 0)
				tmp.pos.y = 0;

			trackedDetections.push_back(tmp);
		}
	}
}
Example #25
0
std::vector<ChatCommand> const& ChatHandler::getCommandTable()
{
    static std::vector<ChatCommand> commandTableCache;

    if (LoadCommandTable())
    {
        SetLoadCommandTable(false);

        std::vector<ChatCommand> cmds = sScriptMgr->GetChatCommands();
        commandTableCache.swap(cmds);

        PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_COMMANDS);
        PreparedQueryResult result = WorldDatabase.Query(stmt);
        if (result)
        {
            do
            {
                Field* fields = result->Fetch();
                std::string name = fields[0].GetString();

                SetDataForCommandInTable(commandTableCache, name.c_str(), fields[1].GetUInt16(), fields[2].GetString(), name);
            }
            while (result->NextRow());
        }
    }

    return commandTableCache;
}
Example #26
0
namespace bm {

typedef EliasFanoEncoderV2<uint32_t, uint32_t, 128, 128> Encoder;
typedef EliasFanoReader<Encoder> Reader;

std::vector<uint32_t> data;
std::vector<size_t> order;

std::vector<uint32_t> encodeSmallData;
std::vector<uint32_t> encodeLargeData;

typename Encoder::MutableCompressedList list;

void init() {
  std::mt19937 gen;

  data = generateRandomList(100 * 1000, 10 * 1000 * 1000, gen);
  list = Encoder::encode(data.begin(), data.end());

  order.resize(data.size());
  std::iota(order.begin(), order.end(), size_t());
  std::shuffle(order.begin(), order.end(), gen);

  encodeSmallData = generateRandomList(10, 100 * 1000, gen);
  encodeLargeData = generateRandomList(1000 * 1000, 100 * 1000 * 1000, gen);
}

void free() {
  list.free();
}

}  // namespace bm
Example #27
0
Debug Util_Parser::read_yaml_Debug(std::vector<YAML::Node> baseNode)
{
    try
    {
        debugs.clear();
        for (auto &document : baseNode)
        {
            debugs.emplace_back(document["debug"]);
        }
    }
    catch(const std::runtime_error& re)
    {
        NotifyError("Error en Runtime: ", "Util_Parser.cpp");
        NotifyError(re.what(), "Util_Parser.cpp");
    }
    catch(const std::exception& ex)
    {
        NotifyError("Ha ocurrido un error: ", "Util_Parser.cpp");
        NotifyError(ex.what(), "Util_Parser.cpp");
    }
    catch(...)
    {
        NotifyError("Error desconocido que no se ha podido especificar.", "Util_Parser.cpp");
    }
    return debugs.at(0);
}
Example #28
0
T FunctionHandlerDDL<T>::operator () (std::vector<std::string> const & args) const
{
	obj_t funcObj = LevelObject::create();

	obj_t returnType = LevelObject::create(type_t::type_type(), type_t::type_auto<T>());
	funcObj->addObject(name_t::name_return_type, returnType);

	obj_t argcObj = LevelObject::create(type_t::type_shortint(), int_s_t(args.size()));
	funcObj->addObject(name_t(key_name_argc()), argcObj);

	for (size_t index = 0; index < args.size(); ++index)
	{
		// TODO: Should make an arg_t for undefined types.
		obj_t argObj;
		if (index < _argt.size())
			obj_t argObj = LevelObject::create(_argt[index], args[index]);
		else
			obj_t argObj = LevelObject::create(type_t::type_string(), string_t(args[index]));

		name_t argName(parse_name(key_name_arg() + make_string(index)));

		funcObj->addObject(argName, argObj);
	}

	funcObj->addData(_data);

	obj_t returnValue = funcObj->getObject(name_t::name_return_value);
	return convert<T, obj_t>(returnValue);
}
Example #29
0
  void backwardOneInput(int layerId, const UpdateCallback& callback) {
    const MatrixPtr& inputMat = getInputValue(layerId);
    const MatrixPtr& inputGradMat = getInputGrad(layerId);
    const MatrixPtr& weightMat = weights_[layerId]->getW();
    const MatrixPtr& weightGradMat = weights_[layerId]->getWGrad();

    int dim = inputMat->getWidth();
    real* sampleGrad = sampleOut_.grad->getData();

    if (weightGradMat) {
      for (size_t i = 0; i < samples_.size(); ++i) {
        axpy(dim,
             sampleGrad[i],
             inputMat->getRowBuf(samples_[i].sampleId),
             weightGradMat->getRowBuf(samples_[i].labelId));
      }
      weights_[layerId]->incUpdate(callback);
    }

    if (inputGradMat) {
      for (size_t i = 0; i < samples_.size(); ++i) {
        axpy(dim,
             sampleGrad[i],
             weightMat->getRowBuf(samples_[i].labelId),
             inputGradMat->getRowBuf(samples_[i].sampleId));
      }
    }
  }
Example #30
0
static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsigned char>& data)
{
    RecipientCatcher sigCatcher;
    QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));

    // Write data to a temp file:
    QTemporaryFile f;
    f.open();
    f.write((const char*)data.data(), data.size());
    f.close();

    // Create a QObject, install event filter from PaymentServer
    // and send a file open event to the object
    QObject object;
    object.installEventFilter(server);
    QFileOpenEvent event(f.fileName());
    // If sending the event fails, this will cause sigCatcher to be empty,
    // which will lead to a test failure anyway.
    QCoreApplication::sendEvent(&object, &event);

    QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));

    // Return results from sigCatcher
    return sigCatcher.recipient;
}