hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
970df27bbd8f99dc06963233fda0aa18d6bbaf7f
2,258
hpp
C++
include/rllib/bundle/Bundle.hpp
loriswit/rllib
a09a73f8ac353db76454007b2ec95bf438c0fc1a
[ "MIT" ]
1
2022-02-15T17:49:44.000Z
2022-02-15T17:49:44.000Z
include/rllib/bundle/Bundle.hpp
loriswit/rllib
a09a73f8ac353db76454007b2ec95bf438c0fc1a
[ "MIT" ]
null
null
null
include/rllib/bundle/Bundle.hpp
loriswit/rllib
a09a73f8ac353db76454007b2ec95bf438c0fc1a
[ "MIT" ]
null
null
null
#ifndef RLLIB_BUNDLE_HPP #define RLLIB_BUNDLE_HPP #include <string> #include <rllib/stream/ByteStream.hpp> #include <rllib/bundle/FileProperties.hpp> namespace rl { /** * A bundle is a collection of files packed in a big single file. It is used to store all the game assets. * In particular, this is where scene are being extracted from the game. */ class RL_API Bundle { public: /** * Creates an empty bundle. */ Bundle() = default; /** * Creates a bundle loaded from a file. * * @param path The path to the bundle file */ explicit Bundle(FilePath path); /** * Load the bundle from a file. * * @param path The path to the bundle file */ void load(FilePath path); /** * Reads a file in the bundle and returns its content. * * @param path The path to the file in the bundle * @return The content of the file */ ByteStream readFile(const FilePath & path) const; /** * Overwrites a file in the bundle. * The file path must already exist in the bundle. * * @warning The original content will be lost. * * @param path The path to the file in the bundle * @param data The data that is to be written */ void writeFile(const FilePath & path, const ByteStream & data); /** * Creates a new bundle file and returns its instance. * * @param bundlePath The path to the new bundle file that is to be created * @param files A list of pairs containing file paths with associated contents * @return The instance of the new bundle */ static Bundle create(FilePath bundlePath, const std::vector<std::pair<FilePath, ByteStream>> & files); private: /** * Finds a file in the bundle index and returns its properties. * * @param path The path to the file in the bundle * @return A pair containing the file properties and the offset of the properties */ const std::pair<FileProperties, std::streampos> & findFile(const FilePath & path) const; FilePath m_path; std::vector<std::pair<FileProperties, std::streampos>> m_fileList; std::size_t m_baseOffset = 0; }; } // namespace rl #endif //RLLIB_BUNDLE_HPP
27.204819
106
0.647476
loriswit
970e072080a9ec4db50ac4aeb4e5ca80634a2942
18,605
cpp
C++
OOP/Project_2/main.cpp
moyfdzz/University-Projects
8d6ab689fd3fba43994494245e489b1c97544fbd
[ "MIT" ]
4
2018-04-27T00:03:39.000Z
2019-01-27T07:31:57.000Z
OOP/Project_2/main.cpp
moyfdzz/University-Projects
8d6ab689fd3fba43994494245e489b1c97544fbd
[ "MIT" ]
1
2018-04-08T18:55:36.000Z
2018-11-01T02:30:11.000Z
OOP/Project_2/main.cpp
moyfdzz/University-Assignments
8d6ab689fd3fba43994494245e489b1c97544fbd
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <iostream> using namespace std; #include "EjemploVideo.h" Materia materias[5]; Tema temas[10]; Autor autores[10]; EjemploVideo eVideos[20]; int cantidadTemasG = 0, cantidadAutoresG = 0, cantidadMateriasG = 0, cantidadEVideosG = 0; void cargarDatosMaterias() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de las materias" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaMaterias; listaMaterias.open(extensionArchivo); int cveMateria; string nombreMateria; while(listaMaterias >> cveMateria && getline(listaMaterias, nombreMateria)) { materias[cantidadMateriasG].setIdMateria(cveMateria); materias[cantidadMateriasG].setNombreMateria(nombreMateria); cantidadMateriasG++; } listaMaterias.close(); } void cargarDatosTemas() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de los temas" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaTemas; listaTemas.open(extensionArchivo); int idTema, idMateria; string nombreTema; while(listaTemas >> idTema >> idMateria && getline(listaTemas, nombreTema)) { temas[cantidadTemasG].setIdTema(idTema); temas[cantidadTemasG].setIdMateria(idMateria); temas[cantidadTemasG].setNombreTema(nombreTema); cantidadTemasG++; } listaTemas.close(); } void cargarDatosAutores() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de los autores" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaAutores; listaAutores.open(extensionArchivo); int idAutor; string nombreAutor; while(listaAutores >> idAutor && getline(listaAutores, nombreAutor)) { autores[cantidadAutoresG].setIdAutor(idAutor); autores[cantidadAutoresG].setNombreAutor(nombreAutor); cantidadAutoresG++; } listaAutores.close(); } void checarIdAutor(int numAutores, bool &idAutorExiste, int idAutor) { for (int counter2 = 0; counter2 < cantidadAutoresG; ++counter2) { if (autores[counter2].getIdAutor() == idAutor) { idAutorExiste = true; break; } else { idAutorExiste = false; } } } void checarIdTema(int idTema, bool &idTemaExiste) { for(int counter = 0; counter < cantidadTemasG; counter++) { if(idTema != temas[counter].getIdTema()) { idTemaExiste = false; } else { idTemaExiste = true; break; } } } void checarIdMateria(int idMateria, bool &idMateriaExiste) { for(int counter = 0; counter < cantidadTemasG; counter++) { if(idMateria != materias[counter].getIdMateria()) { idMateriaExiste = false; } else { idMateriaExiste = true; break; } } } void cargarDatosEVideos() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de los ejemplo videos" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaEVideos; listaEVideos.open(extensionArchivo); int idVideo, idTema, dia, mes, anio, numAutores, idAutor; Fecha fechaElaboracion; string nombreEVideo; bool idTemaExiste = true, idAutorExiste = true; while(listaEVideos >> idVideo >> nombreEVideo >> idTema >> dia >> mes >> anio >> numAutores) { cout << "Agregando video" << endl; int posAutores[numAutores]; for (int counter = 0; counter < numAutores; ++counter) { listaEVideos >> idAutor; checarIdAutor(numAutores, idAutorExiste, idAutor); if(!idAutorExiste) { break; } posAutores[counter] = idAutor; } checarIdTema(idTema, idTemaExiste); cout << idAutorExiste << idTemaExiste << endl; if (idAutorExiste && idTemaExiste) { fechaElaboracion.setFecha(dia, mes, anio); eVideos[cantidadEVideosG].setIdVideo(idVideo); eVideos[cantidadEVideosG].setNombreEjemploVideo(nombreEVideo); eVideos[cantidadEVideosG].setIdTema(idTema); eVideos[cantidadEVideosG].setFechaElaboracion(fechaElaboracion); for (int counter = 0; counter < numAutores; ++counter) { if (!eVideos[cantidadEVideosG].agregaAutor(posAutores[counter])) { cout << "El id del autor del video número " << posAutores[counter] << " es inválido." << endl; } } cout << eVideos[cantidadEVideosG].getNombreEjemploVideo() << endl; cantidadEVideosG++; cout << "Sumando a cantidad videos" << endl; } else { cout << "El video " << nombreEVideo << " tiene el o los id(s) del autor o del tema mal por "; cout << "lo que no fue contado." << endl; } cout << endl << endl; } listaEVideos.close(); } void mostrarMaterias() { cout << endl << "Materias" << endl; cout << endl << "ID Materia Nombre Materia" << endl; for(int counter = 0; counter < cantidadMateriasG; counter++) { cout << " " << materias[counter].getIdMateria(); cout << " " << materias[counter].getNombreMateria() << endl; } cout << endl; } void mostrarTemas() { cout << "Temas" << endl; cout << endl << "ID Tema ID Materia Nombre Tema" << endl; for(int counter = 0; counter < cantidadTemasG; counter++) { cout << " " << temas[counter].getIdTema(); cout << " " << temas[counter].getIdMateria() << " "; cout << " " << temas[counter].getNombreTema() << endl; } cout << endl; } void mostrarAutores() { cout << "Autores" << endl; cout << endl << "ID Autor Nombre Autor" << endl; for(int counter = 0; counter < cantidadAutoresG; counter++) { cout << " " << autores[counter].getIdAutor() << " "; cout << " " << autores[counter].getNombreAutor() << endl; } cout << endl; } void checarIdVideo(bool &idVideoExiste, int idVideo) { for (int counter = 0; counter < cantidadEVideosG; ++counter) { if (idVideo == eVideos[counter].getIdVideo()) { cout << "Este id se repite: " << idVideo << endl; idVideoExiste = false; break; } else { idVideoExiste = true; } } } void checarCantAutores(bool &cantAutoresPosible, int numAutoresUsuario) { if (numAutoresUsuario < 1 || numAutoresUsuario > 10) { cantAutoresPosible = false; } else { cantAutoresPosible = true; } } void agregarEVideos() { int idVideo, idTema, dia, mes, anio, numAutoresUsuario, idAutor; Fecha fechaElaboracion; string nombreEVideo; bool idTemaExiste = true, idAutorExiste = true, idVideoExiste = true, cantAutoresPosible = true; cout << "Ingrese el id del video" << endl; cin >> idVideo; checarIdVideo(idVideoExiste, idVideo); while(!idVideoExiste) { cout << "El id de video existe. Por favor ingrese uno diferente." << endl; cin >> idVideo; checarIdVideo(idVideoExiste, idVideo); } cin.ignore(); eVideos[cantidadEVideosG].setIdVideo(idVideo); cout << "Ingrese el nombre del video" << endl; getline(cin, nombreEVideo); eVideos[cantidadEVideosG].setNombreEjemploVideo(nombreEVideo); cout << "Ingrese el id del tema" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); while(!idTemaExiste) { cout << "El id del tema no es válido. Vuelva a ingresarlo" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); } eVideos[cantidadEVideosG].setIdTema(idTema); cout << "Ingrese el día en el que el video fue elaborado" << endl; cin >> dia; cout << "Ingrese el mes en el que el video fue elaborado (número)" << endl; cin >> mes; cout << "Ingrese el año en el que el video fue elaborado" << endl; cin >> anio; fechaElaboracion.setFecha(dia, mes, anio); eVideos[cantidadEVideosG].setFechaElaboracion(fechaElaboracion); cout << "Ingrese la cantidad de autores del video" << endl; cin >> numAutoresUsuario; checarCantAutores(cantAutoresPosible, numAutoresUsuario); while(!cantAutoresPosible) { cout << "La cantidad de autores debe ser entre 1 y 10. Por favor vuelva a ingresarla" << endl; cin >> numAutoresUsuario; checarCantAutores(cantAutoresPosible, numAutoresUsuario); } for (int counter = 0; counter < numAutoresUsuario; counter++) { cout << "Introduzca el id del autor número " << counter + 1 << endl; do { cin >> idAutor; checarIdAutor(numAutoresUsuario, idAutorExiste, idAutor); if (!idAutorExiste) { cout << "El id del autor no existe. Por favor vuelva a ingresarlo" << endl; } else { idAutorExiste = eVideos[cantidadEVideosG].agregaAutor(idAutor); if(!idAutorExiste) { cout << "El id del autor ya ha sido ingresado. Por favor introduzca otro" << endl; } else { cout << "Autor agregado cantidad: " << eVideos[cantidadEVideosG].getCantidadAutores() << endl; } } }while(!idAutorExiste); } cantidadEVideosG++; } void buscarPorTema() { int idTema; bool idTemaExiste = true; cout << "¿Cuál es el id del tema?" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); while(!idTemaExiste) { cout << "El id del tema que ingresó es inválido. Por favor vuelva a ingresarlo" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); } if(idTemaExiste) { cout << "Los datos de los videos con el id del tema " << idTema << " son los siguientes:" << endl; for(int counter = 0; counter < cantidadEVideosG; counter++) { if(idTema == eVideos[counter].getIdTema()) { cout << "ID del video: " << eVideos[counter].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[counter].getNombreEjemploVideo() << endl; cout << "Tema del video: "; for(int counter2 = 0; counter2 < cantidadEVideosG; counter2++) { if(idTema == eVideos[counter].getIdTema()) { cout << temas[counter2].getNombreTema() << endl; break; } } cout << "Fecha de elaboración: "; cout << eVideos[counter].getFechaElaboracion().getDd() << "."; cout << eVideos[counter].getFechaElaboracion().getMm() << "."; cout << eVideos[counter].getFechaElaboracion().getAa(); cout << endl << "Autor(es):" << endl; for(int counter2 = 0; counter2 < eVideos[counter].getCantidadAutores(); counter2++) { for(int counter3 = 0; counter3 < cantidadAutoresG; counter3++) { if(eVideos[counter].getListaAutores(counter2) == autores[counter3].getIdAutor()) { cout << " - " << autores[counter3].getNombreAutor() << endl; } } } cout << endl; } } } } void buscarPorMateria() { int idMateria; bool idMateriaExiste = true; cout << "Ingrese el id de la materia" << endl; cin >> idMateria; checarIdMateria(idMateria, idMateriaExiste); while(!idMateriaExiste) { cout << "El id de la materia que ingresó es inválido. Por favor vuelva a ingresarlo" << endl; cin >> idMateria; checarIdMateria(idMateria, idMateriaExiste); } if(idMateriaExiste) { cout << "Los datos de los videos con el id de la materia " << idMateria << " son los siguientes:" << endl; for(int counter = 0; counter < cantidadTemasG; counter++) { if(idMateria == temas[counter].getIdMateria()) { for (int counter2 = 0; counter2 < cantidadEVideosG; ++counter2) { if (temas[counter].getIdTema() == eVideos[counter2].getIdTema()) { cout << "ID del video: " << eVideos[counter2].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[counter2].getNombreEjemploVideo() << endl; cout << "ID del tema: " << eVideos[counter2].getIdTema() << endl; cout << "Fecha de elaboración: "; cout << eVideos[counter2].getFechaElaboracion().getDd() << "."; cout << eVideos[counter2].getFechaElaboracion().getMm() << "."; cout << eVideos[counter2].getFechaElaboracion().getAa(); cout << endl << "Autor(es):" << endl; for(int counter3 = 0; counter3 < eVideos[counter].getCantidadAutores(); counter3++) { for(int counter4 = 0; counter4 < cantidadAutoresG; counter4++) { if(eVideos[counter2].getListaAutores(counter3) == autores[counter4].getIdAutor()) { cout << " - " << autores[counter4].getNombreAutor() << endl; } } } cout << endl; } } } } } } void consultarVideos() { int counterTemporal, dia, mes, anio; cout << endl << "Videos" << endl << endl; for (int counter = 0; counter < cantidadEVideosG; ++counter) { cout << "Id del video: " << eVideos[counter].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[counter].getNombreEjemploVideo() << endl; cout << "Tema: "; for (int counter2 = 0; counter2 < cantidadTemasG; ++counter2) { if (temas[counter2].getIdTema() == eVideos[counter].getIdTema()) { cout << temas[counter2].getNombreTema() << endl; counterTemporal = counter2; break; } } cout << "Materia: "; for (int counter2 = 0; counter2 < cantidadMateriasG; ++counter2) { if (materias[counter2].getIdMateria() == temas[counterTemporal].getIdMateria()) { cout << materias[counter2].getNombreMateria() << endl; break; } } dia = eVideos[counter].getFechaElaboracion().getDd(); mes = eVideos[counter].getFechaElaboracion().getMm(); anio = eVideos[counter].getFechaElaboracion().getAa(); cout << "Fecha de Elaboracion: " << dia << "." << mes << "." << anio << endl; cout << "Autor(es): " << endl; for (int iCounter2 = 0; iCounter2 < eVideos[counter].getCantidadAutores(); ++iCounter2) { for (int iCounter3 = 0; iCounter3 < cantidadAutoresG; ++iCounter3) { if (eVideos[counter].getListaAutores(iCounter2) == autores[iCounter3].getIdAutor()) { cout << " - " << autores[iCounter3].getNombreAutor() << endl; } } } cout << endl; } } void buscarPorAutor() { int idAutor; bool idAutorExiste = false; cout << "Introduce el id del autor" << endl; cin >> idAutor; checarIdAutor(cantidadAutoresG, idAutorExiste, idAutor); while(!idAutorExiste) { cout << "El id del autor es inválido. Por favor introdzque uno correcto" << endl; cin >> idAutor; checarIdAutor(cantidadAutoresG, idAutorExiste, idAutor); } cout << endl << "Videos" << endl; for (int iCounter = 0; iCounter < cantidadEVideosG; ++iCounter) { for (int iCounter2 = 0; iCounter2 < eVideos[iCounter].getCantidadAutores(); ++iCounter2) { if (eVideos[iCounter].getListaAutores(iCounter2) == idAutor) { cout << "Id del video: " << eVideos[iCounter].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[iCounter].getNombreEjemploVideo() << endl; break; } } cout << endl; } } void menu(char &opcion) { do { cout << endl << "M E N U " << endl; cout << "a. consultar información de materias, temas y autores" << endl; cout << "b. dar de alta videos de ejemplo" << endl; cout << "c. consultar la lista de videos por tema" << endl; cout << "d. consultar la lista de videos por materia" << endl; cout << "e. consultar lista de videos" << endl; cout << "f. consultar videos por autor" << endl; cout << "g. terminar" << endl; cout << "Opcion -> "; cin >> opcion; switch (opcion) { case 'a': mostrarMaterias(); mostrarTemas(); mostrarAutores(); break; case 'b': agregarEVideos(); break; case 'c': buscarPorTema(); break; case 'd': buscarPorMateria(); break; case 'e': consultarVideos(); break; case 'f': buscarPorAutor(); break; } } while (opcion != 'g'); } //meter los ifstreams a cada función de cargar datos int main() { char opcion; cargarDatosMaterias(); cargarDatosTemas(); cargarDatosAutores(); cargarDatosEVideos(); menu(opcion); cantidadEVideosG++; return 0; }
28.623077
114
0.5448
moyfdzz
9710455bfa31dd6d4cbc8488a2e2b731c93b7598
2,848
cpp
C++
projects-lib/opengl-wrapper/draw/GLSquare.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
15
2019-01-13T16:07:27.000Z
2021-09-27T15:18:58.000Z
projects-lib/opengl-wrapper/draw/GLSquare.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
1
2019-03-14T00:36:35.000Z
2020-12-29T11:48:09.000Z
projects-lib/opengl-wrapper/draw/GLSquare.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
3
2020-03-02T21:28:56.000Z
2021-09-27T15:18:50.000Z
#include "GLSquare.h" #include <opengl-wrapper/PlatformGL.h> namespace openglWrapper { //short drawOrder[6] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices GLSquare::GLSquare() { } void GLSquare::draw(GLShaderColor *shader) { const int COORDS_PER_POS = 3; const int STRUCTURE_STRIDE_BYTES_POS = COORDS_PER_POS * sizeof(float); const int VERTEX_COUNT = 4; const float vertexBuffer[12] = { -1.0f, 1.0f, 0.0f, // top left -1.0f, -1.0f, 0.0f, // bottom left 1.0f, -1.0f, 0.0f, // bottom right 1.0f, 1.0f, 0.0f }; // top right // // Set the vertex position attrib array // OPENGL_CMD(glEnableVertexAttribArray(GLShaderColor::vPosition)); OPENGL_CMD(glVertexAttribPointer(GLShaderColor::vPosition, COORDS_PER_POS, GL_FLOAT, false, STRUCTURE_STRIDE_BYTES_POS, vertexBuffer)); // // Draw quad // OPENGL_CMD(glDrawArrays(GL_TRIANGLE_FAN, 0, VERTEX_COUNT)); // // Disable arrays after draw // OPENGL_CMD(glDisableVertexAttribArray(GLShaderTextureColor::vPosition)); } void GLSquare::draw(GLShaderTextureColor *shader) { const int COORDS_PER_POS = 3; const int STRUCTURE_STRIDE_BYTES_POS = COORDS_PER_POS * sizeof(float); const int COORDS_PER_UV = 2; const int STRUCTURE_STRIDE_BYTES_UV = COORDS_PER_UV * sizeof(float); const int VERTEX_COUNT = 4; const float vertexBuffer[12] = { -1.0f, 1.0f, 0.0f, // top left -1.0f, -1.0f, 0.0f, // bottom left 1.0f, -1.0f, 0.0f, // bottom right 1.0f, 1.0f, 0.0f }; // top right const float uvBuffer[8] = { 0, 0, // top left 0, 1, // bottom left 1, 1, // bottom right 1, 0 }; // top right // // Set the vertex position attrib array // OPENGL_CMD(glEnableVertexAttribArray(GLShaderTextureColor::vPosition)); OPENGL_CMD(glVertexAttribPointer(GLShaderTextureColor::vPosition, COORDS_PER_POS, GL_FLOAT, false, STRUCTURE_STRIDE_BYTES_POS, vertexBuffer)); // // Set the vertex uv attrib array // OPENGL_CMD(glEnableVertexAttribArray(GLShaderTextureColor::vUV)); OPENGL_CMD(glVertexAttribPointer(GLShaderTextureColor::vUV, COORDS_PER_UV, GL_FLOAT, false, STRUCTURE_STRIDE_BYTES_UV, uvBuffer)); // // Draw quad // OPENGL_CMD(glDrawArrays(GL_TRIANGLE_FAN, 0, VERTEX_COUNT)); // // Disable arrays after draw // OPENGL_CMD(glDisableVertexAttribArray(GLShaderTextureColor::vPosition)); OPENGL_CMD(glDisableVertexAttribArray(GLShaderTextureColor::vUV)); } }
30.956522
150
0.601475
A-Ribeiro
9710f58c33f0561bfe2070f30e4e86b72d6a9a41
10,075
cc
C++
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * DEBUG: section 29 Negotiate Authenticator * AUTHOR: Robert Collins, Henrik Nordstrom, Francesco Chemolli * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * */ /* The functions in this file handle authentication. * They DO NOT perform access control or auditing. * See acl.c for access control and client_side.c for auditing */ #include "squid.h" #include "auth/negotiate/auth_negotiate.h" #include "auth/Gadgets.h" #include "auth/State.h" #include "cache_cf.h" #include "mgr/Registration.h" #include "Store.h" #include "client_side.h" #include "HttpHeaderTools.h" #include "HttpReply.h" #include "HttpRequest.h" #include "SquidTime.h" #include "auth/negotiate/Scheme.h" #include "auth/negotiate/User.h" #include "auth/negotiate/UserRequest.h" #include "wordlist.h" /** \defgroup AuthNegotiateInternal Negotiate Authenticator Internals \ingroup AuthNegotiateAPI */ /* Negotiate Scheme */ static AUTHSSTATS authenticateNegotiateStats; /// \ingroup AuthNegotiateInternal statefulhelper *negotiateauthenticators = NULL; /// \ingroup AuthNegotiateInternal static int authnegotiate_initialised = 0; /// \ingroup AuthNegotiateInternal static hash_table *proxy_auth_cache = NULL; /* * * Private Functions * */ void Auth::Negotiate::Config::rotateHelpers() { /* schedule closure of existing helpers */ if (negotiateauthenticators) { helperStatefulShutdown(negotiateauthenticators); } /* NP: dynamic helper restart will ensure they start up again as needed. */ } void Auth::Negotiate::Config::done() { authnegotiate_initialised = 0; if (negotiateauthenticators) { helperStatefulShutdown(negotiateauthenticators); } if (!shutting_down) return; delete negotiateauthenticators; negotiateauthenticators = NULL; if (authenticateProgram) wordlistDestroy(&authenticateProgram); debugs(29, DBG_IMPORTANT, "Reconfigure: Negotiate authentication configuration cleared."); } void Auth::Negotiate::Config::dump(StoreEntry * entry, const char *name, Auth::Config * scheme) { wordlist *list = authenticateProgram; storeAppendPrintf(entry, "%s %s", name, "negotiate"); while (list != NULL) { storeAppendPrintf(entry, " %s", list->key); list = list->next; } storeAppendPrintf(entry, "\n%s negotiate children %d startup=%d idle=%d concurrency=%d\n", name, authenticateChildren.n_max, authenticateChildren.n_startup, authenticateChildren.n_idle, authenticateChildren.concurrency); storeAppendPrintf(entry, "%s %s keep_alive %s\n", name, "negotiate", keep_alive ? "on" : "off"); } Auth::Negotiate::Config::Config() : keep_alive(1) { } void Auth::Negotiate::Config::parse(Auth::Config * scheme, int n_configured, char *param_str) { if (strcasecmp(param_str, "program") == 0) { if (authenticateProgram) wordlistDestroy(&authenticateProgram); parse_wordlist(&authenticateProgram); requirePathnameExists("auth_param negotiate program", authenticateProgram->key); } else if (strcasecmp(param_str, "children") == 0) { authenticateChildren.parseConfig(); } else if (strcasecmp(param_str, "keep_alive") == 0) { parse_onoff(&keep_alive); } else { debugs(29, DBG_CRITICAL, "ERROR: unrecognised Negotiate auth scheme parameter '" << param_str << "'"); } } const char * Auth::Negotiate::Config::type() const { return Auth::Negotiate::Scheme::GetInstance()->type(); } /** * Initialize helpers and the like for this auth scheme. * Called AFTER parsing the config file */ void Auth::Negotiate::Config::init(Auth::Config * scheme) { if (authenticateProgram) { authnegotiate_initialised = 1; if (negotiateauthenticators == NULL) negotiateauthenticators = new statefulhelper("negotiateauthenticator"); if (!proxy_auth_cache) proxy_auth_cache = hash_create((HASHCMP *) strcmp, 7921, hash_string); assert(proxy_auth_cache); negotiateauthenticators->cmdline = authenticateProgram; negotiateauthenticators->childs.updateLimits(authenticateChildren); negotiateauthenticators->ipc_type = IPC_STREAM; helperStatefulOpenServers(negotiateauthenticators); } } void Auth::Negotiate::Config::registerWithCacheManager(void) { Mgr::RegisterAction("negotiateauthenticator", "Negotiate User Authenticator Stats", authenticateNegotiateStats, 0, 1); } bool Auth::Negotiate::Config::active() const { return authnegotiate_initialised == 1; } bool Auth::Negotiate::Config::configured() const { if (authenticateProgram && (authenticateChildren.n_max != 0)) { debugs(29, 9, HERE << "returning configured"); return true; } debugs(29, 9, HERE << "returning unconfigured"); return false; } /* Negotiate Scheme */ void Auth::Negotiate::Config::fixHeader(Auth::UserRequest::Pointer auth_user_request, HttpReply *rep, http_hdr_type reqType, HttpRequest * request) { if (!authenticateProgram) return; /* Need keep-alive */ if (!request->flags.proxyKeepalive && request->flags.mustKeepalive) return; /* New request, no user details */ if (auth_user_request == NULL) { debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate"); if (!keep_alive) { /* drop the connection */ rep->header.delByName("keep-alive"); request->flags.proxyKeepalive = 0; } } else { Auth::Negotiate::UserRequest *negotiate_request = dynamic_cast<Auth::Negotiate::UserRequest *>(auth_user_request.getRaw()); assert(negotiate_request != NULL); switch (negotiate_request->user()->credentials()) { case Auth::Failed: /* here it makes sense to drop the connection, as auth is * tied to it, even if MAYBE the client could handle it - Kinkie */ rep->header.delByName("keep-alive"); request->flags.proxyKeepalive = 0; /* fall through */ case Auth::Ok: /* Special case: authentication finished OK but disallowed by ACL. * Need to start over to give the client another chance. */ if (negotiate_request->server_blob) { debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate " << negotiate_request->server_blob << "'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate %s", negotiate_request->server_blob); safe_free(negotiate_request->server_blob); } else { debugs(29, 9, HERE << "Connection authenticated"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate"); } break; case Auth::Unchecked: /* semantic change: do not drop the connection. * 2.5 implementation used to keep it open - Kinkie */ debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate"); break; case Auth::Handshake: /* we're waiting for a response from the client. Pass it the blob */ debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate " << negotiate_request->server_blob << "'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate %s", negotiate_request->server_blob); safe_free(negotiate_request->server_blob); break; default: debugs(29, DBG_CRITICAL, "ERROR: Negotiate auth fixHeader: state " << negotiate_request->user()->credentials() << "."); fatal("unexpected state in AuthenticateNegotiateFixErrorHeader.\n"); } } } static void authenticateNegotiateStats(StoreEntry * sentry) { helperStatefulStats(sentry, negotiateauthenticators, "Negotiate Authenticator Statistics"); } /* * Decode a Negotiate [Proxy-]Auth string, placing the results in the passed * Auth_user structure. */ Auth::UserRequest::Pointer Auth::Negotiate::Config::decode(char const *proxy_auth) { Auth::Negotiate::User *newUser = new Auth::Negotiate::User(Auth::Config::Find("negotiate")); Auth::UserRequest *auth_user_request = new Auth::Negotiate::UserRequest(); assert(auth_user_request->user() == NULL); auth_user_request->user(newUser); auth_user_request->user()->auth_type = Auth::AUTH_NEGOTIATE; /* all we have to do is identify that it's Negotiate - the helper does the rest */ debugs(29, 9, HERE << "decode Negotiate authentication"); return auth_user_request; }
33.250825
151
0.669181
spaceify
97119b216fa931d06d1caaf67a230202aa9805f0
451
cpp
C++
game/tile.cpp
StylishTriangles/Scrabble
9d24a598ad552533d1cdf4a47fae586d8f6cb607
[ "MIT" ]
null
null
null
game/tile.cpp
StylishTriangles/Scrabble
9d24a598ad552533d1cdf4a47fae586d8f6cb607
[ "MIT" ]
null
null
null
game/tile.cpp
StylishTriangles/Scrabble
9d24a598ad552533d1cdf4a47fae586d8f6cb607
[ "MIT" ]
null
null
null
#include "tile.h" /** * @brief Default constructor for Tile. **/ Tile::Tile() : modified(false), bonus(BONUS_NONE), letter(L' '), backup(letter) { } /** * @brief Set character representing this Tile. * @param ch: Character to represent this Tile object. **/ void Tile::set(wchar_t ch) { if (ch != letter) { if (!modified) { backup = letter; modified = true; } letter = ch; } }
16.703704
54
0.547672
StylishTriangles
97147701e11e92d08470269a5d390fa33c4699b5
6,715
cpp
C++
src/tcp/socket_manager.cpp
alipay/sofa-bolt-cpp
6f422c0a8767ff8292db2b7c0557f9990219eb6b
[ "Apache-2.0" ]
13
2018-09-05T07:10:11.000Z
2019-04-30T01:31:32.000Z
src/tcp/socket_manager.cpp
sofastack/sofa-bolt-cpp
6f422c0a8767ff8292db2b7c0557f9990219eb6b
[ "Apache-2.0" ]
1
2018-11-03T03:54:40.000Z
2018-11-05T11:37:33.000Z
src/tcp/socket_manager.cpp
sofastack/sofa-bolt-cpp
6f422c0a8767ff8292db2b7c0557f9990219eb6b
[ "Apache-2.0" ]
2
2019-09-08T13:52:09.000Z
2021-04-21T08:42:08.000Z
// Copyright (c) 2018 Ant Financial, Inc. All Rights Reserved // Created by zhenggu.xwt on 18/4/13. // #include "socket_manager.h" #include <future> #include <poll.h> #include "common/utils.h" #include "session/session.h" #include "schedule/schedule.h" #include "common/log.h" namespace antflash { bool SocketManager::init() { _exit.store(false, std::memory_order_release); int reclaim_fd[2]; reclaim_fd[0] = -1; reclaim_fd[1] = -1; if (pipe(reclaim_fd) != 0) { return false; } _reclaim_fd[0] = reclaim_fd[0]; _reclaim_fd[1] = reclaim_fd[1]; auto size = Schedule::getInstance().scheduleThreadSize(); _on_reclaim.reserve(size); _reclaim_notify_flag.resize(size, false); for (size_t i = 0; i < size; ++i) { _on_reclaim.emplace_back([this, i]() { _reclaim_notify_flag[i] = true; Schedule::getInstance().removeSchedule( _reclaim_fd[1].fd(), POLLOUT, i); std::lock_guard<std::mutex> guard(_reclaim_mtx); _reclaim_notify.notify_one(); }); } _thread.reset(new std::thread([this](){ while (!_exit.load(std::memory_order_acquire)) { watchConnections(); std::this_thread::sleep_for(std::chrono::seconds(1)); } })); return true; } void SocketManager::destroy() { _exit.store(true, std::memory_order_release); if (_thread && _thread->joinable()) { _thread->join(); _thread.reset(); } //reclaim all socket's memory for (auto& socket : _list) { //If channel still holds exclusive when socket manager destroy, //which means channel is still alive when whole process is //going to shut down, in this case, we granted that no more //socket request will be sent, and related socket will be // destroyed in channel. if (socket->_sharers.tryUpgrade()) { socket->_sharers.exclusive(); } //Just push to reclaim list _reclaim_list.push_back(socket); } _list.clear(); //As socket manager is destroyed after schedule manager, clear reclaim list directly for (auto socket : _reclaim_list) { socket->_on_read = std::function<void()>(); LOG_DEBUG("reset socket:{}", socket->fd()); } _reclaim_list.clear(); } void SocketManager::addWatch(std::shared_ptr<Socket>& socket) { std::lock_guard<std::mutex> lock_guard(_mtx); _list.push_back(socket); } void SocketManager::watchConnections() { std::vector<std::shared_ptr<Socket>> sockets; //1. Collect sockets to be reclaimed or to be watched { std::lock_guard<std::mutex> lock_guard(_mtx); sockets.reserve(_list.size()); for (auto itr = _list.begin(); itr != _list.end();) { //As channel always exclusive it's socket when socket is active //If socket's exclusive status can be catch in socket manager, //it means this socket needs to be reclaimed. if ((*itr)->tryExclusive()) { LOG_INFO("socket[{}] is going to be reclaimed.", (*itr)->fd()); //Disconnect socket just remove OnRead handler, we can not reclaim this // socket directly after disconnect as schedule manager may still call // this socket's OnRead event in its loop before it receive schedule // remove message, we could only do it in next loop. (*itr)->disconnect(); _reclaim_list.emplace_back(*itr); itr = _list.erase(itr); } else { sockets.emplace_back(*itr); ++itr; } } } //2. Try to reclaim socket if (!_reclaim_list.empty()) { size_t schedule_size = Schedule::getInstance().scheduleThreadSize(); size_t cur_idx = _reclaim_counter++ % schedule_size; _reclaim_notify_flag[cur_idx] = false; Schedule::getInstance().addSchedule( _reclaim_fd[1].fd(), POLLOUT, _on_reclaim[cur_idx], cur_idx); std::unique_lock<std::mutex> lock(_reclaim_mtx); auto status = _reclaim_notify.wait_for( lock, std::chrono::milliseconds(500), [this, cur_idx]() { return _reclaim_notify_flag[cur_idx]; }); //Receiving notify successfully from schedule must happen in next loop as //adding schedule of reclaim is after removing schedule of sockets. //And in this case, sockets can be reclaimed safety. if (status) { for (auto itr = _reclaim_list.begin(); itr != _reclaim_list.end();) { if (((*itr)->fd() % schedule_size) == cur_idx) { //release socket shared_from_this so that memory can be reclaimed (*itr)->_on_read = std::function<void()>(); LOG_DEBUG("reset socket:{}", (*itr)->fd()); itr = _reclaim_list.erase(itr); } else { ++itr; } } } } //3. send heartbeat to watch sockets for (auto& socket : sockets) { //If socket status is not active, and still in watch list, it means //this socket is not used by any other session yet, just skip it if (!socket->active()) { continue; } auto last_active_time = socket->get_last_active_time(); if (SOCKET_MAX_IDLE_US < Utils::getHighPrecisionTimeStamp() - last_active_time) { if (socket->_protocol && socket->_protocol->assemble_heartbeat_fn) { std::shared_ptr<RequestBase> request; std::shared_ptr<ResponseBase> response; if (socket->_protocol->assemble_heartbeat_fn(request, response)) { Session ss; ss.send(*request) .to(socket) .timeout(SOCKET_TIMEOUT_MS) .receiveTo(*response) .sync(); if (ss.failed()) { socket->setStatus(RPC_STATUS_SOCKET_CONNECT_FAIL); } else { if (!socket->_protocol->parse_heartbeat_fn(response)) { socket->setStatus(RPC_STATUS_SOCKET_CONNECT_FAIL); } else { LOG_INFO("remote[{}] heartbeat success", socket->getRemote().ipToStr()); } } } } } } } }
36.494565
88
0.554728
alipay
971667fd5c4d2259c9287db4407c7eaa04968372
10,064
cpp
C++
src/subsys/CompBot/CompBotChassis.cpp
Team302/2017Steamworks
757a5332c47dd007482e30ee067852d13582ba39
[ "MIT" ]
null
null
null
src/subsys/CompBot/CompBotChassis.cpp
Team302/2017Steamworks
757a5332c47dd007482e30ee067852d13582ba39
[ "MIT" ]
1
2018-09-07T14:14:28.000Z
2018-09-13T04:01:33.000Z
src/subsys/CompBot/CompBotChassis.cpp
Team302/2017Steamworks
757a5332c47dd007482e30ee067852d13582ba39
[ "MIT" ]
null
null
null
/* * CompBotChassis.cpp * * Created on: Jan 16, 2017 * Author: Austin/Neethan */ #include <utils/DragonTalon.h> #include <utils/LimitValue.h> #include <subsys/CompBot/CompBotChassis.h> #include <subsys/CompBot/CompMap.h> #include <subsys/interfaces/IChassis.h> #include <SmartDashboard/SmartDashboard.h> namespace Team302 { float CompBotChassis::GetLeftDistance() const { return GetRightDistance(); } float CompBotChassis::GetRightDistance() const { float rightPos = m_rightMasterMotor->GetEncPosition(); frc::SmartDashboard::PutNumber("encoder distance conversion", ENCODER_DISTANCE_CONVERSION); return ((rightPos) * ENCODER_DISTANCE_CONVERSION ); } float CompBotChassis::GetLeftBackDistance() const { return GetRightBackDistance(); } float CompBotChassis::GetLeftFrontDistance() const { return GetRightFrontDistance(); } float CompBotChassis::GetRightBackDistance() const { return GetRightDistance(); } float CompBotChassis::GetRightFrontDistance() const { return GetRightDistance(); } float CompBotChassis::GetLeftVelocity() const { return GetRightVelocity(); } float CompBotChassis::GetRightVelocity() const { float rightMotorVel = m_rightMasterMotor->GetEncVel(); return ((rightMotorVel) * ENCODER_VELOCITY_CONVERSION ); } float CompBotChassis::GetLeftBackVelocity() const { return GetRightBackVelocity(); } float CompBotChassis::GetLeftFrontVelocity() const { return GetRightFrontVelocity(); } float CompBotChassis::GetRightBackVelocity() const { return GetRightVelocity(); } float CompBotChassis::GetRightFrontVelocity() const { return GetRightVelocity(); } void CompBotChassis::ResetDistance() { m_leftSlaveMotor->Reset(); m_leftMasterMotor->Reset(); m_rightSlaveMotor->Reset(); m_rightMasterMotor->Reset(); } void CompBotChassis::SetLeftPower(float power) { //Make sure the left side speed is within range and then set both left motors to this speed float leftSpeed = LimitValue::ForceInRange( power, -0.98, 0.98 ); m_leftMasterMotor->Set( leftSpeed ); } void CompBotChassis::SetRightPower(float power) { // Make sure the right side speed is within range and then set both right motors to this speed float rightSpeed = LimitValue::ForceInRange( power, -0.98, 0.98 ); m_rightMasterMotor->Set( rightSpeed ); } void CompBotChassis::SetBrakeMode(bool mode) { if(mode) { m_leftSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); m_rightSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); m_leftMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); m_rightMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); } else { m_leftSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); m_rightSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); m_leftMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); m_rightMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); } } void CompBotChassis::SetControlMode(DragonTalon::DRAGON_CONTROL_MODE mode) { switch (mode) { case DragonTalon::POSITION: m_rightMasterMotor->SetControlMode(DragonTalon::POSITION); m_leftMasterMotor->SetControlMode(DragonTalon::POSITION); break; case DragonTalon::VELOCITY: m_rightMasterMotor->SetControlMode(DragonTalon::VELOCITY); m_leftMasterMotor->SetControlMode(DragonTalon::VELOCITY); break; case DragonTalon::THROTTLE: m_rightMasterMotor->SetControlMode(DragonTalon::THROTTLE); m_leftMasterMotor->SetControlMode(DragonTalon::THROTTLE); break; case DragonTalon::FOLLOWER: m_rightMasterMotor->SetControlMode(DragonTalon::FOLLOWER); m_leftMasterMotor->SetControlMode(DragonTalon::FOLLOWER); break; default: m_rightMasterMotor->SetControlMode(DragonTalon::THROTTLE); m_leftMasterMotor->SetControlMode(DragonTalon::THROTTLE); } } //---------------------------------------------------------------------------------- // Method: SetControlParams // Description: Sets PID and F factors to the motors and sets target. Target is // double for position in feet. Make sure to set // motor to POSITION control first. Once target is set, // motor will immediately start using it for position control // Params: double kP - proportional-gain value // double kI - integral-gain value // double kD - derivative-gain value // double kF - feed-forward factor // double leftTarget - target position in feet for left // double rightTarget - target position in feet for right //---------------------------------------------------------------------------------- void CompBotChassis::SetPositionParams(double kP, double kI, double kD, double kF, double leftTarget, double rightTarget) { m_rightMasterMotor->SetF(kF); //set feed-forward gain m_rightMasterMotor->SetP(kP); //set p-gain m_rightMasterMotor->SetI(kI); //set i-gain m_rightMasterMotor->SetD(kD); //set d-gain m_leftMasterMotor->SetF(kF); //set feed-forward gain m_leftMasterMotor->SetP(kP); //set p-gain m_leftMasterMotor->SetI(kI); //set i-gain m_leftMasterMotor->SetD(kD); //set d-gain m_rightMasterMotor->Set(rightTarget * FEET_TO_ROTATIONS); //set target position in rotations m_leftMasterMotor->Set(leftTarget * FEET_TO_ROTATIONS); //set target position in rotations } //---------------------------------------------------------------------------------- // Method: SetVelocityParams // Description: Sets PID and F factors to the motors and sets target. Target is // double for velocity in feet per second. Make sure to set // motor to VELOCITY control first. Once target is set, // motor will immediately start using it for velocity control // Params: double kP - proportional-gain value // double kI - integral-gain value // double kD - derivative-gain value // double kF - feed-forward factor // double leftTarget - target speed in feet per second for left // double rightTarget - target speed in feet per second for right //---------------------------------------------------------------------------------- void CompBotChassis::SetVelocityParams(double kP, double kI, double kD, double kF, double leftTarget, double rightTarget) { // SetControlMode(DragonTalon::VELOCITY); m_rightMasterMotor->SetF(kF); //set feed-forward gain m_rightMasterMotor->SetP(kP); //set p-gain m_rightMasterMotor->SetI(kI); //set i-gain m_rightMasterMotor->SetD(kD); //set d-gain m_leftMasterMotor->SetF(kF); //set feed-forward gain m_leftMasterMotor->SetP(kP); //set p-gain m_leftMasterMotor->SetI(kI); //set i-gain m_leftMasterMotor->SetD(kD); //set d-gain m_rightMasterMotor->Set(rightTarget * FPS_TO_RPM); //set target speed, converts from feet per second to rpm for talon use m_leftMasterMotor->Set(leftTarget * FPS_TO_RPM); //set target speed, converts from feet per second to rpm for talon use } void CompBotChassis::EnableCurrentLimiting() //Y key on driver { //Enable current limit m_leftMasterMotor->EnableCurrentLimit(true); m_leftSlaveMotor->EnableCurrentLimit(true); m_rightMasterMotor->EnableCurrentLimit(true); m_rightSlaveMotor->EnableCurrentLimit(true); } void CompBotChassis::DisableCurrentLimiting() //A key on driver { //Disable current limiting m_leftMasterMotor->EnableCurrentLimit(false); m_leftSlaveMotor->EnableCurrentLimit(false); m_rightMasterMotor->EnableCurrentLimit(false); m_rightSlaveMotor->EnableCurrentLimit(false); } void CompBotChassis::SetCurrentLimit(int amps) { //Set current limit m_leftMasterMotor->SetCurrentLimit(amps); m_leftSlaveMotor->SetCurrentLimit(amps); m_rightMasterMotor->SetCurrentLimit(amps); m_rightSlaveMotor->SetCurrentLimit(amps); } CompBotChassis::CompBotChassis(): //declare all of the motors m_leftSlaveMotor(new DragonTalon(LEFT_FRONT_DRIVE_MOTOR)), m_rightSlaveMotor(new DragonTalon(RIGHT_FRONT_DRIVE_MOTOR)), m_leftMasterMotor(new DragonTalon(LEFT_BACK_DRIVE_MOTOR)), m_rightMasterMotor(new DragonTalon(RIGHT_BACK_DRIVE_MOTOR)) { // Left Back Motor m_leftMasterMotor->SetFeedbackDevice(CANTalon::CtreMagEncoder_Relative); //sets the left master talon to use encoder as sensor m_leftMasterMotor->ConfigEncoderCodesPerRev(DRIVE_COUNTS_PER_REVOLUTION), // defines encoder counts per revolution m_leftMasterMotor->SetInverted (IS_LEFT_BACK_DRIVE_MOTOR_INVERTED); m_leftMasterMotor->SetSensorDirection (IS_LEFT_BACK_DRIVE_ENCODER_INVERTED); // Left Front Motor m_leftSlaveMotor->SetControlMode(DragonTalon::FOLLOWER); //sets the front left slave to follow output of the master m_leftSlaveMotor->Set(LEFT_BACK_DRIVE_MOTOR); //specifies that the left slave will follow master m_leftSlaveMotor->SetInverted(IS_LEFT_FRONT_DRIVE_MOTOR_INVERTED); // Right Back Motor m_rightMasterMotor->SetFeedbackDevice(CANTalon::CtreMagEncoder_Relative); //sets the right master talon to use encoder as sensor m_rightMasterMotor->ConfigEncoderCodesPerRev(DRIVE_COUNTS_PER_REVOLUTION), // defines encoder counts per revolution m_rightMasterMotor->SetInverted (IS_RIGHT_BACK_DRIVE_MOTOR_INVERTED); m_rightMasterMotor->SetSensorDirection (IS_RIGHT_BACK_DRIVE_ENCODER_INVERTED); // Right Front Motor m_rightSlaveMotor->SetControlMode(DragonTalon::FOLLOWER); //sets the front right to follow output of the master m_rightSlaveMotor->Set(RIGHT_BACK_DRIVE_MOTOR); //specifies that the right slave will follow master m_rightSlaveMotor->SetInverted (IS_RIGHT_FRONT_DRIVE_MOTOR_INVERTED); SetCurrentLimit( TALON_CURRENT_LIMIT ); EnableCurrentLimiting(); // //Enable current limit // m_leftMasterMotor->EnableCurrentLimit(true); // m_leftSlaveMotor->EnableCurrentLimit(true); // m_rightMasterMotor->EnableCurrentLimit(true); // m_rightSlaveMotor->EnableCurrentLimit(true); // // //Set current limit // m_leftMasterMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); // m_leftSlaveMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); // m_rightMasterMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); // m_rightSlaveMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); } } /* namespace Team302 */
35.066202
129
0.760036
Team302
9717b27939f1cd716d928179a9561929900d5c66
3,709
cpp
C++
src/base/muduo/net/poller/poll_poller.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
src/base/muduo/net/poller/poll_poller.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
src/base/muduo/net/poller/poll_poller.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
#include "muduo/net/poller/poll_poller.h" #include "muduo/net/common/channel.h" #include "muduo/base/common/logging.h" #include "define/define_types.h" #include <asm-generic/errno-base.h> #include <assert.h> #include <errno.h> #include <poll.h> #include <sys/cdefs.h> using namespace muduo; using namespace muduo::net; PollPoller::PollPoller(EventLoop* loop) : Poller(loop) { } PollPoller::~PollPoller() = default; TimeStamp PollPoller::poll(SDWORD timeoutMs, ChannelList* activeChannels) { // XXX pollfds_ shouldn't change SDWORD numEvents = ::poll(&*m_pollfds.begin(), m_pollfds.size(), timeoutMs); SDWORD savedErrno = errno; TimeStamp now(TimeStamp::now()); if (numEvents > 0) { LOG_TRACE << numEvents << " events happened"; fillActiveChannels(numEvents, activeChannels); } else if (numEvents == 0) { LOG_TRACE << " nothing happened"; } else { if (savedErrno != EINTR) { errno = savedErrno; LOG_SYSERR << "PollPoller::poll()"; } } return now; } void PollPoller::fillActiveChannels(SDWORD numEvents, ChannelList* activeChannels) const { for (PollFdList::const_iterator pfd = m_pollfds.begin(); pfd != m_pollfds.end() && numEvents > 0; ++ pfd) { if (pfd->revents > 0) { -- numEvents; ChannelMap::const_iterator ch = m_channels.find(pfd->fd); assert(ch != m_channels.end()); Channel* channel = ch->second; assert(channel->getFd() == pfd->fd); channel->setRevents(pfd->revents); activeChannels->push_back(channel); } } } void PollPoller::UpdateChannel(Channel* channel) { Poller::AssertInLoopThread(); LOG_TRACE << "fd = " << channel->getFd() << " events = " << channel->getEvents(); if (channel->getIndex() < 0) { // a new one, add to pollfds_ assert(m_channels.find(channel->getFd()) == m_channels.end()); struct pollfd pfd; pfd.fd = channel->getFd(); pfd.events = static_cast<SWORD>(channel->getEvents()); pfd.revents = 0; m_pollfds.push_back(pfd); SDWORD idx = static_cast<SDWORD>(m_pollfds.size()) - 1; channel->setIndex(idx); m_channels[pfd.fd] = channel; } else { // update existing one assert(m_channels.find(channel->getFd()) != m_channels.end()); assert(m_channels[channel->getFd()] == channel); SDWORD idx = channel->getIndex(); assert(0 <= idx && idx < static_cast<SDWORD>(m_pollfds.size())); struct pollfd& pfd = m_pollfds[idx]; assert(pfd.fd == channel->getFd() || pfd.fd == -channel->getFd()-1); pfd.fd = channel->getFd(); pfd.events = static_cast<SWORD>(channel->getEvents()); pfd.revents = 0; if (channel->IsNoneEvent()) { pfd.fd = -channel->getFd() - 1; // 删除,屏蔽掉这个fd } } } void PollPoller::RemoveChannel(Channel* channel) { Poller::AssertInLoopThread(); LOG_TRACE << "fd = " << channel->getFd(); assert(m_channels.find(channel->getFd()) != m_channels.end()); assert(m_channels[channel->getFd()] == channel); assert(channel->IsNoneEvent()); SDWORD idx = channel->getIndex(); assert(0 <= idx && idx < static_cast<SDWORD>(m_pollfds.size())); const struct pollfd& pfd = m_pollfds[idx]; (void)pfd; assert(pfd.fd == -channel->getFd()-1 && pfd.events == channel->getEvents()); size_t n = m_channels.erase(channel->getFd()); assert(n == 1); (void)n; if (implicit_cast<size_t>(idx) == m_pollfds.size() - 1) { m_pollfds.pop_back(); } else { SDWORD channelAtEnd = m_pollfds.back().fd; iter_swap(m_pollfds.begin() + idx, m_pollfds.end() - 1); if (channelAtEnd < 0) { channelAtEnd = -channelAtEnd - 1; } m_channels[channelAtEnd]->setIndex(idx); m_pollfds.pop_back(); } }
28.312977
88
0.640874
sbfhy
97183bf80c9dbf7b6f32600a7f96ade0928d99f5
4,191
cpp
C++
Practice/2018/2018.12.29/BZOJ5417.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.12.29/BZOJ5417.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.12.29/BZOJ5417.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<vector> #include<iostream> using namespace std; #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define ll long long #define NAME "name" const int maxL=505000*2; const int maxAlpha=26; class Node{ public: int son[maxAlpha],fail,len; }; class SAM{ public: int nodecnt,root,lst,Pos[maxL]; Node S[maxL]; SAM(){ nodecnt=root=lst=1;return; } void Init(){ nodecnt=root=lst=1;mem(S[1].son,0);S[1].fail=S[1].len=0;Pos[1]=0; return; } int New(){ int p=++nodecnt;S[p].len=S[p].fail=0;mem(S[p].son,0);Pos[p]=0;return p; } void Extend(int c,int id){ int np=New(),p=lst;lst=np;S[np].len=S[p].len+1;Pos[np]=id; while (p&&!S[p].son[c]) S[p].son[c]=np,p=S[p].fail; if (!p) S[np].fail=root; else{ int q=S[p].son[c]; if (S[q].len==S[p].len+1) S[np].fail=q; else{ int nq=New();S[nq]=S[q];S[q].fail=S[np].fail=nq;S[nq].len=S[p].len+1;Pos[nq]=Pos[q]; while (p&&S[p].son[c]==q) S[p].son[c]=nq,p=S[p].fail; } } return; } }; int n,Mtc[maxL]; char Input[maxL]; SAM S,T; vector<int> TS[maxL]; void dfs_build(int x); namespace DS{ class SegmentData{ public: int ls,rs; }; int nodecnt,root[maxL]; SegmentData S[maxL*20]; void Insert(int &x,int l,int r,int pos); int Query(int x,int l,int r,int ql,int qr); int Merge(int x,int y); void outp(int x,int l,int r); } int main(){ //freopen(NAME".in","r",stdin);freopen(NAME".out","w",stdout); scanf("%s",Input+1);n=strlen(Input+1); for (int i=1;i<=n;i++){ S.Extend(Input[i]-'a',i); DS::Insert(DS::root[S.lst],1,n,i); } /* for (int i=1;i<=S.nodecnt;i++) for (int j=0;j<maxAlpha;j++) if (S.S[i].son[j]) cout<<i<<"->"<<S.S[i].son[j]<<" "<<(char)(j+'a')<<endl; for (int i=1;i<=S.nodecnt;i++) cout<<S.S[i].len<<" ";cout<<endl; for (int i=1;i<=S.nodecnt;i++) cout<<S.S[i].fail<<" ";cout<<endl; //*/ for (int i=2;i<=S.nodecnt;i++) TS[S.S[i].fail].push_back(i); dfs_build(1); int Q;scanf("%d",&Q); while (Q--){ int L,R,m;scanf("%s",Input+1);scanf("%d%d",&L,&R); m=strlen(Input+1);T.Init(); for (int i=1;i<=m;i++) T.Extend(Input[i]-'a',i); for (int i=1,x=1,cnt=0;i<=m;i++){ int c=Input[i]-'a'; //cout<<"running on :"<<i<<endl; while (x&&((!S.S[x].son[c])||( !DS::Query(DS::root[S.S[x].son[c]],1,n,L+S.S[S.S[S.S[x].son[c]].fail].len,R)))){ //cout<<"GetQ:"<<S.S[x].son[c]<<" ["<<L<<"+"<<S.S[S.S[S.S[x].son[c]].fail].len<<","<<R<<"]"<<endl; x=S.S[x].fail,cnt=S.S[x].len; } //cout<<"now:"<<x<<" "<<cnt<<endl; if (x==0){ x=1;cnt=0;Mtc[i]=0;continue; } x=S.S[x].son[c];++cnt; //cout<<"Q:"<<i<<" "<<x<<" "<<S.S[S.S[x].fail].len+1<<" "<<cnt<<endl; if (S.S[S.S[x].fail].len+1!=cnt){ int l=S.S[S.S[x].fail].len+1,r=cnt; do{ int mid=(l+r)>>1; if (DS::Query(DS::root[x],1,n,L+mid-1,R)) cnt=mid,l=mid+1; else r=mid-1; } while (l<=r); } Mtc[i]=cnt; } ll Ans=0; //for (int i=1;i<=m;i++) cout<<Mtc[i]<<" ";cout<<endl; for (int i=1;i<=T.nodecnt;i++) Ans=Ans+max(0,T.S[i].len-max(T.S[T.S[i].fail].len,Mtc[T.Pos[i]])); printf("%lld\n",Ans); } return 0; } void dfs_build(int x){ for (int i=0,sz=TS[x].size();i<sz;i++){ dfs_build(TS[x][i]); DS::root[x]=DS::Merge(DS::root[x],DS::root[TS[x][i]]); } return; } namespace DS{ void Insert(int &x,int l,int r,int pos){ if (x==0) x=++nodecnt; if (l==r) return; int mid=(l+r)>>1; if (pos<=mid) Insert(S[x].ls,l,mid,pos); else Insert(S[x].rs,mid+1,r,pos); return; } int Query(int x,int l,int r,int ql,int qr){ //cout<<"Q:"<<x<<" "<<l<<" "<<r<<" "<<ql<<" "<<qr<<endl; if (ql>qr) return 0; if (x==0) return 0;if ((l==ql)&&(r==qr)) return 1; int mid=(l+r)>>1; if (qr<=mid) return Query(S[x].ls,l,mid,ql,qr); else if (ql>=mid+1) return Query(S[x].rs,mid+1,r,ql,qr); else return Query(S[x].ls,l,mid,ql,mid)|Query(S[x].rs,mid+1,r,mid+1,qr); } int Merge(int x,int y){ if ((!x)||(!y)) return x+y; int u=++nodecnt; S[u].ls=Merge(S[x].ls,S[y].ls);S[u].rs=Merge(S[x].rs,S[y].rs); return u; } void outp(int x,int l,int r){ if (x==0) return; if (l==r){ return; } int mid=(l+r)>>1; outp(S[x].ls,l,mid);outp(S[x].rs,mid+1,r);return; } }
25.4
102
0.545455
SYCstudio
97189995a32bdf90aa00afcba997e87849321c16
6,186
cpp
C++
Tools/DcmCmoveSCU/dicomquery.cpp
zyq1569/HealthApp
9e96e8759aad577693f597b5763febd2094767ee
[ "BSD-3-Clause" ]
3
2020-06-30T02:44:30.000Z
2022-01-13T12:27:09.000Z
Tools/DcmCmoveSCU/dicomquery.cpp
zyq1569/HealthApp
9e96e8759aad577693f597b5763febd2094767ee
[ "BSD-3-Clause" ]
3
2021-12-14T20:45:20.000Z
2021-12-18T18:22:04.000Z
Tools/DcmCmoveSCU/dicomquery.cpp
zyq1569/HealthApp
9e96e8759aad577693f597b5763febd2094767ee
[ "BSD-3-Clause" ]
6
2019-09-19T11:40:48.000Z
2020-12-07T08:01:52.000Z
#include "dicomquery.h" #include <boost/thread.hpp> // work around the fact that dcmtk doesn't work in unicode mode, so all string operation needs to be converted from/to mbcs #ifdef _UNICODE #undef _UNICODE #undef UNICODE #define _UNDEFINEDUNICODE #endif #include "dcmtk/ofstd/ofstd.h" #include "dcmtk/oflog/oflog.h" #include "dcmtk/dcmdata/dctk.h" #include "dcmtk/dcmnet/scu.h" // check DCMTK functionality #if !defined(WIDE_CHAR_FILE_IO_FUNCTIONS) && defined(_WIN32) //#error "DCMTK and this program must be compiled with DCMTK_WIDE_CHAR_FILE_IO_FUNCTIONS" #endif #ifdef _UNDEFINEDUNICODE #define _UNICODE 1 #define UNICODE 1 #endif DICOMQueryScanner::DICOMQueryScanner(PatientData &patientdata) : patientdata(patientdata) { cancelEvent = doneEvent = false; } DICOMQueryScanner::~DICOMQueryScanner() { } bool DICOMQueryScanner::ScanPatientName(std::string name, DestinationEntry &destination) { class MyDcmSCU : public DcmSCU { public: MyDcmSCU(PatientData &patientdata, DICOMQueryScanner &scanner) : patientdata(patientdata), scanner(scanner) {} PatientData &patientdata; DICOMQueryScanner &scanner; OFCondition handleFINDResponse(const T_ASC_PresentationContextID presID, QRResponse *response, OFBool &waitForNextResponse) { OFCondition ret = DcmSCU::handleFINDResponse(presID, response, waitForNextResponse); if (ret.good() && response->m_dataset != NULL) { OFString patientname, patientid, birthday; OFString studyuid, modality, studydesc, studydate; response->m_dataset->findAndGetOFString(DCM_StudyInstanceUID, studyuid); response->m_dataset->findAndGetOFString(DCM_PatientID, patientid); response->m_dataset->findAndGetOFString(DCM_PatientName, patientname); response->m_dataset->findAndGetOFString(DCM_StudyDescription, studydesc); response->m_dataset->findAndGetOFString(DCM_StudyDate, studydate); patientdata.AddStudy(studyuid.c_str(), patientid.c_str(), patientname.c_str(), studydesc.c_str(), studydate.c_str()); } if (scanner.IsCanceled()) waitForNextResponse = false; return ret; } }; if (IsCanceled()) return true; MyDcmSCU scu(patientdata, *this); scu.setVerbosePCMode(true); scu.setAETitle(destination.ourAETitle.c_str()); scu.setPeerHostName(destination.destinationHost.c_str()); scu.setPeerPort(destination.destinationPort); scu.setPeerAETitle(destination.destinationAETitle.c_str()); scu.setACSETimeout(30); scu.setDIMSETimeout(60); scu.setDatasetConversionMode(true); OFList<OFString> defaulttransfersyntax; defaulttransfersyntax.push_back(UID_LittleEndianExplicitTransferSyntax); scu.addPresentationContext(UID_FINDStudyRootQueryRetrieveInformationModel, defaulttransfersyntax); OFCondition cond; if (scu.initNetwork().bad()) return false; if (scu.negotiateAssociation().bad()) return false; T_ASC_PresentationContextID pid = scu.findAnyPresentationContextID(UID_FINDStudyRootQueryRetrieveInformationModel, UID_LittleEndianExplicitTransferSyntax); DcmDataset query; query.putAndInsertString(DCM_QueryRetrieveLevel, "STUDY"); query.putAndInsertString(DCM_StudyInstanceUID, ""); query.putAndInsertString(DCM_PatientName, name.c_str()); query.putAndInsertString(DCM_PatientID, ""); query.putAndInsertString(DCM_StudyDate, ""); query.putAndInsertString(DCM_StudyDescription, ""); query.putAndInsertSint16(DCM_NumberOfStudyRelatedInstances, 0); scu.sendFINDRequest(pid, &query, NULL); scu.releaseAssociation(); return true; } void DICOMQueryScanner::DoQueryAsync(DestinationEntry &destination) { SetDone(false); ClearCancel(); m_destination = destination; boost::thread t(DICOMQueryScanner::DoQueryThread, this); t.detach(); } void DICOMQueryScanner::DoQueryThread(void *obj) { DICOMQueryScanner *me = (DICOMQueryScanner *) obj; if(me) { me->DoQuery(me->m_destination); me->SetDone(true); } } void DICOMQueryScanner::DoQuery(DestinationEntry &destination) { OFLog::configure(OFLogger::OFF_LOG_LEVEL); // catch any access errors try { ScanPatientName("a", destination); ScanPatientName("e", destination); ScanPatientName("i", destination); ScanPatientName("o", destination); ScanPatientName("u", destination); } catch(...) { } } bool DICOMQueryScanner::Echo(DestinationEntry destination) { DcmSCU scu; scu.setVerbosePCMode(true); scu.setAETitle(destination.ourAETitle.c_str()); scu.setPeerHostName(destination.destinationHost.c_str()); scu.setPeerPort(destination.destinationPort); scu.setPeerAETitle(destination.destinationAETitle.c_str()); scu.setACSETimeout(30); scu.setDIMSETimeout(60); scu.setDatasetConversionMode(true); OFList<OFString> transfersyntax; transfersyntax.push_back(UID_LittleEndianExplicitTransferSyntax); transfersyntax.push_back(UID_LittleEndianImplicitTransferSyntax); scu.addPresentationContext(UID_VerificationSOPClass, transfersyntax); OFCondition cond; cond = scu.initNetwork(); if (cond.bad()) return false; cond = scu.negotiateAssociation(); if (cond.bad()) return false; cond = scu.sendECHORequest(0); scu.releaseAssociation(); if (cond == EC_Normal) { return true; } return false; } void DICOMQueryScanner::Cancel() { boost::mutex::scoped_lock lk(mutex); cancelEvent = true; } void DICOMQueryScanner::ClearCancel() { boost::mutex::scoped_lock lk(mutex); cancelEvent = false; } bool DICOMQueryScanner::IsDone() { boost::mutex::scoped_lock lk(mutex); return doneEvent; } bool DICOMQueryScanner::IsCanceled() { boost::mutex::scoped_lock lk(mutex); return cancelEvent; } void DICOMQueryScanner::SetDone(bool state) { boost::mutex::scoped_lock lk(mutex); doneEvent = state; }
27.371681
159
0.707727
zyq1569
971ba38196a99e61d55b148d731d5f280f161836
5,735
cpp
C++
src/TEXBModify.cpp
MikuAuahDark/Itsudemo
3e939414bff6d21abd41670dd7278435721075ae
[ "Zlib" ]
30
2016-02-26T16:21:39.000Z
2021-07-21T06:42:33.000Z
src/TEXBModify.cpp
Ink-33/Itsudemo
3e939414bff6d21abd41670dd7278435721075ae
[ "Zlib" ]
3
2016-08-25T16:37:12.000Z
2016-11-27T06:26:32.000Z
src/TEXBModify.cpp
Ink-33/Itsudemo
3e939414bff6d21abd41670dd7278435721075ae
[ "Zlib" ]
14
2016-04-03T15:42:56.000Z
2019-09-16T02:08:33.000Z
/** * TEXBModify.cpp * Modification of TextureBank class **/ #include "TEXB.h" #include "xy2uv.h" #include <algorithm> #include <vector> #include <map> #include <string> #include <cerrno> #include <cstdlib> #include <cstring> TextureBank::TextureBank(uint32_t _Width,uint32_t _Height):Width(RawImageWidth),Height(RawImageHeight),Flags(_Flags) { uint32_t rawimage_size=_Width*_Height*4; RawImageWidth=_Width; RawImageHeight=_Height; RawImage=LIBTEXB_ALLOC(uint8_t,rawimage_size); // 4-byte/pixel _Flags=0; memset(RawImage,0,rawimage_size); } TextureBank::~TextureBank() { for(uint32_t i=0;i<this->ImageList_Id.size();i++) { TextureImage* a=this->ImageList_Id[i]; uint32_t* b=this->VertexIndexUVs[i]; if(a->from_texb==this) delete a; LIBTEXB_FREE(b); } } TextureBank* TextureBank::Clone() { TextureBank* texb=new TextureBank; uint32_t memsize=Width*Height*4; texb->RawImageWidth=Width; texb->RawImageHeight=Height; texb->RawImage=LIBTEXB_ALLOC(uint8_t,memsize); texb->Name=Name; memcpy(texb->RawImage,RawImage,memsize); memsize=ImageList_Id.size(); for(uint32_t i=0;i<memsize;i++) { TextureImage* timg=ImageList_Id[i]->Clone(); uint32_t* VrtxMem=reinterpret_cast<uint32_t*>(LIBTEXB_ALLOC(uint8_t,70)); timg->from_texb=texb; texb->ImageList_Id.push_back(timg); texb->ImageList_Names[timg->Name]=i; texb->VertexIndexUVs.push_back(VrtxMem); memcpy(VrtxMem,VertexIndexUVs[i],70); } return texb; } int32_t TextureBank::ReplaceImage(TextureImage* Image) { std::map<std::string,uint32_t>::iterator i=ImageList_Names.find(Image->Name); if(i!=ImageList_Names.end()) return ReplaceImage(Image,i->second); return EINVAL; } int32_t TextureBank::ReplaceImage(TextureImage* Image,uint32_t Index) { if(Index>=ImageList_Id.size()) return ERANGE; TextureImage* target=ImageList_Id[Index]; if(target->Width!=Image->Width || target->Height!=Image->Height || target->Name!=Image->Name) return EINVAL; if(target->from_texb==this) delete target; ImageList_Id[Index]=Image; // Copy raw TIMG image to raw TEXB image uint32_t* Vrtx=VertexIndexUVs[Index]; uint32_t* texbBmp=reinterpret_cast<uint32_t*>(RawImage); uint32_t* rawBmp=reinterpret_cast<uint32_t*>(Image->RawImage); Point v[4]={ {Vrtx[0]/65536,Vrtx[1]/65536}, {Vrtx[4]/65536,Vrtx[5]/65536}, {Vrtx[8]/65536,Vrtx[9]/65536}, {Vrtx[12]/65536,Vrtx[13]/65536} }; UVPoint t[4]={ {Vrtx[2]/65536.0,Vrtx[3]/65536.0}, {Vrtx[6]/65536.0,Vrtx[7]/65536.0}, {Vrtx[10]/65536.0,Vrtx[11]/65536.0}, {Vrtx[14]/65536.0,Vrtx[15]/65536.0} }; for(uint32_t y=0;y<Image->Height;y++) { for(uint32_t x=0;x<Image->Width;x++) { UVPoint uv=xy2uv(x,y,v[0],v[1],v[2],v[3],t[0],t[1],t[2],t[3]); texbBmp[uint32_t(uv.U*Width+0.5)+uint32_t(uv.V*Height+0.5)*Width]=rawBmp[x+y*Image->Width]; } } return 0; } int32_t TextureBank::DefineImage(const Point* Vertexes,const UVPoint* UVs,std::string Name,uint32_t* Index) { if(Index==NULL) return EINVAL; TextureImage* timg=new TextureImage(); timg->Width=Vertexes[2].X; timg->Height=Vertexes[2].Y; timg->from_texb=this; timg->Name=Name; uint32_t* Vertex=reinterpret_cast<uint32_t*>(LIBTEXB_ALLOC(uint8_t,70)); uint8_t* RawMem=LIBTEXB_ALLOC(uint8_t,timg->Width*timg->Height*4); timg->RawImage=RawMem; memcpy(&Vertex[16],"\x00\x01\x03\x03\x01\x02",6); memset(RawMem,0,timg->Width*timg->Height*4); for(uint32_t i=0;i<4;i++) { Vertex[i*4]=Vertexes[i].X*65536; Vertex[i*4+1]=Vertexes[i].Y*65536; Vertex[i*4+2]=uint32_t(UVs[i].U*65536); Vertex[i*4+3]=uint32_t(UVs[i].V*65536); } *Index=ImageList_Id.size(); VertexIndexUVs.push_back(Vertex); ImageList_Id.push_back(timg); ImageList_Names[Name]=*Index; return 0; } int32_t TextureBank::DefineImage(const Point* WhereWidthHeight,std::string Name,uint32_t* Index) { Point v[4]={ {0,0}, {WhereWidthHeight[1].X,0}, {WhereWidthHeight[1].X,WhereWidthHeight[1].Y}, {0,WhereWidthHeight[1].Y} }; // Applied MiraiNoHana TEXBModify.cpp patch. UVPoint t[4]={ {double(WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[0].Y)/double(Height)}, {double(WhereWidthHeight[1].X+WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[0].Y)/double(Height)}, {double(WhereWidthHeight[1].X+WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[1].Y+WhereWidthHeight[0].Y)/double(Height)}, {double(WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[1].Y+WhereWidthHeight[0].Y)/double(Height)} }; return DefineImage(v,t,Name,Index); } void TextureBank::ReflectChanges() { for(uint32_t i=0;i<ImageList_Id.size();i++) { TextureImage* timg=ImageList_Id[i]; uint32_t* Vrtx=VertexIndexUVs[i]; uint32_t* texbBmp=reinterpret_cast<uint32_t*>(RawImage); uint32_t* rawBmp=reinterpret_cast<uint32_t*>(timg->RawImage); Point v[4]={ {Vrtx[0]/65536,Vrtx[1]/65536}, {Vrtx[4]/65536,Vrtx[5]/65536}, {Vrtx[8]/65536,Vrtx[9]/65536}, {Vrtx[12]/65536,Vrtx[13]/65536} }; UVPoint t[4]={ {Vrtx[2]/65536.0,Vrtx[3]/65536.0}, {Vrtx[6]/65536.0,Vrtx[7]/65536.0}, {Vrtx[10]/65536.0,Vrtx[11]/65536.0}, {Vrtx[14]/65536.0,Vrtx[15]/65536.0} }; uint32_t min_x = std::min(v[0].X, std::min(v[1].X, std::min(v[2].X, v[3].X))); uint32_t min_y = std::min(v[0].Y, std::min(v[1].Y, std::min(v[2].Y, v[3].Y))); uint32_t max_x = std::max(v[0].X, std::max(v[1].X, std::max(v[2].X, v[3].X))); uint32_t max_y = std::max(v[0].Y, std::max(v[1].Y, std::max(v[2].Y, v[3].Y))); for(uint32_t y = min_y; y < max_y; y++) { for(uint32_t x = min_x; x < max_x; x++) { UVPoint uv=xy2uv(x, y, v[0], v[1], v[2], v[3], t[0], t[1], t[2], t[3]); texbBmp[uint32_t(uv.U * Width + 0.5) + uint32_t(uv.V * Height + 0.5) * Width] = rawBmp[x + y * timg->Width]; } } } }
28.532338
137
0.689799
MikuAuahDark
971cd7c3d55ec832dc00c68b332983eccc0351c9
748
cpp
C++
src/Island.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
null
null
null
src/Island.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
1
2019-08-14T13:36:33.000Z
2019-08-14T13:36:33.000Z
src/Island.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
null
null
null
// Copyright 2018, // Author: Luka Steinbach <luka.steinbach@gmx.de> #include "./Island.h" #include <string> #include <vector> // _____________________________________________________________________________ Island::Island(int x, int y, int count) : Field(x, y) { _islandCount = count; _correctBridgeCount = 0; _symbol = std::to_string(_islandCount); } // _____________________________________________________________________________ Island::~Island() {} // _____________________________________________________________________________ int Island::getCount() const { return _islandCount; } // _____________________________________________________________________________ std::string Island::getType() const { return "type_island"; }
27.703704
80
0.798128
luka1199
971d0e7be632f513340bede6a7f76ecd77082369
77,961
cpp
C++
simulation-code/Network.cpp
jlubo/memory-consolidation-stc
f9934760e12de324360297d7fc7902623169cb4d
[ "Apache-2.0" ]
2
2021-03-02T21:46:56.000Z
2021-06-30T03:12:07.000Z
simulation-code/Network.cpp
jlubo/memory-consolidation-stc
f9934760e12de324360297d7fc7902623169cb4d
[ "Apache-2.0" ]
null
null
null
simulation-code/Network.cpp
jlubo/memory-consolidation-stc
f9934760e12de324360297d7fc7902623169cb4d
[ "Apache-2.0" ]
3
2021-03-22T12:56:52.000Z
2021-09-13T07:42:36.000Z
/************************************************************************************************** *** Model of a network of neurons with long-term plasticity between excitatory neurons *** **************************************************************************************************/ /*** Copyright 2017-2021 Jannik Luboeinski *** *** licensed under Apache-2.0 (http://www.apache.org/licenses/LICENSE-2.0) ***/ #include <random> #include <sstream> using namespace std; #include "Neuron.cpp" struct synapse // structure for synapse definition { int presyn_neuron; // the number of the presynaptic neuron int postsyn_neuron; // the number of the postsynaptic neuron synapse(int _presyn_neuron, int _postsyn_neuron) // constructor { presyn_neuron = _presyn_neuron; postsyn_neuron = _postsyn_neuron; } }; /*** Network class *** * Represents a network of neurons */ class Network { #if (PROTEIN_POOLS != POOLS_C && PROTEIN_POOLS != POOLS_PD && PROTEIN_POOLS != POOLS_PCD) #error "Unsupported option for PROTEIN_POOLS." #endif friend class boost::serialization::access; private: /*** Computational parameters ***/ double dt; // s, one timestep for numerical simulation int N; // total number of excitatory plus inhibitory neurons int t_syn_delay_steps; // constant t_syn_delay converted to timesteps int t_Ca_delay_steps; // constant t_Ca_delay converted to timesteps /*** State variables ***/ vector<Neuron> neurons; // vector of all N neuron instances (first excitatory, then inhibitory) bool** conn; // the binary connectivity matrix, the main diagonal is zero (because there is no self-coupling) double** Ca; // the matrix of postsynaptic calcium concentrations double** h; // the matrix of early-phase coupling strengths double** z; // the matrix of late-phase coupling strengths int* last_Ca_spike_index; // contains the indices of the last spikes that were important for calcium dynamics minstd_rand0 rg; // default uniform generator for random numbers to establish connections (seed is chosen in constructor) uniform_real_distribution<double> u_dist; // uniform distribution, constructed in Network class constructor normal_distribution<double> norm_dist; // normal distribution to obtain Gaussian white noise, constructed in Network class constructor int stimulation_end; // timestep by which all stimuli have ended double* sum_h_diff; // sum of all early-phase changes for each postsynaptic neuron double* sum_h_diff_p; // sum of E-LTP changes for each postsynaptic neuron double* sum_h_diff_d; // sum of E-LTD changes for each postsynaptic neuron protected: /*** Physical parameters ***/ int Nl_exc; // number of neurons in one line (row or column) of the exc. population (better choose an odd number, for there exists a "central" neuron) int Nl_inh; // number of neurons in one line (row or column) of the inh. population (better choose an odd number, for there exists a "central" neuron) double tau_syn; // s, the synaptic time constant double t_syn_delay; // s, the synaptic transmission delay for PSPs - has to be at least one timestep! double p_c; // connection probability (prob. that a directed connection exists) double w_ee; // nC, magnitude of excitatory PSP effecting an excitatory postsynaptic neuron double w_ei; // nC, magnitude of excitatory PSP effecting an inhibitory postsynaptic neuron double w_ie; // nC, magnitude of inhibitory PSP effecting an excitatory postsynaptic neuron double w_ii; // nC, magnitude of inhibitory PSP effecting an inhibitory postsynaptic neuron /*** Plasticity parameters ***/ double t_Ca_delay; // s, delay for spikes to affect calcium dynamics - has to be at least one timestep! double Ca_pre; // s^-1, increase in calcium current evoked by presynaptic spike double Ca_post; // s^-1, increase in calcium current evoked by postsynaptic spike double tau_Ca; // s, time constant for calcium dynamics double tau_Ca_steps; // time constant for calcium dynamics in timesteps double tau_h; // s, time constant for early-phase plasticity double tau_pp; // h, time constant of LTP-related protein synthesis double tau_pc; // h, time constant of common protein synthesis double tau_pd; // h, time constant of LTD-related protein synthesis double tau_z; // min, time constant of consolidation double gamma_p; // constant for potentiation process double gamma_d; // constant for depression process double theta_p; // threshold for calcium concentration to induce potentiation double theta_d; // threshold for calcium concentration to induce depotentiation double sigma_plasticity; // nA s, standard deviation of plasticity noise double alpha_p; // LTP-related protein synthesis rate double alpha_c; // common protein synthesis rate double alpha_d; // LTD-related protein synthesis rate double h_0; // nA, initial value for early-phase plasticity double theta_pro_p; // nA s, threshold for LTP-related protein synthesis double theta_pro_c; // nA s, threshold for common protein synthesis double theta_pro_d; // nA s, threshold for LTD-related protein synthesis double theta_tag_p; // nA s, threshold for LTP-related tag double theta_tag_d; // nA s, threshold for LTD-related tag double z_max; // upper z bound public: #ifdef TWO_NEURONS_ONE_SYNAPSE bool tag_glob; // specifies if a synapse was tagged ever bool ps_glob; // specifies if protein synthesis ever occurred in any neuron #endif double max_dev; // maximum deviation from h_0 (deviation of the synapse with the largest change) int tb_max_dev; // time bin at which max_dev was encountered #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD double max_sum_diff; // maximum sum of early-phase changes (sum of the neuron with the most changes) int tb_max_sum_diff; // time bin at which max_sum_diff was encountered #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD double max_sum_diff_p; // maximum sum of LTP early-phase changes (sum of the neuron with the most changes) int tb_max_sum_diff_p; // time bin at which max_sum_diff_p was encountered double max_sum_diff_d; // maximum sum of LTD early-phase changes (sum of the neuron with the most changes) int tb_max_sum_diff_d; // time bin at which max_sum_diff_d was encountered #endif /*** rowG (macro) *** * Returns the row number for element n (in consecutive numbering), be * * aware that it starts with one, unlike the consecutive number (general case for a row/column size of d) * * - int n: the consecutive element number * * - int d: the row/column size */ #define rowG(n, d) ((((n) - ((n) % d)) / d) + 1) /*** colG (macro) *** * Returns the column number for element n (in consecutive numbering), be * * aware that it starts with one, unlike the consecutive number (general case for a row/column size of d) * * - int n: the consecutive element number * * - int d: the row/column size */ #define colG(n, d) (((n) % d) + 1) /*** cNN (macro) *** * Returns a consecutive number for excitatory neuron (i|j) rather than a pair of numbers like (i|j), be * * aware that it starts with zero, unlike i and j * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located */ #define cNN(i, j) (((i)-1)*Nl_exc + ((j)-1)) /*** row (macro) *** * Returns the row number for excitatory neuron n, be * * aware that it starts with one, unlike the consecutive number * * - int n: the consecutive neuron number */ #define row(n) (rowG(n, Nl_exc)) /*** col (macro) *** * Returns the column number for excitatory neuron n, be * * aware that it starts with one, unlike the consecutive number * * - int n: the consecutive neuron number */ #define col(n) (colG(n, Nl_exc)) /*** symm (macro) *** * Returns the number of the symmetric element for an element given * * by its consecutive number * * - int n: the consecutive element number */ #define symm(n) (cNN(col(n),row(n))) /*** shallBeConnected *** * Draws a uniformly distributed random number from the interval 0.0 to 1.0 and returns, * * depending on the connection probability, whether or not a connection shall be established * * - int m: consecutive number of presynaptic neuron * * - int n: consecutive number of postsynaptic neuron * * - return: true if connection shall be established, false if not */ bool shallBeConnected(int m, int n) { #ifdef TWO_NEURONS_ONE_SYNAPSE // in this paradigm, there is only one synapse from neuron 1 to neuron 0 if (m == 1 && n == 0) { neurons[m].addOutgoingConnection(n, TYPE_EXC); return true; } #else // exc.->exc. synapse if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_EXC); neurons[m].addOutgoingConnection(n, TYPE_EXC); return true; } } // exc.->inh. synapse else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_EXC); neurons[m].addOutgoingConnection(n, TYPE_INH); return true; } } // inh.->exc. synapse else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_INH); neurons[m].addOutgoingConnection(n, TYPE_EXC); return true; } } // inh.->inh. synapse else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_INH); neurons[m].addOutgoingConnection(n, TYPE_INH); return true; } } #endif return false; } /*** areConnected *** * Returns whether or not there is a synapse from neuron m to neuron n * * - int m: the number of the first neuron in consecutive order * * - int n: the number of the second neuron in consecutive order * * - return: true if connection from m to n exists, false if not */ bool areConnected(int m, int n) const { if (conn[m][n]) return true; else return false; } /*** saveNetworkParams *** * Saves all the network parameters (including the neuron and channel parameters) to a given file */ void saveNetworkParams(ofstream *f) const { *f << endl; *f << "Network parameters:" << endl; *f << "N_exc = " << pow2(Nl_exc) << " (" << Nl_exc << " x " << Nl_exc << ")" << endl; *f << "N_inh = " << pow2(Nl_inh) << " (" << Nl_inh << " x " << Nl_inh << ")" << endl; *f << "tau_syn = " #if SYNAPSE_MODEL == DELTA << 0 #elif SYNAPSE_MODEL == MONOEXP << tau_syn #endif << " s" << endl; *f << "t_syn_delay = " << t_syn_delay << " s" << endl; *f << "h_0 = " << h_0 << " nA s" << endl; *f << "w_ee = " << dtos(w_ee/h_0,1) << " h_0" << endl; *f << "w_ei = " << dtos(w_ei/h_0,1) << " h_0" << endl; *f << "w_ie = " << dtos(w_ie/h_0,1) << " h_0" << endl; *f << "w_ii = " << dtos(w_ii/h_0,1) << " h_0" << endl; *f << "p_c = " << p_c << endl; *f << endl; *f << "Plasticity parameters" #if PLASTICITY == OFF << " <switched off>" #endif << ": " << endl; *f << "t_Ca_delay = " << t_Ca_delay << " s" << endl; *f << "Ca_pre = " << Ca_pre << endl; *f << "Ca_post = " << Ca_post << endl; *f << "tau_Ca = " << tau_Ca << " s" << endl; *f << "tau_h = " << tau_h << " s" << endl; *f << "tau_pp = " << tau_pp << " h" << endl; *f << "tau_pc = " << tau_pc << " h" << endl; *f << "tau_pd = " << tau_pd << " h" << endl; *f << "tau_z = " << tau_z << " min" << endl; *f << "z_max = " << z_max << endl; *f << "gamma_p = " << gamma_p << endl; *f << "gamma_d = " << gamma_d << endl; *f << "theta_p = " << theta_p << endl; *f << "theta_d = " << theta_d << endl; *f << "sigma_plasticity = " << dtos(sigma_plasticity/h_0,2) << " h_0" << endl; *f << "alpha_p = " << alpha_p << endl; *f << "alpha_c = " << alpha_c << endl; *f << "alpha_d = " << alpha_d << endl; double nm = 1. / (theta_pro_c/h_0) - 0.001; // compute neuromodulator concentration from threshold theta_pro_c *f << "theta_pro_p = " << dtos(theta_pro_p/h_0,2) << " h_0" << endl; *f << "theta_pro_c = " << dtos(theta_pro_c/h_0,2) << " h_0 (nm = " << dtos(nm,2) << ")" << endl; *f << "theta_pro_d = " << dtos(theta_pro_d/h_0,2) << " h_0" << endl; *f << "theta_tag_p = " << dtos(theta_tag_p/h_0,2) << " h_0" << endl; *f << "theta_tag_d = " << dtos(theta_tag_d/h_0,2) << " h_0" << endl; neurons[0].saveNeuronParams(f); // all neurons have the same parameters, take the first one } /*** saveNetworkState *** * Saves the current state of the whole network to a given file using boost function serialize(...) * * - file: the file to read the data from * * - tb: current timestep */ void saveNetworkState(string file, int tb) { ofstream savefile(file); if (!savefile.is_open()) throw runtime_error(string("Network state could not be saved.")); boost::archive::text_oarchive oa(savefile); oa << tb; // write the current time (in steps) to archive oa oa << *this; // write this instance to archive oa savefile.close(); } /*** loadNetworkState *** * Load the state of the whole network from a given file using boost function serialize(...); * * connectivity matrix 'conn' of the old and the new simulation has to be the same! * * - file: the file to read the data from * * - return: the simulation time at which the network state was saved (or -1 if nothing was loaded) */ int loadNetworkState(string file) { ifstream loadfile(file); int tb; if (!loadfile.is_open()) return -1; boost::archive::text_iarchive ia(loadfile); ia >> tb; // read the current time (in steps) from archive ia ia >> *this; // read this instance from archive ia loadfile.close(); cout << "Network state successfully loaded." << endl; return tb; } /*** serialize *** * Saves all state variables to a file using serialization from boost * * - ar: the archive stream * * - version: the archive version */ template<class Archive> void serialize(Archive &ar, const unsigned int version) { for (int m=0; m<N; m++) { ar & neurons[m]; // read/write Neuron instances for (int n=0; n<N; n++) { ar & Ca[m][n]; // read/write matrix of postsynaptic Calcium concentrations ar & h[m][n]; // read/write early-phase weight matrix ar & z[m][n]; // read/write late-phase weight matrix } ar & last_Ca_spike_index[m]; // read/write array of the indices of the last spikes that were important for calcium dynamics ar & sum_h_diff[m]; // read/write sum of all early-phase changes for each postsynaptic neuron ar & sum_h_diff_p[m]; // read/write sum of E-LTP changes for each postsynaptic neuron ar & sum_h_diff_d[m]; // read/write sum of E-LTD changes for each postsynaptic neuron } } /*** processTimeStep *** * Processes one timestep (of duration dt) for the network [rich mode / compmode == 1] * * - int tb: current timestep (for evaluating stimulus and for computing spike contributions) * * - ofstream* txt_spike_raster [optional]: file containing spike times for spike raster plot * * - return: number of spikes that occurred within the considered timestep in the whole network */ int processTimeStep(int tb, ofstream* txt_spike_raster = NULL) { int spike_count = 0; // number of neurons that have spiked in this timestep int st_PSP = tb - t_syn_delay_steps; // presynaptic spike time for evoking PSP in this timestep tb int st_CA = tb - t_Ca_delay_steps; // presynaptic spike time for evoking calcium contribution in this timestep tb bool STC = false; // specifies if at least one synapse is tagged and receives proteins bool ps_neuron = false; // specifies if at least one neuron is exhibiting protein synthesis /*******************************************************/ // compute neuronal dynamics for (int m=0; m<N; m++) // loop over neurons (in consecutive order) { neurons[m].processTimeStep(tb, -1); // computation of individual neuron dynamics // add spikes to raster plot and count spikes in this timestep if (neurons[m].getActivity()) { #if SPIKE_PLOTTING == RASTER || SPIKE_PLOTTING == NUMBER_AND_RASTER *txt_spike_raster << tb*dt << "\t\t" << m << endl; // add this spike to the raster plot #endif spike_count += 1; } #if COND_BASED_SYN == OFF #if SYNAPSE_MODEL == DELTA neurons[m].setSynapticCurrent(0.); // reset synaptic current contributions #elif SYNAPSE_MODEL == MONOEXP neurons[m].setSynapticCurrent(neurons[m].getSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions #endif #else #if SYNAPSE_MODEL == DELTA neurons[m].setExcSynapticCurrent(0.); // reset synaptic current contributions neurons[m].setInhSynapticCurrent(0.); // reset synaptic current contributions #elif SYNAPSE_MODEL == MONOEXP neurons[m].setExcSynapticCurrent(neurons[m].getExcSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions neurons[m].setInhSynapticCurrent(neurons[m].getInhSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions //[simple Euler: neurons[m].setExcSynapticCurrent(neurons[m].getExcSynapticCurrent() * (1.-dt/tau_syn)); ] //[simple Euler: neurons[m].setInhSynapticCurrent(neurons[m].getInhSynapticCurrent() * (1.-dt/tau_syn)); ] #endif #endif // COND_BASED_SYN == ON // Protein dynamics (for neuron m) #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC #ifdef TWO_NEURONS_ONE_SYNAPSE ps_glob = ps_glob || (sum_h_diff[m] >= theta_pro_c); #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD double pa_p = neurons[m].getPProteinAmount(); double pa_d = neurons[m].getDProteinAmount(); if (sum_h_diff_p[m] > max_sum_diff_p) { max_sum_diff_p = sum_h_diff_p[m]; tb_max_sum_diff_p = tb; } if (sum_h_diff_d[m] > max_sum_diff_d) { max_sum_diff_d = sum_h_diff_d[m]; tb_max_sum_diff_d = tb; } ps_neuron = ps_neuron || (sum_h_diff_p[m] >= theta_pro_p) || (sum_h_diff_d[m] >= theta_pro_d); pa_p = pa_p * exp(-dt/(tau_pp * 3600.)) + alpha_p * step(sum_h_diff_p[m] - theta_pro_p) * (1. - exp(-dt/(tau_pp * 3600.))); pa_d = pa_d * exp(-dt/(tau_pd * 3600.)) + alpha_d * step(sum_h_diff_d[m] - theta_pro_d) * (1. - exp(-dt/(tau_pd * 3600.))); // [simple Euler: pa += (- pa + alpha * step(sum_h_diff - theta_pro)) * (dt / (tau_p * 3600.));] sum_h_diff_p[m] = 0.; sum_h_diff_d[m] = 0.; #else double pa_p = 0.; double pa_d = 0.; #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD double pa_c = neurons[m].getCProteinAmount(); if (sum_h_diff[m] > max_sum_diff) { max_sum_diff = sum_h_diff[m]; tb_max_sum_diff = tb; } ps_neuron = ps_neuron || (sum_h_diff[m] >= theta_pro_c); pa_c = pa_c * exp(-dt/(tau_pc * 3600.)) + alpha_c * step(sum_h_diff[m] - theta_pro_c) * (1. - exp(-dt/(tau_pc * 3600.))); // === ESSENTIAL === sum_h_diff[m] = 0.; #else double pa_c = 0.; #endif neurons[m].setProteinAmounts(pa_p, pa_c, pa_d); #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC } /*******************************************************/ // compute synaptic dynamics for (int m=0; m<N; m++) // loop over presynaptic neurons (in consecutive order) { bool delayed_PSP; // specifies if a presynaptic spike occurred t_syn_delay ago // go through presynaptic spikes for PSPs; start from most recent one delayed_PSP = neurons[m].spikeAt(st_PSP); //delayed_PSP = neurons[m].getActivity(); // in case no synaptic delay is used #if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC bool delayed_Ca = false; // specifies if a presynaptic spike occurred t_Ca_delay ago if (m < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections { // go through presynaptic spikes for calcium contribution; start from last one that was used plus one for (int k=last_Ca_spike_index[m]; k<=neurons[m].getSpikeHistorySize(); k++) { int st = neurons[m].getSpikeTime(k); if (st >= st_CA) { if (st == st_CA) // if presynaptic spike occurred t_Ca_delay ago { delayed_Ca = true; // presynaptic neuron fired t_Ca_delay ago last_Ca_spike_index[m] = k + 1; // next time, start with the next possible spike } break; } } } #endif /*******************************************************/ for (int in=0; in<neurons[m].getNumberOutgoing(); in++) // loop over postsynaptic neurons { int n = neurons[m].getOutgoingConnection(in); // get index (in consecutive order) of postsynaptic neuron double h_dev; // the deviation of the early-phase weight from its resting state // Synaptic current if (delayed_PSP) // if presynaptic spike occurred t_syn_delay ago { if (neurons[m].getType() == TYPE_EXC) { double psc; // the postsynaptic current if (neurons[n].getType() == TYPE_EXC) // E -> E { psc = h[m][n] + h_0 * z[m][n]; neurons[n].increaseExcSynapticCurrent(psc); } else // E -> I { psc = w_ei; neurons[n].increaseExcSynapticCurrent(psc); } #if DENDR_SPIKES == ON neurons[n].updateDendriteInput(psc); // contribution to dendritic spikes #endif } else { if (neurons[n].getType() == TYPE_EXC) // I -> E { neurons[n].increaseInhSynapticCurrent(w_ie); } else // I -> I { neurons[n].increaseInhSynapticCurrent(w_ii); } } } // Long-term plasticity if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections { #if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC // Calcium dynamics Ca[m][n] *= exp(-dt/tau_Ca); // === ESSENTIAL === if (delayed_Ca) // if presynaptic spike occurred t_Ca_delay ago Ca[m][n] += Ca_pre; if (neurons[n].getActivity()) // if postsynaptic spike occurred in previous timestep Ca[m][n] += Ca_post; // E-LTP/-LTD if ((Ca[m][n] >= theta_p) // if there is E-LTP and "STDP-like" condition is fulfilled #if LTP_FR_THRESHOLD > 0 && (neurons[m].spikesInInterval(tb-2500,tb+1) > LTP_FR_THRESHOLD/2 && neurons[n].spikesInInterval(tb-2500,tb+1) > LTP_FR_THRESHOLD/2) #endif ) { double noise = sigma_plasticity * sqrt(tau_h) * sqrt(2) * norm_dist(rg) / sqrt(dt); // division by sqrt(dt) was not in Li et al., 2016 double C = 0.1 + gamma_p + gamma_d; double hexp = exp(-dt*C/tau_h); h[m][n] = h[m][n] * hexp + (0.1*h_0 + gamma_p + noise) / C * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]) + gamma_p * (1-h[m][n]) - gamma_d * h[m][n] + noise)*(dt/tau_h));] if (abs(h[m][n] - h_0) > abs(max_dev)) { max_dev = h[m][n] - h_0; tb_max_dev = tb; } } else if ((Ca[m][n] >= theta_d) // if there is E-LTD #if LTD_FR_THRESHOLD > 0 && (neurons[m].spikesInInterval(tb-2500,tb+1) > LTD_FR_THRESHOLD/2 && neurons[n].spikesInInterval(tb-2500,tb+1) > LTD_FR_THRESHOLD/2) #endif ) { double noise = sigma_plasticity * sqrt(tau_h) * norm_dist(rg) / sqrt(dt); // division by sqrt(dt) was not in Li et al., 2016 double C = 0.1 + gamma_d; double hexp = exp(-dt*C/tau_h); h[m][n] = h[m][n] * hexp + (0.1*h_0 + noise) / C * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]) + gamma_d * h[m][n] + noise)*(dt/tau_h));] if (abs(h[m][n] - h_0) > abs(max_dev)) { max_dev = h[m][n] - h_0; tb_max_dev = tb; } } else // if early-phase weight just decays { double hexp = exp(-dt*0.1/tau_h); h[m][n] = h[m][n] * hexp + h_0 * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]))*(dt/tau_h));] } h_dev = h[m][n] - h_0; #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD if (h_dev > 0.) sum_h_diff_p[n] += h_dev; // sum of early-phases changes (for LTP-related protein synthesis) else if (h_dev < 0.) sum_h_diff_d[n] -= h_dev; // sum of early-phases changes (for LTD-related protein synthesis) #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD sum_h_diff[n] += abs(h_dev); // sum of early-phases changes (for protein synthesis) #endif #endif // PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC // L-LTP/-LTD if (h_dev >= theta_tag_p) // LTP { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getPProteinAmount()*neurons[n].getCProteinAmount(); // LTP protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getPProteinAmount(); // LTP protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-dt / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-dt / (tau_z * 60. * z_max) * pa); z[m][n] = z[m][n] * zexp + z_max * (1. - zexp); STC = true; } } else if (-h_dev >= theta_tag_d) // LTD { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getDProteinAmount()*neurons[n].getCProteinAmount(); // LTD protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getDProteinAmount(); // LTD protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-dt / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-dt / (tau_z * 60.) * pa); z[m][n] = z[m][n] * zexp - 0.5 * (1. - zexp); STC = true; } } // [simple Euler: z[m][n] += (pa * ((1 - z[m][n]) * step1 - (0.5 + z[m][n]) * step2) * (dt / (tau_z * 6.0 * 10)));] #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC #if PLASTICITY == STDP double Ap = 1.2, Am = -1.0; double tau_syn_stdp = 3e-3; double tau_p_stdp = 1e-3; double tau_m_stdp = 20e-3; double tau_pt_stdp = tau_syn_stdp * tau_p_stdp / (tau_syn_stdp + tau_p_stdp); double tau_mt_stdp = tau_syn_stdp * tau_m_stdp / (tau_syn_stdp + tau_m_stdp); double eta = 12e-2; // if presynaptic neuron m spiked in previous timestep if (delayed_PSP) { int last_post_spike = neurons[n].getSpikeHistorySize(); if (last_post_spike > 0) { int tb_post = neurons[n].getSpikeTime(last_post_spike); double stdp_delta_t = (tb + 1 - tb_post) * dt; h[m][n] += eta * exp(-abs(stdp_delta_t) / tau_syn_stdp) * (Ap * (1. + abs(stdp_delta_t)/tau_pt_stdp) + Am * (1. + abs(stdp_delta_t)/tau_mt_stdp)); if (h[m][n] < 0.) h[m][n] = 0.1;//h_0 / 100.; // set to a very small value } } // if postsynaptic neuron n spiked in previous timestep bool delayed_PSP2 = false; for (int k=neurons[n].getSpikeHistorySize(); k>0; k--) { int st = neurons[n].getSpikeTime(k); if (st <= st_PSP) // spikes that have already arrived { if (st == st_PSP) // if presynaptic spike occurred t_syn_delay ago { delayed_PSP2 = true; // presynaptic neuron fired t_syn_delay ago } break; } } if (delayed_PSP2) { int last_pre_spike = neurons[m].getSpikeHistorySize(); if (last_pre_spike > 0) { int tb_pre = neurons[n].getSpikeTime(last_pre_spike); double stdp_delta_t = (tb_pre - tb - 1) * dt; h[m][n] += eta * (Ap * exp(-abs(stdp_delta_t) / tau_p_stdp) + Am * exp(-abs(stdp_delta_t) / tau_m_stdp)); if (h[m][n] < 0.) h[m][n] = 0.1;//h_0 / 100.; // set to a very small value } } #endif // PLASTICITY == STDP } // plasticity within excitatory population #if SYN_SCALING == ON h[m][n] += ( eta_ss * pow2(h[m][n] / g_star) * (- r[n]) ) * dt; #endif } // loop over postsynaptic neurons } // loop over presynaptic neurons return spike_count; } /*** processTimeStep_FF *** * Processes one timestep for the network only computing late-phase observables [fast-forward mode / compmode == 2] * * - int tb: current timestep (for printing purposes only) * * - double delta_t: duration of the fast-forward timestep * * - ofstream* logf: pointer to log file handle (for printing interesting information) * * - return: true if late-phase dynamics are persisting, false if not */ int processTimeStep_FF(int tb, double delta_t, ofstream* logf) { bool STC = false; // specifies if at least one synapse is tagged and receives proteins bool ps_neuron = false; // specifies if at least one neuron is exhibiting protein synthesis /*******************************************************/ // compute neuronal dynamics for (int m=0; m<N; m++) // loop over neurons (in consecutive order) { // Protein dynamics (for neuron m) - computation from analytic functions #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC #ifdef TWO_NEURONS_ONE_SYNAPSE ps_glob = ps_glob || (sum_h_diff[m] >= theta_pro_c); #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD double pa_p = neurons[m].getPProteinAmount(); double pa_d = neurons[m].getDProteinAmount(); double p_synth_end_p = 0.; double p_synth_end_d = 0.; // Potentiation pool if (sum_h_diff_p[m] > theta_pro_p) // still rising { ps_neuron = ps_neuron || true; p_synth_end_p = tau_h / 0.1 * log(sum_h_diff_p[m] / theta_pro_p); if (delta_t < p_synth_end_p) // rising phase only { pa_p = pa_p * exp(-delta_t/(tau_pp * 3600.)) + alpha_p * (1. - exp(-delta_t/(tau_pp * 3600.))); } else // rising phase transitioning to declining phase { pa_p = pa_p * exp(-p_synth_end_p/(tau_pp * 3600.)) + alpha_p * (1. - exp(-p_synth_end_p/(tau_pp * 3600.))); pa_p = pa_p * exp(-(delta_t-p_synth_end_p)/(tau_pp * 3600.)); *logf << "Protein synthesis (P) ending in neuron " << m << " (t = " << p_synth_end_p + tb*dt << " s)" << endl; } } else // declining phase only { pa_p = pa_p * exp(-delta_t/(tau_pp * 3600.)); } // Depression pool if (sum_h_diff_d[m] > theta_pro_d) // still rising { ps_neuron = ps_neuron || true; p_synth_end_d = tau_h / 0.1 * log(sum_h_diff_d[m] / theta_pro_d); if (delta_t < p_synth_end_d) // rising phase only { pa_d = pa_d * exp(-delta_t/(tau_pd * 3600.)) + alpha_d * (1. - exp(-delta_t/(tau_pd * 3600.))); } else // rising phase transitioning to declining phase { pa_d = pa_d * exp(-p_synth_end_d/(tau_pd * 3600.)) + alpha_d * (1. - exp(-p_synth_end_d/(tau_pd * 3600.))); pa_d = pa_d * exp(-(delta_t-p_synth_end_d)/(tau_pd * 3600.)); *logf << "Protein synthesis (D) ending in neuron " << m << " (t = " << p_synth_end_d + tb*dt << " s)" << endl; } } else // declining phase only { pa_d = pa_d * exp(-delta_t/(tau_pd * 3600.)); } sum_h_diff_p[m] = 0.; sum_h_diff_d[m] = 0.; #else double pa_p = 0.; double pa_d = 0.; #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD double pa_c = neurons[m].getCProteinAmount(); double p_synth_end_c = 0.; // Common pool if (sum_h_diff[m] > theta_pro_c) // still rising { ps_neuron = ps_neuron || true; p_synth_end_c = tau_h / 0.1 * log(sum_h_diff[m] / theta_pro_c); if (delta_t < p_synth_end_c) // rising phase only { pa_c = pa_c * exp(-delta_t/(tau_pc * 3600.)) + alpha_c * (1. - exp(-delta_t/(tau_pc * 3600.))); } else // rising phase transitioning to declining phase { pa_c = pa_c * exp(-p_synth_end_c/(tau_pc * 3600.)) + alpha_c * (1. - exp(-p_synth_end_c/(tau_pc * 3600.))); pa_c = pa_c * exp(-(delta_t-p_synth_end_c)/(tau_pc * 3600.)); *logf << "Protein synthesis (C) ending in neuron " << m << " (t = " << p_synth_end_c + tb*dt << " s)" << endl; } } else // declining phase only { pa_c = pa_c * exp(-delta_t/(tau_pc * 3600.)); } sum_h_diff[m] = 0.; #else double pa_c = 0.; #endif neurons[m].setProteinAmounts(pa_p, pa_c, pa_d); #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC } /*******************************************************/ // compute synaptic dynamics for (int m=0; m<N; m++) // loop over presynaptic neurons (in consecutive order) { for (int in=0; in<neurons[m].getNumberOutgoing(); in++) // loop over postsynaptic neurons { int n = neurons[m].getOutgoingConnection(in); // get index (in consecutive order) of postsynaptic neuron double h_dev; // the deviation of the early-phase weight from its resting state // Long-term plasticity if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections { #if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC // early-phase weight just decays double hexp = exp(-delta_t*0.1/tau_h); h[m][n] = h[m][n] * hexp + h_0 * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]))*(delta_t/tau_h));] h_dev = h[m][n] - h_0; #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD if (h_dev > 0.) sum_h_diff_p[n] += h_dev; // sum of early-phases changes (for LTP-related protein synthesis) else if (h_dev < 0.) sum_h_diff_d[n] -= h_dev; // sum of early-phases changes (for LTD-related protein synthesis) #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD sum_h_diff[n] += abs(h_dev); // sum of early-phases changes (for protein synthesis) #endif #endif // PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC // L-LTP/-LTD if (h_dev >= theta_tag_p) // LTP { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getPProteinAmount()*neurons[n].getCProteinAmount(); // LTP protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getPProteinAmount(); // LTP protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-delta_t / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-delta_t / (tau_z * 60. * z_max) * pa); z[m][n] = z[m][n] * zexp + z_max * (1. - zexp); STC = true; } } else if (-h_dev >= theta_tag_d) // LTD { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getDProteinAmount()*neurons[n].getCProteinAmount(); // LTD protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getDProteinAmount(); // LTD protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-delta_t / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-delta_t / (tau_z * 60.) * pa); z[m][n] = z[m][n] * zexp - 0.5 * (1. - zexp); STC = true; } } // [simple Euler: z[m][n] += (pa * ((1 - z[m][n]) * step1 - (0.5 + z[m][n]) * step2) * (delta_t / (tau_z * 6.0 * 10)));] #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC } // plasticity within excitatory population } // loop over postsynaptic neurons } // loop over presynaptic neurons if (!STC) // no late-phase dynamics can take place anymore { return false; } return true; } /*** getSumDiff *** * Returns the sum of absolute values of weight differences to the initial value for a specific neuron * * - n: number of the neuron to be considered * * - return: sum_h_diff for a specific neuron */ double getSumDiff(int n) { return sum_h_diff[n]; } #ifdef TWO_NEURONS_ONE_SYNAPSE /*** getPlasticityType *** * Returns the kind of plasticity evoked by the stimulus * * - return: 0 for ELTP, 1 for ELTP with tag, 2 for LLTP, 3 for ELTD, 4 for ELTD with tag, 5 for LLTD, -1 else */ int getPlasticityType() { if (max_dev > EPSILON) // LTP { if (!tag_glob) return 0; else { if (!ps_glob) return 1; else return 2; } } else if (max_dev < -EPSILON) // LTD { if (!tag_glob) return 3; else { if (!ps_glob) return 4; else return 5; } } return -1; } /*** getMaxDev *** * Returns the maximum deviation from h_0 * * - return: max_dev*/ double getMaxDev() { return max_dev; } #endif /*** getTagVanishTime *** * Returns the time by which all tags will have vanished, based on * * the largest early-phase deviation from the mean h_0 (max_dev) * * - return: the time difference */ double getTagVanishTime() { double tag_vanish = tau_h / 0.1 * log(abs(max_dev) / min(theta_tag_p, theta_tag_d)); if (abs(max_dev) > EPSILON && tag_vanish > EPSILON) return tag_vanish + tb_max_dev*dt; else return 0.; } /*** getProteinSynthesisEnd *** * Returns the time (for every pool) by which all protein synthesis will halt, based on the * * largest sum of early-phase deviations from the mean h_0 (max_sum_diff*) * * - return: the times for the different pools (P,C,D) in a vector */ vector<double> getProteinSynthesisEnd() { vector<double> ret(3,0.); #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD if (max_sum_diff > theta_pro_c) ret[1] = tau_h / 0.1 * log(max_sum_diff / theta_pro_c) + tb_max_sum_diff*dt; #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD if (max_sum_diff_p > theta_pro_p) ret[0] = tau_h / 0.1 * log(max_sum_diff_p / theta_pro_p) + tb_max_sum_diff_p*dt; if (max_sum_diff_d > theta_pro_d) ret[2] = tau_h / 0.1 * log(max_sum_diff_d / theta_pro_d) + tb_max_sum_diff_d*dt; #endif return ret; } /*** getThreshold *** * Returns a specified threshold value (for tag or protein synthesis) * * - plast: the type of plasticity (1: LTP, 2: LTD) * - which: the type of threshold (1: early-phase calcium treshold, 2: tagging threshold, 3: protein synthesis threshold) * - return: the threshold value */ double getThreshold(int plast, int which) { if (plast == 1) // LTP { if (which == 1) // early-phase calcium treshold return theta_p; else if (which == 2) // tagging threshold return theta_tag_p; else // protein synthesis threshold return theta_pro_p; } else // LTD { if (which == 1) // early-phase calcium treshold return theta_d; else if (which == 2) // tagging threshold return theta_tag_d; else // protein synthesis threshold return theta_pro_d; } } /*** setRhombStimulus *** * Sets a spatially rhomb-shaped firing rate stimulus in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons, radius 4 to 41, radius 5 to 61, radius 9 to 181) */ void setRhombStimulus(Stimulus& _st, int center, int radius) { for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { neurons[center+i*Nl_exc+j].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron } } setStimulationEnd(_st.getStimulationEnd()); } /*** setRhombPartialRandomStimulus *** * Sets stimulation for randomly drawn neurons out of a rhomb shape in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons) * * - double fraction: the fraction of neurons in the rhomb that shall be stimulated */ void setRhombPartialRandomStimulus(Stimulus& _st, int center, int radius, double fraction) { int total_assembly_size = 2*pow2(radius) + 2*radius + 1; // total number of neurons within the rhomb int ind = 0, count = 0; uniform_int_distribution<int> rhomb_dist(1, total_assembly_size); int* indices; // array of indices (consectuive neuron numbers) for rhomb neurons indices = new int[total_assembly_size]; // gather indices of neurons belonging to the rhomb for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { indices[ind++] = center+i*Nl_exc+j; } } // draw random neurons out of the rhomb while(count < fraction*total_assembly_size) { int chosen_n = rhomb_dist(rg); if (indices[chosen_n-1] >= 0) // found a neuron that has not be assigned a stimulus { neurons[indices[chosen_n-1]].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron count++; indices[chosen_n-1] = -1; } } setStimulationEnd(_st.getStimulationEnd()); delete[] indices; } /*** setRhombPartialStimulus *** * Sets stimulation for first fraction of neurons out of a rhomb shape in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons) * * - double fraction: the fraction of neurons in the rhomb that shall be stimulated */ void setRhombPartialStimulus(Stimulus& _st, int center, int radius, double fraction) { int count = int(fraction * (2*radius*(radius+1)+1)); for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { neurons[center+i*Nl_exc+j].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron count--; if (count == 0) break; } if (count == 0) break; } setStimulationEnd(_st.getStimulationEnd()); } /*** setRandomStimulus *** * Sets a randomly distributed firing rate stimulus in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int num: the number of neurons to be drawn (i.e., to be stimulated) * * - ofstream* f [optional]: handle to a file for output of the randomly drawn neuron numbers * * - int range_start [optional]: the lowest neuron number that can be drawn * * - int range_end [optional]: one plus the highest neuron number that can be drawn (-1: highest possible) */ void setRandomStimulus(Stimulus& _st, int num, ofstream* f = NULL, int range_start=0, int range_end=-1) { int range_len = (range_end == -1) ? (pow2(Nl_exc) - range_start) : (range_end - range_start); // the number of neurons eligible for being drawn bool* stim_neurons = new bool [range_len]; uniform_int_distribution<int> u_dist_neurons(0, range_len-1); // uniform distribution to draw neuron numbers int neurons_left = num; if (f != NULL) *f << "Randomly drawn neurons for stimulation:" << " { "; for (int i=0; i<range_len; i++) stim_neurons[i] = false; while (neurons_left > 0) { int neur = u_dist_neurons(rg); // draw a neuron if (!stim_neurons[neur]) // if the stimulus has not yet been assigned to the drawn neuron { neurons[neur+range_start].setCurrentStimulus(_st); // set temporal course of current stimulus for drawn neuron stim_neurons[neur] = true; neurons_left--; if (f != NULL) *f << neur+range_start << ", "; // print stimulated neuron to file } } setStimulationEnd(_st.getStimulationEnd()); if (f != NULL) *f << " }" << endl; delete[] stim_neurons; } /*** setSingleNeuronStimulus *** * Sets a firing rate stimulus for a specified neuron * * - int m: number of the neuron to be stimulated * * - Stimulus& _st: shape of one stimulus period */ void setSingleNeuronStimulus(int m, Stimulus& _st) { neurons[m].setCurrentStimulus(_st); setStimulationEnd(_st.getStimulationEnd()); } /*** setBlockStimulus *** * Sets a stimulus for a given block of n neurons in the network * * - Stimulus& _st: shape of one stimulus period * * - int n: the number of neurons that shall be stimulated * * - int off [optional]: the offset that defines at which neuron number the block begins */ void setBlockStimulus(Stimulus& _st, int n, int off=0) { for (int i=off; i<(n+off); i++) { neurons[i].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron } setStimulationEnd(_st.getStimulationEnd()); } /*** setConstCurrent *** * Sets the constant current for all neurons to a newly defined value * - double _I_const: constant current in nA */ void setConstCurrent(double _I_const) { for (int m=0; m<N; m++) { neurons[m].setConstCurrent(_I_const); } } #if STIPULATE_CA == ON /*** stipulateRhombAssembly *** * Stipulates a rhomb-shaped cell assembly with strong interconnections * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons, radius 5 to 61 neurons) */ void stipulateRhombAssembly(int center, int radius) { double value = 2*h_0; // stipulated value for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { int m = center+i*Nl_exc+j; for (int k=-radius; k<=radius; k++) { int num_cols = (radius-abs(k)); for (int l=-num_cols; l<=num_cols; l++) { int n = center+k*Nl_exc+l; if (conn[m][n]) // set all connections within the assembly to this value h[m][n] = value; } } } } } /*** stipulateFirstNeuronsAssembly *** * Stipulates an cell assembly consisting of the first neurons with strong interconnections * * - int n: the number of neurons that shall be stimulated */ void stipulateFirstNeuronsAssembly(int n) { double value = 2*h_0; // stipulated value for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (conn[i][j]) // set all connections within the assembly to this value h[i][j] = value; } } } #endif /*** setSigma *** * Sets the standard deviation for the external input current for all neurons to a newly defined value * - double _sigma: standard deviation in nA s^(1/2) */ void setSigma(double _sigma) { for (int m=0; m<N; m++) { neurons[m].setSigma(_sigma); } } /*** setSynTimeConstant *** * Sets the synaptic time constant * * - double _tau_syn: synaptic time constant in s */ void setSynTimeConstant(double _tau_syn) { tau_syn = _tau_syn; for (int m=0; m<N; m++) { neurons[m].setTauOU(tau_syn); } } /*** setCouplingStrengths *** * Sets the synaptic coupling strengths * * - double _w_ee: coupling strength for exc. -> exc. connections in units of h_0 * * - double _w_ei: coupling strength for exc. -> inh. connections in units of h_0 * * - double _w_ie: coupling strength for inh. -> exc. connections in units of h_0 * * - double _w_ii: coupling strength for inh. -> inh. connections in units of h_0 */ void setCouplingStrengths(double _w_ee, double _w_ei, double _w_ie, double _w_ii) { w_ee = _w_ee * h_0; w_ei = _w_ei * h_0; w_ie = _w_ie * h_0; w_ii = _w_ii * h_0; } /*** getInitialWeight *** * Returns the initial exc.->exc. weight (typically h_0) */ double getInitialWeight() { return w_ee; } /*** getSynapticCalcium *** * Returns the calcium amount at a given synapse * * - synapse s: structure specifying pre- and postsynaptic neuron * * - return: the synaptic calcium amount */ double getSynapticCalcium(synapse s) const { return Ca[s.presyn_neuron][s.postsyn_neuron]; } /*** getEarlySynapticStrength *** * Returns the early-phase synaptic strength at a given synapse * * - synapse s: structure specifying pre- and postsynaptic neuron * * - return: the early-phase synaptic strength */ double getEarlySynapticStrength(synapse s) const { return h[s.presyn_neuron][s.postsyn_neuron]; } /*** getLateSynapticStrength *** * Returns the late-phase synaptic strength at a given synapse * * - synapse s: structure specifying pre- and postsynaptic neuron * * - return: the late-phase synaptic strength */ double getLateSynapticStrength(synapse s) const { return z[s.presyn_neuron][s.postsyn_neuron]; } /*** getMeanEarlySynapticStrength *** * Returns the mean early-phase synaptic strength (averaged over all synapses within the given set of neurons) * * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the mean early-phase synaptic strength */ double getMeanEarlySynapticStrength(int n, int off=0) const { double h_mean = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; h_mean += h[i][j]; } } } h_mean /= c_number; return h_mean; } /*** getMeanLateSynapticStrength *** * Returns the mean late-phase synaptic strength (averaged over all synapses within the given set of neurons) * * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the mean late-phase synaptic strength */ double getMeanLateSynapticStrength(int n, int off=0) const { double z_mean = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; z_mean += z[i][j]; } } } z_mean /= c_number; return z_mean; } /*** getSDEarlySynapticStrength *** * Returns the standard deviation of the early-phase synaptic strength (over all synapses within the given set of neurons) * * - double mean: the mean of the early-phase syn. strength within the given set * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the std. dev. of the early-phase synaptic strength */ double getSDEarlySynapticStrength(double mean, int n, int off=0) const { double h_sd = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; h_sd += pow2(h[i][j] - mean); } } } h_sd = sqrt(h_sd / c_number); return h_sd; } /*** getSDLateSynapticStrength *** * Returns the standard deviation of the late-phase synaptic strength (over all synapses within the given set of neurons) * * - double mean: the mean of the late-phase syn. strength within the given set * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the std. dev. of the late-phase synaptic strength */ double getSDLateSynapticStrength(double mean, int n, int off=0) const { double z_sd = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; z_sd += pow2(z[i][j] - mean); } } } z_sd = sqrt(z_sd / c_number); return z_sd; } /*** getMeanCProteinAmount *** * Returns the mean protein amount (averaged over all neurons within the given set) * * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the mean protein amount */ double getMeanCProteinAmount(int n, int off=0) const { double pa = 0.; for (int i=off; i < (n+off); i++) { pa += neurons[i].getCProteinAmount(); } pa /= n; return pa; } /*** getSDCProteinAmount *** * Returns the standard deviation of the protein amount (over all neurons within the given set) * * - double mean: the mean of the protein amount within the given set * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the std. dev. of the protein amount */ double getSDCProteinAmount(double mean, int n, int off=0) const { double pa_sd = 0.; for (int i=off; i < (n+off); i++) { pa_sd += pow2(neurons[i].getCProteinAmount() - mean); } pa_sd = sqrt(pa_sd / n); return pa_sd; } /*** readConnections *** * Reads the connectivity matrix from a file, either given by a text-converted numpy array or a plain matrix structure * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened, 0 - dimension mismatch */ int readConnections(string file, int format = 0) { ifstream f(file, ios::in); // the file handle string buf; // buffer to read one line int m, n = 0; // pre- and postsynaptic neuron int initial_brackets = 0; // specifies if the initial brackets have been read yet if (!f.is_open()) // check if file was opened successfully return 1; for (int a=0;a<N;a++) // reset connections of all neurons neurons[a].resetConnections(); if (format == 0) m = -1; else m = 0; while (getline(f, buf)) // while end of file has not yet been reached { if (format == 0 && buf.size() > 0) { m++; n = 0; } for (int i=0; i<buf.size(); i++) // go through all characters in this line { if (format == 1 && buf[i] == '[') { if (initial_brackets < 2) // still reading the initial brackets initial_brackets++; else { m++; n = 0; } } else if (buf[i] == '1') { if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // exc. -> exc. { neurons[m].addOutgoingConnection(n, TYPE_EXC); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_EXC); } else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) // exc. -> inh. { neurons[m].addOutgoingConnection(n, TYPE_INH); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_EXC); } else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) // inh. -> exc. { neurons[m].addOutgoingConnection(n, TYPE_EXC); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_INH); } else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) // inh. -> inh. { neurons[m].addOutgoingConnection(n, TYPE_INH); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_INH); } conn[m][n] = true; n++; } else if (buf[i] == '0') { conn[m][n] = false; n++; } } } f.close(); reset(); if (m != (N-1) || n != N) // if dimensions do not match return 0; return 2; } /*** printConnections *** * Prints the connection matrix to a given file (either in numpy structure or in plain matrix structure) * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened */ int printConnections(string file, int format = 0) { ofstream f(file); // the file handle if (!f.is_open()) // check if file was opened successfully return 1; if (format == 1) f << "["; for (int m=0;m<N;m++) { if (format == 1) f << "["; for (int n=0;n<N;n++) { if (conn[m][n]) f << "1 "; else f << "0 "; } if (format == 1) f << "]"; f << endl; } if (format == 1) f << "]"; f.close(); return 2; } /*** printConnections2 *** * FOR TESTING THE CONNECTIONS SAVED IN ARRAYS IN NEURONS * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened * int printConnections2(string file, int format = 0) { ofstream f(file); // the file handle if (!f.is_open()) // check if file was opened successfully return 1; if (format == 1) f << "["; for (int m=0;m<N;m++) { if (format == 1) f << "["; int in=0; for (int n=0;n<N;n++) { if (conn[m][n] && neurons[m].getNumberOutgoing() > in && neurons[m].getOutgoingConnection(in) == n) { f << "1 "; in++; } else f << "0 "; } if (format == 1) f << "]"; f << endl; } if (format == 1) f << "]"; f.close(); return 2; }*/ /*** printAllInitialWeights *** * Prints the connection matrix to a given file (either in numpy structure or in plain matrix structure) * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened */ int printAllInitialWeights(string file, int format = 0) { ofstream f(file); // the file handle if (!f.is_open()) // check if file was opened successfully return 1; if (format == 1) f << "["; for (int m=0;m<N;m++) { if (format == 1) f << "["; for (int n=0;n<N;n++) { // Output of all initial weights if (conn[m][n]) { if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // exc. -> exc. f << h[m][n] << " "; else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) // exc. -> inh. f << w_ei << " "; else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) // inh. -> exc. f << w_ie << " "; else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) // inh. -> inh. f << w_ii << " "; } else f << 0. << " "; } if (format == 1) f << "]"; f << endl; } if (format == 1) f << "]"; f.close(); return 2; } /*** readCouplingStrengths *** * Reads the excitatory coupling strengths from a text file that contains a matrix for early-phase weights and a matrix * * for late-phase weights, each terminated by a blank line * * - file: a text file where the matrix is located * * - return: 2 - successful, 1 - file could not opened, 0 - dimension mismatch */ int readCouplingStrengths(string file) { int phase = 1; // 1: reading early-phase values, 2: reading late-phase values int m = 0, n; // pre- and postsynaptic neuron double strength; ifstream f(file, ios::in); // the file handle string buf; // buffer to read one line if (!f.is_open()) return 1; // Read early- and late-phase matrix while (getline (f, buf)) { istringstream iss(buf); if (!buf.empty()) { n = 0; while(iss >> strength) { if (phase == 1) h[m][n] = strength; else z[m][n] = strength; n++; } m++; } else // blank line encountered { if (phase == 1) // now begins the second phase { if (m != pow2(Nl_exc) || n != pow2(Nl_exc)) // if dimensions do not match { f.close(); return 0; } phase = 2; m = 0; n = 0; } else break; } } f.close(); if (m != pow2(Nl_exc) || n != pow2(Nl_exc)) // if dimensions do not match { return 0; } return 2; } /*** setStimulationEnd *** * Tells the Network instance the end of stimulation (even if not all stimuli are yet set) * * - int stim_end: the timestep in which stimulation ends */ void setStimulationEnd(int stim_end) { if (stim_end > stimulation_end) stimulation_end = stim_end; } /*** setSpikeStorageTime *** * Sets the number of timesteps for which spikes have to be kept in RAM * * - int storage_steps: the size of the storage timespan in timesteps */ void setSpikeStorageTime(int storage_steps) { for (int m=0; m<N; m++) { neurons[m].setSpikeHistoryMemory(storage_steps); } } /*** resetLastSpikeIndex *** * Resets the last spike index of a neuron important to its calcium dynamics * * - int m: the neuron number */ void resetLastSpikeIndex(int m) { last_Ca_spike_index[m] = 1; } /*** resetPlasticity *** * Depending on the arguments, undoes plastic changes that the network has undergone, * * resets calcium values or protein values * * - bool early_phase: resets all early-phase weights and calcium concentrations * * - bool late_phase: resets all late-phase weights * * - bool calcium: resets all calcium concentrations * * - bool proteins: resets all neuronal protein pools */ void resetPlasticity(bool early_phase, bool late_phase, bool calcium, bool proteins) { for (int m=0; m<N; m++) { if (proteins) neurons[m].setProteinAmounts(0., 0., 0.); for (int n=0; n<N; n++) // reset synapses { if (early_phase) { if (conn[m][n]) h[m][n] = h_0; else h[m][n] = 0.; } if (calcium) Ca[m][n] = 0.; if (late_phase) z[m][n] = 0.; } } } /*** reset *** * Resets the network and all neurons to initial state (but maintain connectivity) */ void reset() { rg.seed(getClockSeed()); // set new seed by clock's epoch u_dist.reset(); // reset the uniform distribution for random numbers norm_dist.reset(); // reset the normal distribution for random numbers for (int m=0; m<N; m++) { neurons[m].reset(); for (int n=0; n<N; n++) // reset synapses { if (conn[m][n]) h[m][n] = h_0; else h[m][n] = 0.; Ca[m][n] = 0.; z[m][n] = 0.; } resetLastSpikeIndex(m); sum_h_diff[m] = 0.; sum_h_diff_p[m] = 0.; sum_h_diff_d[m] = 0.; } stimulation_end = 0; max_dev = 0.; tb_max_dev = 0; #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD max_sum_diff = 0.; tb_max_sum_diff = 0; #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD max_sum_diff_p = 0.; tb_max_sum_diff_p = 0; max_sum_diff_d = 0.; tb_max_sum_diff_d = 0; #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = false; ps_glob = false; #endif } /*** setCaConstants *** * Set constants for the calcium dynamics * * - double _theta_p: the potentiation threshold * * - double _theta_d: the potentiation threshold */ void setCaConstants(double _theta_p, double _theta_d, double _Ca_pre, double _Ca_post) { theta_p = _theta_p; theta_d = _theta_d; Ca_pre = _Ca_pre; Ca_post = _Ca_post; } /*** setPSThresholds *** * Set thresholds for the onset of protein synthesis * * - double _theta_pro_P: the threshold for P synthesis (in units of h0) * * - double _theta_pro_C: the threshold for C synthesis (in units of h0) * * - double _theta_pro_D: the threshold for D synthesis (in units of h0) */ void setPSThresholds(double _theta_pro_P, double _theta_pro_C, double _theta_pro_D) { theta_pro_p = _theta_pro_P*h_0; theta_pro_c = _theta_pro_C*h_0; theta_pro_d = _theta_pro_D*h_0; } /*** Constructor *** * Sets all parameters, creates neurons and synapses * * --> it is required to call setSynTimeConstant and setCouplingStrengths immediately * * after calling this constructor! * * - double _dt: the length of one timestep in s * * - int _Nl_exc: the number of neurons in one line in excitatory population (row/column) * * - int _Nl_inh: the number of neurons in one line in inhibitory population (row/column) - line structure so that stimulation of inhib. * population could be implemented more easily * * - double _p_c: connection probability * * - double _sigma_plasticity: standard deviation of the plasticity * * - double _z_max: the upper z bound */ Network(const double _dt, const int _Nl_exc, const int _Nl_inh, double _p_c, double _sigma_plasticity, double _z_max) : dt(_dt), rg(getClockSeed()), u_dist(0.0,1.0), norm_dist(0.0,1.0), Nl_exc(_Nl_exc), Nl_inh(_Nl_inh), z_max(_z_max) { N = pow2(Nl_exc) + pow2(Nl_inh); // total number of neurons p_c = _p_c; // set connection probability t_syn_delay = 0.003; // from https://www.britannica.com/science/nervous-system/The-neuronal-membrane#ref606406, accessed 18-06-21 #if defined TWO_NEURONS_ONE_SYNAPSE && !defined TWO_NEURONS_ONE_SYNAPSE_ALT t_syn_delay = dt; #endif t_syn_delay_steps = int(t_syn_delay/dt); // Biophysical parameters for stimulation, Ca dynamics and early phase t_Ca_delay = 0.0188; // from Graupner and Brunel (2012), hippocampal slices t_Ca_delay_steps = int(t_Ca_delay/dt); Ca_pre = 1.0; // from Graupner and Brunel (2012), hippocampal slices Ca_post = 0.2758; // from Graupner and Brunel (2012), hippocampal slices tau_Ca = 0.0488; // from Graupner and Brunel (2012), hippocampal slices tau_Ca_steps = int(tau_Ca/dt); tau_h = 688.4; // from Graupner and Brunel (2012), hippocampal slices gamma_p = 1645.6; // from Graupner and Brunel (2012), hippocampal slices gamma_d = 313.1; // from Graupner and Brunel (2012), hippocampal slices h_0 = 0.5*(gamma_p/(gamma_p+gamma_d)); // from Li et al. (2016) theta_p = 3.0; // from Li et al. (2016) theta_d = 1.2; // from Li et al. (2016) sigma_plasticity = _sigma_plasticity; // from Graupner and Brunel (2012) but corrected by 1/sqrt(1000) // Biophysical parameters for protein synthesis and late phase tau_pp = 1.0; // from Li et al. (2016) tau_pc = 1.0; // from Li et al. (2016) tau_pd = 1.0; // from Li et al. (2016) alpha_p = 1.0; // from Li et al. (2016) alpha_c = 1.0; // from Li et al. (2016) alpha_d = 1.0; // from Li et al. (2016) tau_z = 60.0; // from Li et al. (2016) - includes "gamma" theta_pro_p = 0.5*h_0; // theta_pro_c = 0.5*h_0; // from Li et al. (2016) theta_pro_d = 0.5*h_0; // theta_tag_p = 0.2*h_0; // from Li et al. (2016) theta_tag_d = 0.2*h_0; // from Li et al. (2016) // Create neurons and synapse matrices neurons = vector<Neuron> (N, Neuron(_dt)); conn = new bool* [N]; Ca = new double* [N]; h = new double* [N]; z = new double* [N]; last_Ca_spike_index = new int [N]; sum_h_diff = new double [N]; sum_h_diff_p = new double [N]; sum_h_diff_d = new double [N]; for (int m=0; m<N; m++) { if (m < pow2(Nl_exc)) // first Nl_exc^2 neurons are excitatory neurons[m].setType(TYPE_EXC); else // remaining neurons are inhibitory neurons[m].setType(TYPE_INH); conn[m] = new bool [N]; Ca[m] = new double [N]; h[m] = new double [N]; z[m] = new double [N]; // create synaptic connections for (int n=0; n<N; n++) { conn[m][n] = false; // necessary for resetting the connections if (m != n) // if not on main diagonal (which should remain zero) { conn[m][n] = shallBeConnected(m, n); // use random generator depending on connection probability } } } #ifdef TWO_NEURONS_ONE_SYNAPSE neurons[1].setPoisson(true); #ifdef PLASTICITY_OVER_FREQ neurons[0].setPoisson(true); #endif #endif } /*** Destructor *** * Cleans up the allocated memory for arrays */ ~Network() { for(int i=0; i<N; i++) { delete[] conn[i]; delete[] Ca[i]; delete[] h[i]; delete[] z[i]; } delete[] conn; delete[] Ca; delete[] h; delete[] z; delete[] last_Ca_spike_index; delete[] sum_h_diff; delete[] sum_h_diff_p; delete[] sum_h_diff_d; } /* =============================================================================================================================== */ /* ==== Functions redirecting to corresponding functions in Neuron class ========================================================= */ /* Two versions are given for each function, one for consecutive and one for row/column numbering */ /*** getType *** * Returns the type of neuron (i|j) (inhbitory/excitatory) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the neuron type */ int getType(int i, int j) const { return neurons[cNN(i,j)].getType(); } int getType(int m) const { return neurons[m].getType(); } /*** getVoltage *** * Returns the membrane potential of neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the membrane potential in mV */ double getVoltage(int i, int j) const { return neurons[cNN(i,j)].getVoltage(); } double getVoltage(int m) const { return neurons[m].getVoltage(); } /*** getThreshold *** * Returns the value of the dynamic membrane threshold of neuron (i|j) * * - return: the membrane threshold in mV */ double getThreshold(int i, int j) const { return neurons[cNN(i,j)].getThreshold(); } double getThreshold(int m) const { return neurons[m].getThreshold(); } /*** getCurrent *** * Returns total current effecting neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the instantaneous current in nA */ double getCurrent(int i, int j) const { return neurons[cNN(i,j)].getCurrent(); } double getCurrent(int m) const { return neurons[m].getCurrent(); } /*** getStimulusCurrent *** * Returns current evoked by external stimulation in neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the instantaneous current stimulus in nA */ double getStimulusCurrent(int i, int j) const { return neurons[cNN(i,j)].getStimulusCurrent(); } double getStimulusCurrent(int m) const { return neurons[m].getStimulusCurrent(); } /*** getBGCurrent *** * Returns background noise current entering neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the instantaneous fluctuating current in nA */ double getBGCurrent(int i, int j) const { return neurons[cNN(i,j)].getBGCurrent(); } double getBGCurrent(int m) const { return neurons[m].getBGCurrent(); } /*** getConstCurrent *** * Returns the constant current elicited by the surrounding network (not this network!) in neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the constant current in nA */ double getConstCurrent(int i, int j) const { return neurons[cNN(i,j)].getConstCurrent(); } double getConstCurrent(int m) const { return neurons[m].getConstCurrent(); } /*** getSigma *** * Returns the standard deviation of the white noise entering the external current * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the standard deviation in nA s^(1/2) */ double getSigma(int i, int j) const { return neurons[cNN(i,j)].getSigma(); } double getSigma(int m) const { return neurons[m].getSigma(); } /*** getSynapticCurrent *** * Returns the synaptic current that arrived in the previous timestep * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the synaptic current in nA */ double getSynapticCurrent(int i, int j) const { return neurons[cNN(i,j)].getSynapticCurrent(); } double getSynapticCurrent(int m) const { return neurons[m].getSynapticCurrent(); } #if DENDR_SPIKES == ON /*** getDendriticCurrent *** * Returns the current that dendritic spiking caused in the previous timestep * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the synaptic current in nA */ double getDendriticCurrent(int i, int j) const { return neurons[cNN(i,j)].getDendriticCurrent(); } double getDendriticCurrent(int m) const { return neurons[m].getDendriticCurrent(); } #endif #if COND_BASED_SYN == ON /*** getExcSynapticCurrent *** * Returns the internal excitatory synaptic current that arrived in the previous timestep * * - return: the excitatory synaptic current in nA */ double getExcSynapticCurrent(int i, int j) const { return neurons[cNN(i,j)].getExcSynapticCurrent(); } double getExcSynapticCurrent(int m) const { return neurons[m].getExcSynapticCurrent(); } /*** getInhSynapticCurrent *** * Returns the internal inhibitory synaptic current that arrived in the previous timestep * * - return: the inhibitory synaptic current in nA */ double getInhSynapticCurrent(int i, int j) const { return neurons[cNN(i,j)].getInhSynapticCurrent(); } double getInhSynapticCurrent(int m) const { return neurons[m].getInhSynapticCurrent(); } #endif /*** getActivity *** * Returns true if neuron (i|j) is spiking in this instant of duration dt * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: whether neuron is firing or not */ bool getActivity(int i, int j) const { return neurons[cNN(i,j)].getActivity(); } bool getActivity(int m) const { return neurons[m].getActivity(); } /*** spikeAt *** * Returns whether or not a spike has occurred at a given spike, begins searching * * from latest spike * * - int t_step: the timebin at which the spike should have occurred * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: true if a spike occurred, false if not */ bool spikeAt(int t_step, int i, int j) const { return neurons[cNN(i,j)].spikeAt(t_step); } bool spikeAt(int t_step, int m) const { return neurons[m].spikeAt(t_step); } /*** getSpikeTime *** * Returns the spike time for a given spike number (in temporal order, starting with 1) of neuron (i|j) * * ATTENTION: argument n should not exceed the result of getSpikeHistorySize() * * - int n: the number of the considered spike (in temporal order, starting with 1) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the spike time for the n-th spike (or -1 if there exists none) */ int getSpikeTime(int n, int i, int j) const { return neurons[cNN(i,j)].getSpikeTime(n); } int getSpikeTime(int n, int m) const { return neurons[m].getSpikeTime(n); } /*** removeSpikes *** * Removes a specified set of spikes from history, to save memory * * - int start: the number of the spike to start with (in temporal order, starting with 1) * - int end: the number of the spike to end with (in temporal order, starting with 1) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located */ void removeSpikes(int start, int end, int i, int j) { neurons[cNN(i,j)].removeSpikes(start, end); } void removeSpikes(int start, int end, int m) { neurons[m].removeSpikes(start, end); } /*** getSpikeCount *** * Returns the number of spikes that have occurred since the last reset (including those that have been removed) of neuron (i|j) * * - return: the number of spikes */ int getSpikeCount(int i, int j) const { return neurons[cNN(i,j)].getSpikeCount(); } int getSpikeCount(int m) const { return neurons[m].getSpikeCount(); } /*** getSpikeHistorySize *** * Returns the current size of the spike history vector of neuron (i|j) * * - return: the size of the spike history vector */ int getSpikeHistorySize(int i, int j) const { return neurons[cNN(i,j)].getSpikeHistorySize(); } int getSpikeHistorySize(int m) const { return neurons[m].getSpikeHistorySize(); } /*** setCurrentStimulus *** * Sets a current stimulus for neuron (i|j) * - Stimulus& _cst: shape of one stimulus period * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located */ void setCurrentStimulus(Stimulus& _cst, int i, int j) { neurons[cNN(i,j)].setCurrentStimulus(_cst); } void setCurrentStimulus(Stimulus& _cst, int m) { neurons[m].setCurrentStimulus(_cst); } /*** getNumberIncoming *** * Returns the number of either inhibitory or excitatory incoming connections to this neuron * * from other neurons in the network * * - int type: the type of incoming connections (inh./exc.) * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the number of incoming connections */ int getNumberIncoming(int type, int i, int j) const { return neurons[cNN(i,j)].getNumberIncoming(type); } int getNumberIncoming(int type, int m) const { return neurons[m].getNumberIncoming(type); } /*** getNumberOutgoing *** * Returns the number of connections outgoing from this neuron to other * * neurons of a specific type * * - int type: the type of postsynaptic neurons (inh./exc.) * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the number of outgoing connections */ int getNumberOutgoing(int type, int i, int j) const { return neurons[cNN(i,j)].getNumberOutgoing(type); } int getNumberOutgoing(int type, int m) const { return neurons[m].getNumberOutgoing(type); } /*** getPProteinAmount *** * Returns the LTP-related protein amount in a neuron * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: momentary LTP-related protein amount */ double getPProteinAmount(int i, int j) const { return neurons[cNN(i,j)].getPProteinAmount(); } double getPProteinAmount(int m) const { return neurons[m].getPProteinAmount(); } /*** getCProteinAmount *** * Returns the common protein amount in a neuron * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: momentary LTP-related protein amount */ double getCProteinAmount(int i, int j) const { return neurons[cNN(i,j)].getCProteinAmount(); } double getCProteinAmount(int m) const { return neurons[m].getCProteinAmount(); } /*** getDProteinAmount *** * Returns the LTD-related protein amount in a neuron * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: momentary LTD-related protein amount */ double getDProteinAmount(int i, int j) const { return neurons[cNN(i,j)].getDProteinAmount(); } double getDProteinAmount(int m) const { return neurons[m].getDProteinAmount(); } /*** saveNeuronParams *** * Saves all the neuron parameters (including the channel parameters) to a given file; * * all neurons have the same parameters, so the first one is taken */ void saveNeuronParams(ofstream *f) const { neurons[0].saveNeuronParams(f); } /* =============================================================================================================================== */ };
32.375831
161
0.659689
jlubo
97223cf5eab0d82cf2ae033407622716e90e72ba
1,428
cpp
C++
Oem/dbxml/dbxml/src/dbxml/query/QueryPlanToAST.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/dbxml/dbxml/src/dbxml/query/QueryPlanToAST.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/dbxml/dbxml/src/dbxml/query/QueryPlanToAST.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // See the file LICENSE for redistribution information. // // Copyright (c) 2002,2009 Oracle. All rights reserved. // // #include "../DbXmlInternal.hpp" #include "QueryPlanToAST.hpp" #include "ASTToQueryPlan.hpp" #include "QueryPlan.hpp" #include "NodeIterator.hpp" #include <xqilla/ast/XQNav.hpp> #include <xqilla/context/DynamicContext.hpp> using namespace DbXml; using namespace std; QueryPlanToAST::QueryPlanToAST(QueryPlan *qp, StaticContext *context, XPath2MemoryManager *mm) : DbXmlASTNode(QP_TO_AST, mm), qp_(qp) { qp_->staticTypingLite(context); _src.copy(qp_->getStaticAnalysis()); _src.availableCollectionsUsed(true); } ASTNode *QueryPlanToAST::staticTypingImpl(StaticContext *context) { _src.clear(); _src.availableCollectionsUsed(true); _src.copy(qp_->getStaticAnalysis()); if(qp_->getType() == QueryPlan::AST_TO_QP) { return ((ASTToQueryPlan*)qp_)->getASTNode(); } return this; } Result QueryPlanToAST::createResult(DynamicContext* context, int flags) const { return new QueryPlanToASTResult(qp_->createNodeIterator(context), this); } //////////////////////////////////////////////////////////////////////////////////////////////////// QueryPlanToASTResult::~QueryPlanToASTResult() { delete it_; } Item::Ptr QueryPlanToASTResult::next(DynamicContext *context) { if(it_ == 0 || !it_->next(context)) { delete it_; it_ = 0; return 0; } return it_->asDbXmlNode(context); }
21.313433
100
0.688375
achilex
9725f2cc945f31ed11817f4d8f9bcff7d992073b
558
hpp
C++
Classes/PlaneLayer.hpp
nickqiao/AirWar
1cd8b418a1a3ec240bc02581ecff034218939b59
[ "Apache-2.0" ]
2
2017-10-14T06:27:15.000Z
2021-11-05T20:27:28.000Z
Classes/PlaneLayer.hpp
nickqiao/AirWar
1cd8b418a1a3ec240bc02581ecff034218939b59
[ "Apache-2.0" ]
null
null
null
Classes/PlaneLayer.hpp
nickqiao/AirWar
1cd8b418a1a3ec240bc02581ecff034218939b59
[ "Apache-2.0" ]
null
null
null
// // PlaneLayer.hpp // AirWar // // Created by nick on 2017/1/19. // Copyright © 2017年 chenyuqiao. All rights reserved. // #include "cocos2d.h" USING_NS_CC; const int AIRPLANE=747; class PlaneLayer : public Layer { public: PlaneLayer(); ~PlaneLayer(); static PlaneLayer* create(); virtual bool init(); void MoveTo(Point location); void Blowup(int passScore); void RemovePlane(); public: static PlaneLayer* sharedPlane; bool isAlive; int score; };
12.976744
54
0.587814
nickqiao
972b50cd1f04f521e7246ec9b1ca30ac7d0280a9
25,083
cpp
C++
src/genlib/miniserver/miniserver.cpp
xiyusullos/upnpsdk
a1e280530338220a91668e6e6f2f07ccbc0c1382
[ "BSD-3-Clause" ]
null
null
null
src/genlib/miniserver/miniserver.cpp
xiyusullos/upnpsdk
a1e280530338220a91668e6e6f2f07ccbc0c1382
[ "BSD-3-Clause" ]
null
null
null
src/genlib/miniserver/miniserver.cpp
xiyusullos/upnpsdk
a1e280530338220a91668e6e6f2f07ccbc0c1382
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000 Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// // $Revision: 1.2 $ // $Date: 2001/08/15 18:17:31 $ #include "../../inc/tools/config.h" #if EXCLUDE_MINISERVER == 0 #include <arpa/inet.h> #include <netinet/in.h> #include <pthread.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/wait.h> #include <unistd.h> #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <genlib/util/utilall.h> #include <genlib/util/util.h> #include <genlib/miniserver/miniserver.h> #include <genlib/tpool/scheduler.h> #include <genlib/tpool/interrupts.h> #include "upnp.h" #include "tools/config.h" // read timeout #define TIMEOUT_SECS 30 enum MiniServerState { MSERV_IDLE, MSERV_RUNNING, MSERV_STOPPING }; CREATE_NEW_EXCEPTION_TYPE( MiniServerReadException, BasicException, "MiniServerReadException" ) enum READ_EXCEPTION_CODE { RCODE_SUCCESS = 0, RCODE_NETWORK_READ_ERROR = -1, RCODE_MALFORMED_LINE = -2, RCODE_LENGTH_NOT_SPECIFIED = -3, RCODE_METHOD_NOT_ALLOWED = -4, RCODE_INTERNAL_SERVER_ERROR = -5, RCODE_METHOD_NOT_IMPLEMENTED = -6, RCODE_TIMEDOUT = -7, }; enum HTTP_COMMAND_TYPE { CMD_HTTP_GET, CMD_SOAP_POST, CMD_SOAP_MPOST, CMD_GENA_SUBSCRIBE, CMD_GENA_UNSUBSCRIBE, CMD_GENA_NOTIFY, CMD_HTTP_UNKNOWN, CMD_HTTP_MALFORMED }; // module vars static MiniServerCallback gGetCallback = NULL; static MiniServerCallback gSoapCallback = NULL; static MiniServerCallback gGenaCallback = NULL; static MiniServerState gMServState = MSERV_IDLE; static pthread_t gMServThread = 0; ////////////// void SetHTTPGetCallback( MiniServerCallback callback ) { gGetCallback = callback; } MiniServerCallback GetHTTPGetCallback( void ) { return gGetCallback; } void SetSoapCallback( MiniServerCallback callback ) { gSoapCallback = callback; } MiniServerCallback GetSoapCallback( void ) { return gSoapCallback; } void SetGenaCallback( MiniServerCallback callback ) { gGenaCallback = callback; } MiniServerCallback GetGenaCallback( void ) { return gGenaCallback; } class NetReader1 { public: NetReader1( int socketfd ); virtual ~NetReader1(); // throws MiniServerReadException.RCODE_TIMEDOUT int getChar( char& c ); // throws MiniServerReadException.RCODE_TIMEDOUT int getLine( xstring& s, bool& newlineNotFound ); // throws MiniServerReadException.RCODE_TIMEDOUT int readData( void* buf, size_t bufferLen ); int getMaxBufSize() const { return maxbufsize; } private: bool bufferHasData() const { return offset < buflen; } // throws MiniServerReadException.RCODE_TIMEDOUT ssize_t refillBuffer(); private: enum { MAX_BUFFER_SIZE = 1024 * 2 }; private: int sockfd; char data[MAX_BUFFER_SIZE + 1]; // extra byte for null terminator int offset; int buflen; int maxbufsize; }; NetReader1::NetReader1( int socketfd ) { sockfd = socketfd; offset = 0; maxbufsize = MAX_BUFFER_SIZE; buflen = 0; data[maxbufsize] = 0; } NetReader1::~NetReader1() { } int NetReader1::getChar( char& c ) { int status; if ( !bufferHasData() ) { status = refillBuffer(); if ( status <= 0 ) return status; if ( !bufferHasData() ) return 0; } c = data[offset]; offset++; return 1; // length of data returned } int NetReader1::getLine( xstring& s, bool& newlineNotFound ) { int startOffset; char c; int status; bool crFound; startOffset = offset; s = ""; newlineNotFound = false; crFound = false; while ( true ) { status = getChar( c ); if ( status == 0 ) { // no more chars in stream newlineNotFound = true; return s.length(); } if ( status < 0 ) { // some kind of error return status; } s += c; if ( c == 0xA ) { return s.length(); } else if ( c == 0xD ) // CR { crFound = true; } else { // wanted to see LF after CR; error if ( crFound ) { newlineNotFound = true; return s.length(); } } } return 0; } // read data int NetReader1::readData( void* buf, size_t bufferLen ) { int status; int copyLen; size_t dataLeft; // size of data left in buffer if ( bufferLen <= 0 ) return 0; // refill empty buffer if ( !bufferHasData() ) { status = refillBuffer(); if ( status <= 0 ) return status; if ( !bufferHasData() ) return 0; dataLeft = buflen; } else { dataLeft = buflen - offset; } if ( bufferLen < dataLeft ) { copyLen = bufferLen; } else { copyLen = dataLeft; } memcpy( buf, &data[offset], copyLen ); offset += copyLen; return copyLen; } // throws MiniServerReadException.RCODE_TIMEDOUT static int SocketRead( int sockfd, char* buffer, size_t bufsize, int timeoutSecs ) { int retCode; fd_set readSet; struct timeval timeout; int numRead; assert( sockfd > 0 ); assert( buffer != NULL ); assert( bufsize > 0 ); FD_ZERO( &readSet ); FD_SET( sockfd, &readSet ); timeout.tv_sec = timeoutSecs; timeout.tv_usec = 0; while ( true ) { retCode = select( sockfd + 1, &readSet, NULL, NULL, &timeout ); if ( retCode == 0 ) { // timed out MiniServerReadException e( "SocketRead(): timed out" ); e.setErrorCode( RCODE_TIMEDOUT ); throw e; } if ( retCode == -1 ) { if ( errno == EINTR ) { continue; // ignore interrupts } return retCode; // error } else { break; } } // read data numRead = read( sockfd, buffer, bufsize ); return numRead; } ssize_t NetReader1::refillBuffer() { ssize_t numRead; // old code // numRead = read( sockfd, data, maxbufsize ); /////// numRead = SocketRead( sockfd, data, maxbufsize, TIMEOUT_SECS ); if ( numRead >= 0 ) { buflen = numRead; } else { buflen = 0; } offset = 0; return numRead; } static void WriteNetData( const char* s, int sockfd ) { write( sockfd, s, strlen(s) ); } // determines type of UPNP command from request line, ln static HTTP_COMMAND_TYPE GetCommandType( const xstring& ln ) { // commands GET, POST, M-POST, SUBSCRIBE, UNSUBSCRIBE, NOTIFY xstring line = ln; int i; char c; char * getStr = "GET"; char * postStr = "POST"; char * mpostStr = "M-POST"; char * subscribeStr = "SUBSCRIBE"; char * unsubscribeStr = "UNSUBSCRIBE"; char * notifyStr = "NOTIFY"; char * pattern; HTTP_COMMAND_TYPE retCode=CMD_HTTP_UNKNOWN; try { line.toUppercase(); c = line[0]; switch (c) { case 'G': pattern = getStr; retCode = CMD_HTTP_GET; break; case 'P': pattern = postStr; retCode = CMD_SOAP_POST; break; case 'M': pattern = mpostStr; retCode = CMD_SOAP_MPOST; break; case 'S': pattern = subscribeStr; retCode = CMD_GENA_SUBSCRIBE; break; case 'U': pattern = unsubscribeStr; retCode = CMD_GENA_UNSUBSCRIBE; break; case 'N': pattern = notifyStr; retCode = CMD_GENA_NOTIFY; break; default: // unknown method throw -1; } int patLength = strlen( pattern ); for ( i = 1; i < patLength; i++ ) { if ( line[i] != pattern[i] ) throw -1; } } catch ( OutOfBoundsException& e ) { return CMD_HTTP_UNKNOWN; } catch ( int parseCode ) { if ( parseCode == -1 ) { return CMD_HTTP_UNKNOWN; } } return retCode; } static int ParseContentLength( const xstring& textLine, bool& malformed ) { xstring line; xstring asciiNum; char *pattern = "CONTENT-LENGTH"; int patlen = strlen( pattern ); int i; int contentLength; malformed = false; contentLength = -1; line = textLine; line.toUppercase(); if ( strncmp(line.c_str(), pattern, patlen) != 0 ) { // unknown header return -1; } i = patlen; try { // skip whitespace while ( line[i] == ' ' || line [i] == '\t' ) { i++; } // ":" if ( line[i] != ':' ) { throw -1; } i++; char* invalidChar = NULL; contentLength = strtol( &line[i], &invalidChar, 10 ); // anything other than crlf or whitespace after number is invalid if ( *invalidChar != '\0' ) { // see if there is an invalid number while ( *invalidChar ) { char c; c = *invalidChar; if ( !(c == ' ' || c == '\t' || c == '\r' || c == '\n') ) { // invalid char in number throw -1; } invalidChar++; } } } catch ( OutOfBoundsException& e ) { malformed = true; return -1; } catch ( int errCode ) { if ( errCode == -1 ) { malformed = true; return -1; } } return contentLength; } // throws // OutOfMemoryException // MiniServerReadException // RCODE_NETWORK_READ_ERROR // RCODE_MALFORMED_LINE // RCODE_METHOD_NOT_IMPLEMENTED // RCODE_LENGTH_NOT_SPECIFIED static void ReadRequest( int sockfd, xstring& document, HTTP_COMMAND_TYPE& command ) { NetReader1 reader( sockfd ); xstring reqLine; xstring line; bool newlineNotFound; int status; HTTP_COMMAND_TYPE cmd; int contentLength; const int BUFSIZE = 3; char buf[ BUFSIZE + 1 ]; MiniServerReadException excep; document = ""; // read request-line status = reader.getLine( reqLine, newlineNotFound ); if ( status < 0 ) { // read error excep.setErrorCode( RCODE_NETWORK_READ_ERROR ); throw excep; } if ( newlineNotFound ) { // format error excep.setErrorCode( RCODE_MALFORMED_LINE ); throw excep; } cmd = GetCommandType( reqLine ); if ( cmd == CMD_HTTP_UNKNOWN ) { // unknown or unsupported cmd excep.setErrorCode( RCODE_METHOD_NOT_IMPLEMENTED ); throw excep; } document += reqLine; contentLength = -1; // init // read headers while ( true ) { status = reader.getLine( line, newlineNotFound ); if ( status < 0 ) { // network error excep.setErrorCode( RCODE_NETWORK_READ_ERROR ); throw excep; } if ( newlineNotFound ) { // bad format excep.setErrorCode( RCODE_MALFORMED_LINE ); throw excep; } // get content-length if not obtained already if ( contentLength < 0 ) { bool malformed; contentLength = ParseContentLength( line, malformed ); if ( malformed ) { excep.setErrorCode( RCODE_MALFORMED_LINE ); throw excep; } } document += line; // done ? if ( line == "\n" || line == "\r\n" ) { break; } } // must have body for POST and M-POST msgs if ( contentLength < 0 && (cmd == CMD_SOAP_POST || cmd == CMD_SOAP_MPOST) ) { // HTTP: length reqd excep.setErrorCode( RCODE_LENGTH_NOT_SPECIFIED ); throw excep; } if ( contentLength > 0 ) { int totalBytesRead = 0; // read body while ( true ) { int bytesRead; bytesRead = reader.readData( buf, BUFSIZE ); if ( bytesRead > 0 ) { buf[ bytesRead ] = 0; // null terminate string document.appendLimited( buf, bytesRead ); totalBytesRead += bytesRead; if ( totalBytesRead >= contentLength ) { // done reading data break; } } else if ( bytesRead == 0 ) { // done break; } else { // error reading excep.setErrorCode( RCODE_NETWORK_READ_ERROR ); throw excep; } } } command = cmd; } // throws OutOfMemoryException static void HandleError( int errCode, int sockfd ) { xstring errMsg; switch (errCode) { case RCODE_NETWORK_READ_ERROR: break; case RCODE_TIMEDOUT: break; case RCODE_MALFORMED_LINE: errMsg = "400 Bad Request"; break; case RCODE_LENGTH_NOT_SPECIFIED: errMsg = "411 Length Required"; break; case RCODE_METHOD_NOT_ALLOWED: errMsg = "405 Method Not Allowed"; break; case RCODE_INTERNAL_SERVER_ERROR: errMsg = "500 Internal Server Error"; break; case RCODE_METHOD_NOT_IMPLEMENTED: errMsg = "511 Not Implemented"; break; default: DBG( UpnpPrintf( UPNP_CRITICAL, MSERV, __FILE__, __LINE__, "HandleError: unknown code %d\n", errCode ); ) break; }; // no error msg to send; done if ( errMsg.length() == 0 ) return; xstring msg; msg = "HTTP/1.1 "; msg += errMsg; msg += "\r\n\r\n"; // send msg WriteNetData( msg.c_str(), sockfd ); // dbg // sleep so that client does get connection reset //sleep( 3 ); /////// // dbg DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "http error: %s\n", msg.c_str() ); ) /////// } // throws MiniServerReadException.RCODE_METHOD_NOT_IMPLEMENTED static void MultiplexCommand( HTTP_COMMAND_TYPE cmd, const xstring& document, int sockfd ) { MiniServerCallback callback; switch ( cmd ) { case CMD_SOAP_POST: case CMD_SOAP_MPOST: callback = gSoapCallback; break; case CMD_GENA_NOTIFY: case CMD_GENA_SUBSCRIBE: case CMD_GENA_UNSUBSCRIBE: callback = gGenaCallback; break; case CMD_HTTP_GET: callback = gGetCallback; break; default: callback = NULL; } //DBG(printf("READ>>>>>>\n%s\n<<<<<<READ\n", document.c_str())); if ( callback == NULL ) { MiniServerReadException e( "callback not defined or unknown method" ); e.setErrorCode( RCODE_METHOD_NOT_IMPLEMENTED ); throw e; } callback( document.c_str(), sockfd ); } static void HandleRequest( void *args ) { int sockfd; xstring document; HTTP_COMMAND_TYPE cmd; sockfd = (long) args; try { ReadRequest( sockfd, document, cmd ); // pass data to callback MultiplexCommand( cmd, document, sockfd ); //printf( "input document:\n%s\n", document.c_str() ); } catch ( MiniServerReadException& e ) { //DBG( e.print(); ) DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "error code = %d\n", e.getErrorCode()); ) HandleError( e.getErrorCode(), sockfd ); // destroy connection close( sockfd ); } catch ( ... ) { DBG( UpnpPrintf( UPNP_CRITICAL, MSERV, __FILE__, __LINE__, "HandleRequest(): unknown error\n"); ) close( sockfd ); } } static void RunMiniServer( void* args ) { struct sockaddr_in clientAddr; int listenfd; listenfd = (long)args; gMServThread = pthread_self(); gMServState = MSERV_RUNNING; try { while ( true ) { int connectfd; socklen_t clientLen; DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "Waiting...\n" ); ) // get a client request while ( true ) { // stop server if ( gMServState == MSERV_STOPPING ) { throw -9; } connectfd = accept( listenfd, (sockaddr*) &clientAddr, &clientLen ); if ( connectfd > 0 ) { // valid connection break; } if ( connectfd == -1 && errno == EINTR ) { // interrupted -- stop? if ( gMServState == MSERV_STOPPING ) { throw -9; } else { // ignore interruption continue; } } else { xstring errStr = "Error: RunMiniServer: accept(): "; errStr = strerror( errno ); throw BasicException( errStr.c_str() ); } } int sched_stat; sched_stat = tpool_Schedule( HandleRequest, (void*)connectfd ); if ( sched_stat < 0 ) { HandleError( RCODE_INTERNAL_SERVER_ERROR, connectfd ); } //HandleRequest( (void *)connectfd ); } } catch ( GenericException& e ) { //DBG( e.print(); ) } catch ( int code ) { if ( code == -9 ) { // stop miniserver assert( gMServState == MSERV_STOPPING ); DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "Miniserver: recvd STOP signal\n"); ) close( listenfd ); gMServState = MSERV_IDLE; gMServThread = 0; } } } // returns port to which socket, sockfd, is bound. // -1 on error; check errno // > 0 means port number static int get_port( int sockfd ) { sockaddr_in sockinfo; socklen_t len; int code; int port; len = sizeof(sockinfo); code = getsockname( sockfd, (sockaddr*)&sockinfo, &len ); if ( code == -1 ) { return -1; } port = htons( sockinfo.sin_port ); DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "sockfd = %d, .... port = %d\n", sockfd, port ); ) return port; } // if listen port is 0, port is dynamically picked // returns: // on success: actual port socket is bound to // on error: a negative number UPNP_E_XXX int StartMiniServer( unsigned short listen_port ) { struct sockaddr_in serverAddr; int listenfd = 0; int success; int actual_port; int on =1; int retCode = 0; if ( gMServState != MSERV_IDLE ) { return UPNP_E_INTERNAL_ERROR; // miniserver running } try { //printf("listen port: %d\n",listen_port); listenfd = socket( AF_INET, SOCK_STREAM, 0 ); if ( listenfd <= 0 ) { throw UPNP_E_OUTOF_SOCKET; // error creating socket } bzero( &serverAddr, sizeof(serverAddr) ); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = htonl( INADDR_ANY ); serverAddr.sin_port = htons( listen_port ); //THIS IS ALLOWS US TO BIND AGAIN IMMEDIATELY //AFTER OUR SERVER HAS BEEN CLOSED //THIS MAY CAUSE TCP TO BECOME LESS RELIABLE //HOWEVER IT HAS BEEN SUGESTED FOR TCP SERVERS if (setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on, sizeof(int))==-1) { throw UPNP_E_SOCKET_BIND; } success = bind( listenfd, (sockaddr*)&serverAddr, sizeof(serverAddr) ); if ( success == -1 ) { throw UPNP_E_SOCKET_BIND; // bind failed } success = listen( listenfd, 10 ); if ( success == -1 ) { throw UPNP_E_LISTEN; // listen failed } actual_port = get_port( listenfd ); if ( actual_port <= 0 ) { throw UPNP_E_INTERNAL_ERROR; } success = tpool_Schedule( RunMiniServer, (void *)listenfd ); if ( success < 0 ) { throw UPNP_E_OUTOF_MEMORY; } // wait for miniserver to start while ( gMServState != MSERV_RUNNING ) { sleep(1); } retCode = actual_port; } catch ( int catchCode ) { retCode = catchCode; if ( listenfd != 0 ) { close( listenfd ); } } return retCode; } // returns 0: success; -2 if miniserver is idle int StopMiniServer( void ) { if ( gMServState == MSERV_IDLE ) return -2; gMServState = MSERV_STOPPING; // keep sending signals until server stops while ( true ) { if ( gMServState == MSERV_IDLE ) { break; } DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "StopMiniServer(): sending interrupt\n"); ) int code = tintr_Interrupt( gMServThread ); if ( code < 0 ) { DBG( UpnpPrintf( UPNP_CRITICAL, MSERV, __FILE__, __LINE__, "%s: StopMiniServer(): interrupt failed", strerror(errno) ); ) //DBG( perror("StopMiniServer(): interrupt failed"); ) } if ( gMServState == MSERV_IDLE ) { break; } sleep( 1 ); // pause before signalling again } return 0; } #endif
23.398321
95
0.516047
xiyusullos
972b970c9e6a636bf21a733fb3226f50233e9573
4,163
hpp
C++
sdk/boost_1_30_0/boost/integer/static_log2.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
sdk/boost_1_30_0/boost/integer/static_log2.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
sdk/boost_1_30_0/boost/integer/static_log2.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Boost integer/static_log2.hpp header file -------------------------------// // (C) Copyright Daryle Walker 2001. Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or // implied warranty, and with no claim as to its suitability for any purpose. // See http://www.boost.org for updates, documentation, and revision history. #ifndef BOOST_INTEGER_STATIC_LOG2_HPP #define BOOST_INTEGER_STATIC_LOG2_HPP #include <boost/integer_fwd.hpp> // self include #include <boost/config.hpp> // for BOOST_STATIC_CONSTANT, etc. #include <boost/limits.hpp> // for std::numeric_limits #ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION #include <boost/pending/ct_if.hpp> // for boost::ct_if<> #endif namespace boost { // Implementation details --------------------------------------------------// namespace detail { // Forward declarations template < unsigned long Val, int Place = 0, int Index = std::numeric_limits<unsigned long>::digits > struct static_log2_helper_t; #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template < unsigned long Val, int Place > struct static_log2_helper_t< Val, Place, 1 >; #else template < int Place > struct static_log2_helper_final_step; template < unsigned long Val, int Place = 0, int Index = std::numeric_limits<unsigned long>::digits > struct static_log2_helper_nopts_t; #endif // Recursively build the logarithm by examining the upper bits template < unsigned long Val, int Place, int Index > struct static_log2_helper_t { private: BOOST_STATIC_CONSTANT( int, half_place = Index / 2 ); BOOST_STATIC_CONSTANT( unsigned long, lower_mask = (1ul << half_place) - 1ul ); BOOST_STATIC_CONSTANT( unsigned long, upper_mask = ~lower_mask ); BOOST_STATIC_CONSTANT( bool, do_shift = (Val & upper_mask) != 0ul ); BOOST_STATIC_CONSTANT( unsigned long, new_val = do_shift ? (Val >> half_place) : Val ); BOOST_STATIC_CONSTANT( int, new_place = do_shift ? (Place + half_place) : Place ); BOOST_STATIC_CONSTANT( int, new_index = Index - half_place ); #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION typedef static_log2_helper_t<new_val, new_place, new_index> next_step_type; #else typedef static_log2_helper_nopts_t<new_val, new_place, new_index> next_step_type; #endif public: BOOST_STATIC_CONSTANT( int, value = next_step_type::value ); }; // boost::detail::static_log2_helper_t // Non-recursive case #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template < unsigned long Val, int Place > struct static_log2_helper_t< Val, Place, 1 > { public: BOOST_STATIC_CONSTANT( int, value = Place ); }; // boost::detail::static_log2_helper_t #else template < int Place > struct static_log2_helper_final_step { public: BOOST_STATIC_CONSTANT( int, value = Place ); }; // boost::detail::static_log2_helper_final_step template < unsigned long Val, int Place, int Index > struct static_log2_helper_nopts_t { private: typedef static_log2_helper_t<Val, Place, Index> recursive_step_type; typedef static_log2_helper_final_step<Place> final_step_type; typedef typename ct_if<( Index != 1 ), recursive_step_type, final_step_type>::type next_step_type; public: BOOST_STATIC_CONSTANT( int, value = next_step_type::value ); }; // boost::detail::static_log2_helper_nopts_t #endif } // namespace detail // Compile-time log-base-2 evaluator class declaration ---------------------// template < unsigned long Value > struct static_log2 { BOOST_STATIC_CONSTANT( int, value = detail::static_log2_helper_t<Value>::value ); }; template < > struct static_log2< 0ul > { // The logarithm of zero is undefined. }; } // namespace boost #endif // BOOST_INTEGER_STATIC_LOG2_HPP
29.316901
88
0.675715
acidicMercury8
972c55857ab2a64081bc3d0b601fdc8136a6e8de
2,845
cpp
C++
external/openglcts/modules/glesext/draw_buffers_indexed/esextcDrawBuffersIndexedTests.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
354
2017-01-24T17:12:38.000Z
2022-03-30T07:40:19.000Z
external/openglcts/modules/glesext/draw_buffers_indexed/esextcDrawBuffersIndexedTests.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
275
2017-01-24T20:10:36.000Z
2022-03-24T16:24:50.000Z
external/openglcts/modules/glesext/draw_buffers_indexed/esextcDrawBuffersIndexedTests.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
190
2017-01-24T18:02:04.000Z
2022-03-27T13:11:23.000Z
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2015-2016 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ /*! * \file esextcDrawBuffersIndexedTests.cpp * \brief Test group for Draw Buffers Indexed tests */ /*-------------------------------------------------------------------*/ #include "esextcDrawBuffersIndexedTests.hpp" #include "esextcDrawBuffersIndexedBlending.hpp" #include "esextcDrawBuffersIndexedColorMasks.hpp" #include "esextcDrawBuffersIndexedCoverage.hpp" #include "esextcDrawBuffersIndexedDefaultState.hpp" #include "esextcDrawBuffersIndexedNegative.hpp" #include "esextcDrawBuffersIndexedSetGet.hpp" #include "glwEnums.hpp" namespace glcts { /** Constructor * * @param context Test context * @param glslVersion GLSL version **/ DrawBuffersIndexedTests::DrawBuffersIndexedTests(glcts::Context& context, const ExtParameters& extParams) : TestCaseGroupBase(context, extParams, "draw_buffers_indexed", "Draw Buffers Indexed Tests") { /* No implementation needed */ } /** Initializes test cases for Draw Buffers Indexed tests **/ void DrawBuffersIndexedTests::init(void) { /* Initialize base class */ TestCaseGroupBase::init(); /* Draw Buffers Indexed - 1. Coverage */ addChild(new DrawBuffersIndexedCoverage(m_context, m_extParams, "coverage", "Basic coverage test")); /* Draw Buffers Indexed - 2. Default state */ addChild( new DrawBuffersIndexedDefaultState(m_context, m_extParams, "default_state", "Default state verification test")); /* Draw Buffers Indexed - 3. Set and get */ addChild(new DrawBuffersIndexedSetGet(m_context, m_extParams, "set_get", "Setting and getting state test")); /* Draw Buffers Indexed - 4. Color masks */ addChild(new DrawBuffersIndexedColorMasks(m_context, m_extParams, "color_masks", "Masking color test")); /* Draw Buffers Indexed - 5. Blending */ addChild(new DrawBuffersIndexedBlending(m_context, m_extParams, "blending", "Blending test")); /* Draw Buffers Indexed - 6. Negative */ addChild(new DrawBuffersIndexedNegative(m_context, m_extParams, "negative", "Negative test")); } } // namespace glcts
36.012658
114
0.687873
iabernikhin
972e40c3e8102a66fd486836e97db36718a93fd6
1,287
cpp
C++
ProducerConsumer/worker.cpp
bloodMaster/ProducerConsumer
934130b029bff0ce0f314ca65a76f8cbf9b879df
[ "MIT" ]
null
null
null
ProducerConsumer/worker.cpp
bloodMaster/ProducerConsumer
934130b029bff0ce0f314ca65a76f8cbf9b879df
[ "MIT" ]
null
null
null
ProducerConsumer/worker.cpp
bloodMaster/ProducerConsumer
934130b029bff0ce0f314ca65a76f8cbf9b879df
[ "MIT" ]
null
null
null
#include "worker.hpp" #include <iostream> #include <random> std::mutex s_mutex; std::atomic<int> Worker::s_numOfActiveProducers; std::atomic<bool> Worker::s_shouldWork = true; Worker::DataContainer Worker::s_dataContainer; const unsigned int Worker::s_maxSizeOfQueue = 100; const unsigned int Worker::s_allowedSizeForProduction = 80; std::mutex Worker::s_mutex; std::condition_variable Worker::s_producers; std::condition_variable Worker::s_consumers; void Worker:: signalHandler(int sigNum) { s_shouldWork = false; } void Worker:: start() { m_thread = std::thread(&Worker::work, this); } void Worker:: join() { m_thread.join(); } int Worker:: randNumber(int lowerBound, int upperBound) { static thread_local std::mt19937 gen; std::uniform_int_distribution<int> d(lowerBound, upperBound); return d(gen); } void Worker:: sleep() { std::this_thread::sleep_for(std::chrono::milliseconds(randNumber(0, 100))); } void Logger:: work() { while (s_shouldWork || 0 != s_numOfActiveProducers) { log(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } void Logger:: log() { std::unique_lock<std::mutex> uniqueLock(s_mutex); std::cout << "Num of elements: " << s_dataContainer.size() << "\n"; }
19.208955
77
0.685315
bloodMaster
97314d6ac911c17d6d79f8ee95e6d033767e7c29
73,926
cpp
C++
httpendpoints.cpp
qbit-t/qb
c1fd82df3838f8526fc5e335254529ab6f953f78
[ "MIT" ]
1
2021-02-14T04:04:50.000Z
2021-02-14T04:04:50.000Z
httpendpoints.cpp
qbit-t/qb
c1fd82df3838f8526fc5e335254529ab6f953f78
[ "MIT" ]
null
null
null
httpendpoints.cpp
qbit-t/qb
c1fd82df3838f8526fc5e335254529ab6f953f78
[ "MIT" ]
1
2021-08-28T07:42:43.000Z
2021-08-28T07:42:43.000Z
#include "httprequesthandler.h" #include "httpreply.h" #include "httprequest.h" #include "log/log.h" #include "json.h" #include "tinyformat.h" #include "httpendpoints.h" #include "vm/vm.h" #include <iostream> using namespace qbit; void HttpMallocStats::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "mallocstats", "params": [ "<thread_id>", -- (string, optional) thread id "<class_index>", -- (string, optional) class to dump "<path>" -- (string, required if class provided) path to dump to ] } */ /* reply { "result": { "table": [] -- (string array) details }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters if (lParams.size() <= 1) { // param[0] size_t lThreadId = 0; // 0 if (lParams.size() == 1) { json::Value lP0 = lParams[0]; if (lP0.isString()) { if (!convert<size_t>(lP0.getString(), lThreadId)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } char lStats[204800] = {0}; #if defined(JM_MALLOC) if (!lThreadId) { _jm_threads_print_stats(lStats); } else { _jm_thread_print_stats(lThreadId, lStats, JM_ARENA_BASIC_STATS /*| JM_ARENA_CHUNK_STATS | JM_ARENA_DIRTY_BLOCKS_STATS | JM_ARENA_FREEE_BLOCKS_STATS*/, JM_ALLOC_CLASSES); } #endif std::string lValue(lStats); std::vector<std::string> lParts; boost::split(lParts, lValue, boost::is_any_of("\n\t"), boost::token_compress_on); // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); json::Value lKeyArrayObject = lKeyObject.addArray("table"); for (std::vector<std::string>::iterator lString = lParts.begin(); lString != lParts.end(); lString++) { json::Value lItem = lKeyArrayObject.newArrayItem(); lItem.setString(*lString); } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { // param[0] size_t lThreadId = 0; // 0 json::Value lP0 = lParams[0]; if (lP0.isString()) { if (!convert<size_t>(lP0.getString(), lThreadId)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] int lClassIndex = 0; // 1 json::Value lP1 = lParams[1]; if (lP0.isString()) { if (!convert<int>(lP1.getString(), lClassIndex)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] std::string lPath; // 2 json::Value lP2 = lParams[2]; if (lP2.isString()) { lPath = lP2.getString(); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // #if defined(JM_MALLOC) _jm_thread_dump_chunk(lThreadId, 0, lClassIndex, (char*)lPath.c_str()); #endif // prepare reply json::Document lReply; lReply.loadFromString("{}"); lReply.addString("result", "ok"); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetKey::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getkey", "params": [ "<address_id>" -- (string, optional) address ] } */ /* reply { "result": -- (object) address details { "address": "<address>", -- (string) address, base58 encoded "pkey": "<public_key>", -- (string) public key, hex encoded "skey": "<secret_key>", -- (string) secret key, hex encoded "seed": [] -- (string array) seed words }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lAddress; // 0 if (lParams.size()) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } // process SKeyPtr lKey; if (lAddress.size()) { PKey lPKey; if (!lPKey.fromString(lAddress)) { reply = HttpReply::stockReply("E_PKEY_INVALID", "Public key is invalid"); return; } lKey = wallet_->findKey(lPKey); if (!lKey || !lKey->valid()) { reply = HttpReply::stockReply("E_SKEY_NOT_FOUND", "Key was not found"); return; } } else { lKey = wallet_->firstKey(); if (!lKey->valid()) { reply = HttpReply::stockReply("E_SKEY_IS_ABSENT", "Key is absent"); return; } } PKey lPFoundKey = lKey->createPKey(); // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); lKeyObject.addString("address", lPFoundKey.toString()); lKeyObject.addString("pkey", lPFoundKey.toHex()); lKeyObject.addString("skey", lKey->toHex()); json::Value lKeyArrayObject = lKeyObject.addArray("seed"); for (std::vector<SKey::Word>::iterator lWord = lKey->seed().begin(); lWord != lKey->seed().end(); lWord++) { json::Value lItem = lKeyArrayObject.newArrayItem(); lItem.setString((*lWord).wordA()); } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpNewKey::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "newkey", "params": [ ... ] } */ /* reply { "result": -- (object) address details { "address": "<address>", -- (string) address, base58 encoded "pkey": "<public_key>", -- (string) public key, hex encoded "skey": "<secret_key>", -- (string) secret key, hex encoded "seed": [] -- (string array) seed words }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // std::list<std::string> lSeedWords; if (lParams.size()) { // param[0] for (int lIdx = 0; lIdx < lParams.size(); lIdx++) { // json::Value lP0 = lParams[lIdx]; if (lP0.isString()) lSeedWords.push_back(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } } // process SKeyPtr lKey = wallet_->createKey(lSeedWords); if (!lKey->valid()) { reply = HttpReply::stockReply("E_SKEY_IS_INVALID", "Key is invalid"); return; } PKey lPFoundKey = lKey->createPKey(); // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); lKeyObject.addString("address", lPFoundKey.toString()); lKeyObject.addString("pkey", lPFoundKey.toHex()); lKeyObject.addString("skey", lKey->toHex()); json::Value lKeyArrayObject = lKeyObject.addArray("seed"); for (std::vector<SKey::Word>::iterator lWord = lKey->seed().begin(); lWord != lKey->seed().end(); lWord++) { json::Value lItem = lKeyArrayObject.newArrayItem(); lItem.setString((*lWord).wordA()); } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBalance::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getbalance", "params": [ "<asset_id>" -- (string, optional) asset ] } */ /* reply { "result": "1.0", -- (string) corresponding asset balance "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lAsset; // 0 if (lParams.size()) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAsset.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } // process amount_t lScale = QBIT; if (!lAsset.isNull() && lAsset != TxAssetType::qbitAsset()) { // locate asset type EntityPtr lAssetEntity = wallet_->persistentStore()->entityStore()->locateEntity(lAsset); if (lAssetEntity && lAssetEntity->type() == Transaction::ASSET_TYPE) { TxAssetTypePtr lAssetType = TransactionHelper::to<TxAssetType>(lAssetEntity); lScale = lAssetType->scale(); } else { reply = HttpReply::stockReply("E_ASSET", "Asset type was not found"); return; } } // process double lBalance = 0.0; double lPendingBalance = 0.0; IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // main chain only IConsensus::ChainState lState = lMempool->consensus()->chainState(); if (lState == IConsensus::SYNCHRONIZED) { if (!lAsset.isNull()) { amount_t lPending = 0, lActual = 0; wallet_->balance(lAsset, lPending, lActual); lPendingBalance = ((double)lPending) / lScale; lBalance = ((double)lActual) / lScale; } else { amount_t lPending = 0, lActual = 0; wallet_->balance(TxAssetType::qbitAsset(), lPending, lActual); lPendingBalance = ((double)wallet_->pendingBalance()) / lScale; lBalance = ((double)wallet_->balance()) / lScale; } } else if (lState == IConsensus::SYNCHRONIZING) { reply = HttpReply::stockReply("E_NODE_SYNCHRONIZING", "Synchronization is in progress..."); return; } else { reply = HttpReply::stockReply("E_NODE_NOT_SYNCHRONIZED", "Not synchronized"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); lKeyObject.addString("available", strprintf(TxAssetType::scaleFormat(lScale), lBalance)); if (lPendingBalance > lBalance) lKeyObject.addString("pending", strprintf(TxAssetType::scaleFormat(lScale), lPendingBalance-lBalance)); else lKeyObject.addString("pending", strprintf(TxAssetType::scaleFormat(lScale), 0)); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpSendToAddress::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "sendtoaddress", "params": [ "<asset_id>", -- (string) asset or "*" "<address>", -- (string) address "0.1" -- (string) amount ] } */ /* reply { "result": "<tx_id>", -- (string) txid "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lAssetString; // 0 PKey lAddress; // 1 double lValue; // 2 if (lParams.size() == 3) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAssetString = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lAddress.fromString(lP1.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) { if (!convert<double>(lP2.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } uint256 lAsset; if (lAssetString == "*") lAsset = TxAssetType::qbitAsset(); else lAsset.setHex(lAssetString); // locate scale amount_t lScale = QBIT; if (!lAsset.isNull() && lAsset != TxAssetType::qbitAsset()) { // locate asset type EntityPtr lAssetEntity = wallet_->persistentStore()->entityStore()->locateEntity(lAsset); if (lAssetEntity && lAssetEntity->type() == Transaction::ASSET_TYPE) { TxAssetTypePtr lAssetType = TransactionHelper::to<TxAssetType>(lAssetEntity); lScale = lAssetType->scale(); } else { reply = HttpReply::stockReply("E_ASSET", "Asset type was not found"); return; } } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxSpend(lAsset, lAddress, (amount_t)(lValue * (double)lScale)); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_SPEND", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // all spend txs - to the main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } // we good if (lCtx) { // find and broadcast for active clients peerManager_->notifyTransaction(lCtx); } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetPeerInfo::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getpeerinfo", "params": [] } */ /* reply { "result": { "peers": [ { "id": "<peer_id>", -- (string) peer default address id (uint160) "endpoint": "address:port", -- (string) peer endpoint "outbound": true|false, -- (bool) is outbound connection "roles": "<peer_roles>", -- (string) peer roles "status": "<peer_status>", -- (string) peer status "latency": <latency>, -- (int) latency, ms "time": "<peer_time>", -- (string) peer_time, s "chains": [ { "id": "<chain_id>", -- (string) chain id ... } ] }, ... ], }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); json::Value lArrayObject = lKeyObject.addArray("peers"); // get peers std::list<IPeerPtr> lPeers; peerManager_->allPeers(lPeers); // peer manager json::Value lPeerManagerObject = lReply.addObject("manager"); lPeerManagerObject.addUInt("clients", peerManager_->clients()); lPeerManagerObject.addUInt("peers_count", lPeers.size()); for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) { // if ((*lPeer)->status() == IPeer::UNDEFINED) continue; json::Value lItem = lArrayObject.newArrayItem(); lItem.toObject(); // make object if ((*lPeer)->status() == IPeer::BANNED || (*lPeer)->status() == IPeer::POSTPONED) { lItem.addString("endpoint", (*lPeer)->key()); lItem.addString("status", (*lPeer)->statusString()); lItem.addUInt("in_queue", (*lPeer)->inQueueLength()); lItem.addUInt("out_queue", (*lPeer)->outQueueLength()); lItem.addUInt("pending_queue", (*lPeer)->pendingQueueLength()); lItem.addUInt("received_count", (*lPeer)->receivedMessagesCount()); lItem.addUInt64("received_bytes", (*lPeer)->bytesReceived()); lItem.addUInt("sent_count", (*lPeer)->sentMessagesCount()); lItem.addUInt64("sent_bytes", (*lPeer)->bytesSent()); continue; } lItem.addString("id", (*lPeer)->addressId().toHex()); lItem.addString("endpoint", (*lPeer)->key()); lItem.addString("status", (*lPeer)->statusString()); lItem.addUInt64("time", (*lPeer)->time()); lItem.addBool("outbound", (*lPeer)->isOutbound() ? true : false); lItem.addUInt("latency", (*lPeer)->latency()); lItem.addString("roles", (*lPeer)->state()->rolesString()); if ((*lPeer)->state()->address().valid()) lItem.addString("address", (*lPeer)->state()->address().toString()); lItem.addUInt("in_queue", (*lPeer)->inQueueLength()); lItem.addUInt("out_queue", (*lPeer)->outQueueLength()); lItem.addUInt("pending_queue", (*lPeer)->pendingQueueLength()); lItem.addUInt("received_count", (*lPeer)->receivedMessagesCount()); lItem.addUInt64("received_bytes", (*lPeer)->bytesReceived()); lItem.addUInt("sent_count", (*lPeer)->sentMessagesCount()); lItem.addUInt64("sent_bytes", (*lPeer)->bytesSent()); if ((*lPeer)->state()->client()) { // json::Value lDAppsArray = lItem.addArray("dapps"); for(std::vector<State::DAppInstance>::const_iterator lInstance = (*lPeer)->state()->dApps().begin(); lInstance != (*lPeer)->state()->dApps().end(); lInstance++) { json::Value lDApp = lDAppsArray.newArrayItem(); lDApp.addString("name", lInstance->name()); lDApp.addString("instance", lInstance->instance().toHex()); } } else { // json::Value lChainsObject = lItem.addArray("chains"); std::vector<State::BlockInfo> lInfos = (*lPeer)->state()->infos(); for (std::vector<State::BlockInfo>::iterator lInfo = lInfos.begin(); lInfo != lInfos.end(); lInfo++) { // json::Value lChain = lChainsObject.newArrayItem(); lChain.toObject(); // make object lChain.addString("dapp", lInfo->dApp().size() ? lInfo->dApp() : "none"); lChain.addUInt64("height", lInfo->height()); lChain.addString("chain", lInfo->chain().toHex()); lChain.addString("block", lInfo->hash().toHex()); } } } //lReply.addString("result", strprintf(QBIT_FORMAT, lBalance)); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateDApp::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createdapp", "params": [ "<address>", -- (string) owners' address "<short_name>", -- (string) dapp short name, should be unique "<description>", -- (string) dapp description "<instances_tx>", -- (short) dapp instances tx types (transaction::type) "<sharding>" -- (string, optional) static|dynamic, default = 'static' ] } */ /* reply { "result": "<tx_dapp_id>", -- (string) txid = dapp_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 std::string lShortName; // 1 std::string lDescription; // 2 Transaction::Type lInstances; // 3 std::string lSharding = "static"; // 4 if (lParams.size() == 4 || lParams.size() == 5) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lShortName = lP1.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) lDescription = lP2.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[3] json::Value lP3 = lParams[3]; if (lP3.isString()) { unsigned short lValue; if (!convert<unsigned short>(lP3.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lInstances = (Transaction::Type)lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[4] if (lParams.size() == 5) { json::Value lP4 = lParams[4]; if (lP4.isString()) lSharding = lP4.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxDApp(lAddress, lShortName, lDescription, (lSharding == "static" ? TxDApp::STATIC : TxDApp::DYNAMIC), lInstances); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_DAPP", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateShard::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createshard", "params": [ "<address>", -- (string) creators' address (not owner) "<dapp_name>", -- (string) dapp name "<short_name>", -- (string) shard short name, should be unique "<description>" -- (string) shard description ] } */ /* reply { "result": "<tx_shard_id>", -- (string) txid = shard_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 std::string lDAppName; // 1 std::string lShortName; // 2 std::string lDescription; // 3 if (lParams.size() == 4) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lDAppName = lP1.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) lShortName = lP2.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[3] json::Value lP3 = lParams[3]; if (lP3.isString()) lDescription = lP3.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxShard(lAddress, lDAppName, lShortName, lDescription); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_SHARD", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetTransaction::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "gettransaction", "params": [ "<tx_id>" -- (string) tx hash (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) tx hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "type": "<tx_type>", -- (string) tx type: COINBASE, SPEND, SPEND_PRIVATE & etc. "version": <version>, -- (int) version (0-256) "timelock: <lock_time>, -- (int64) lock time (future block) "block": "<block_id>", -- (string) block hash (id), optional "height": <height>, -- (int64) block height, optional "index": <index>, -- (int) tx block index "mempool": false|true, -- (bool) mempool presence, optional "properties": { ... -- (object) tx type-specific properties }, "in": [ { "chain": "<chain_id>", -- (string) source chain/shard hash (id) "asset": "<asset_id>", -- (string) source asset hash (id) "tx": "<tx_id>", -- (string) source tx hash (id) "index": <index>, -- (int) source tx out index "ownership": { "raw": "<hex>", -- (string) ownership script (hex) "qasm": [ -- (array, string) ownership script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ], "out": [ { "asset": "<asset_id>", -- (string) destination asset hash (id) "destination": { "raw": "<hex>", -- (string) destination script (hex) "qasm": [ -- (array, string) destination script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lTxId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lTxId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process TransactionPtr lTx; std::string lCode, lMessage; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager(); if (lStoreManager && lMempoolManager) { // uint256 lBlock; uint64_t lHeight = 0; uint64_t lConfirms = 0; uint32_t lIndex = 0; bool lCoinbase = false; bool lMempool = false; std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages(); for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) { lTx = (*lStore)->locateTransaction(lTxId); if (lTx && (*lStore)->transactionInfo(lTxId, lBlock, lHeight, lConfirms, lIndex, lCoinbase)) { break; } } // try mempool if (!lTx) { std::vector<IMemoryPoolPtr> lMempools = lMempoolManager->pools(); for (std::vector<IMemoryPoolPtr>::iterator lPool = lMempools.begin(); lPool != lMempools.end(); lPool++) { lTx = (*lPool)->locateTransaction(lTxId); if (lTx) { lMempool = true; break; } } } if (lTx) { // if (!unpackTransaction(lTx, lBlock, lHeight, lConfirms, lIndex, lCoinbase, lMempool, lReply, reply)) return; } else { reply = HttpReply::stockReply("E_TX_NOT_FOUND", "Transaction not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Transactions store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetEntity::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getentity", "params": [ "<entity_name>" -- (string) entity name ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) tx hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "type": "<tx_type>", -- (string) tx type: COINBASE, SPEND, SPEND_PRIVATE & etc. "version": <version>, -- (int) version (0-256) "timelock: <lock_time>, -- (int64) lock time (future block) "block": "<block_id>", -- (string) block hash (id), optional "height": <height>, -- (int64) block height, optional "index": <index>, -- (int) tx block index "mempool": false|true, -- (bool) mempool presence, optional "properties": { ... -- (object) tx type-specific properties }, "in": [ { "chain": "<chain_id>", -- (string) source chain/shard hash (id) "asset": "<asset_id>", -- (string) source asset hash (id) "tx": "<tx_id>", -- (string) source tx hash (id) "index": <index>, -- (int) source tx out index "ownership": { "raw": "<hex>", -- (string) ownership script (hex) "qasm": [ -- (array, string) ownership script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ], "out": [ { "asset": "<asset_id>", -- (string) destination asset hash (id) "destination": { "raw": "<hex>", -- (string) destination script (hex) "qasm": [ -- (array, string) destination script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lName; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lName = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process TransactionPtr lTx; std::string lCode, lMessage; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager(); if (lStoreManager && lMempoolManager) { // uint256 lBlock; uint64_t lHeight = 0; uint64_t lConfirms = 0; uint32_t lIndex = 0; bool lCoinbase = false; bool lMempool = false; ITransactionStorePtr lStorage = lStoreManager->locate(MainChain::id()); EntityPtr lTx = lStorage->entityStore()->locateEntity(lName); // try mempool if (!lTx) { IMemoryPoolPtr lMainpool = lMempoolManager->locate(MainChain::id()); lTx = lMainpool->locateEntity(lName); if (lTx) { lMempool = true; } } else { lStorage->transactionInfo(lTx->id(), lBlock, lHeight, lConfirms, lIndex, lCoinbase); } if (lTx) { // if (!unpackTransaction(lTx, lBlock, lHeight, lConfirms, lIndex, lCoinbase, lMempool, lReply, reply)) return; } else { reply = HttpReply::stockReply("E_TX_NOT_FOUND", "Transaction not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Transactions store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBlock::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getblock", "params": [ "<block_id>" -- (string) block hash (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) block hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "height": <height>, -- (int64) block height "version": <version>, -- (int) version (0-256) "time: <time>, -- (int64) block time "prev": "<prev_id>", -- (string) prev block hash (id) "root": "<merkle_root_hash>", -- (string) merkle root hash "origin": "<miner_id>", -- (string) miner address id "bits": <pow_bits>, -- (int) pow bits "nonce": <nonce_counter>, -- (int) found nonce "pow": [ <int>, <int> ... <int> -- (aray) found pow cycle ], "transactions": [ { "id": "<tx_id>", -- (string) tx hash (id) "size": "<size>" -- (int) tx size } ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lBlockId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lBlockId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process BlockPtr lBlock; std::string lCode, lMessage; // height uint64_t lHeight = 0; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); if (lStoreManager) { // std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages(); for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) { lBlock = (*lStore)->block(lBlockId); if (lBlock) { (*lStore)->blockHeight(lBlockId, lHeight); break; } } if (lBlock) { // json::Value lRootObject = lReply.addObject("result"); lRootObject.addString("id", lBlock->hash().toHex()); lRootObject.addString("chain", lBlock->chain().toHex()); lRootObject.addUInt64("height", lHeight); lRootObject.addInt("version", lBlock->version()); lRootObject.addUInt64("time", lBlock->time()); lRootObject.addString("prev", lBlock->prev().toHex()); lRootObject.addString("root", lBlock->root().toHex()); lRootObject.addString("origin", lBlock->origin().toHex()); lRootObject.addInt("bits", lBlock->bits()); lRootObject.addInt("nonce", lBlock->nonce()); json::Value lPowObject = lRootObject.addArray("pow"); int lIdx = 0; for (std::vector<uint32_t>::iterator lNumber = lBlock->cycle_.begin(); lNumber != lBlock->cycle_.end(); lNumber++, lIdx++) { // json::Value lItem = lPowObject.newArrayItem(); //lItem.toObject(); //lItem.addInt("index", lIdx); //lItem.addUInt("number", *lNumber); lItem.setUInt(*lNumber); } json::Value lTransactionsObject = lRootObject.addArray("transactions"); BlockTransactionsPtr lTransactions = lBlock->blockTransactions(); for (std::vector<TransactionPtr>::iterator lTransaction = lTransactions->transactions().begin(); lTransaction != lTransactions->transactions().end(); lTransaction++) { // json::Value lItem = lTransactionsObject.newArrayItem(); lItem.toObject(); TransactionContextPtr lCtx = TransactionContext::instance(*lTransaction); lItem.addString("id", lCtx->tx()->id().toHex()); lItem.addUInt("size", lCtx->size()); } } else { reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBlockHeader::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getblock", "params": [ "<block_id>" -- (string) block hash (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) block hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "height": <height>, -- (int64) block height "version": <version>, -- (int) version (0-256) "time: <time>, -- (int64) block time "prev": "<prev_id>", -- (string) prev block hash (id) "root": "<merkle_root_hash>", -- (string) merkle root hash "origin": "<miner_id>", -- (string) miner address id "bits": <pow_bits>, -- (int) pow bits "nonce": <nonce_counter>, -- (int) found nonce "pow": [ <int>, <int> ... <int> -- (aray) found pow cycle ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lBlockId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lBlockId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process BlockPtr lBlock; std::string lCode, lMessage; // height uint64_t lHeight = 0; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); if (lStoreManager) { // std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages(); for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) { lBlock = (*lStore)->block(lBlockId); if (lBlock) { (*lStore)->blockHeight(lBlockId, lHeight); break; } } if (lBlock) { // json::Value lRootObject = lReply.addObject("result"); lRootObject.addString("id", lBlock->hash().toHex()); lRootObject.addString("chain", lBlock->chain().toHex()); lRootObject.addUInt64("height", lHeight); lRootObject.addInt("version", lBlock->version()); lRootObject.addUInt64("time", lBlock->time()); lRootObject.addString("prev", lBlock->prev().toHex()); lRootObject.addString("root", lBlock->root().toHex()); lRootObject.addString("origin", lBlock->origin().toHex()); lRootObject.addInt("bits", lBlock->bits()); lRootObject.addInt("nonce", lBlock->nonce()); json::Value lPowObject = lRootObject.addArray("pow"); int lIdx = 0; for (std::vector<uint32_t>::iterator lNumber = lBlock->cycle_.begin(); lNumber != lBlock->cycle_.end(); lNumber++, lIdx++) { // json::Value lItem = lPowObject.newArrayItem(); //lItem.toObject(); //lItem.addInt("index", lIdx); //lItem.addUInt("number", *lNumber); lItem.setUInt(*lNumber); } } else { reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBlockHeaderByHeight::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getblockheaderbyheight", "params": [ "<chain_id>" -- (string) chain (id) "<block_height>" -- (string) block height (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) block hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "height": <height>, -- (int64) block height "version": <version>, -- (int) version (0-256) "time: <time>, -- (int64) block time "prev": "<prev_id>", -- (string) prev block hash (id) "root": "<merkle_root_hash>", -- (string) merkle root hash "origin": "<miner_id>", -- (string) miner address id "bits": <pow_bits>, -- (int) pow bits "nonce": <nonce_counter>, -- (int) found nonce "pow": [ <int>, <int> ... <int> -- (aray) found pow cycle ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lChainId; // 0 uint64_t lBlockHeight = 0; // 1 if (lParams.size() == 2) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lChainId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (!convert<uint64_t>(lP1.getString(), lBlockHeight)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process BlockPtr lBlock; std::string lCode, lMessage; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); if (lStoreManager) { // ITransactionStorePtr lStore = lStoreManager->locate(lChainId); if (!lStore) { reply = HttpReply::stockReply("E_STORE_NOT_FOUND", "Storage not found"); return; } BlockHeader lHeader; if (!lStore->blockHeader(lBlockHeight, lHeader)) { reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block was not found"); return; } // json::Value lRootObject = lReply.addObject("result"); lRootObject.addString("id", lHeader.hash().toHex()); lRootObject.addString("chain", lHeader.chain().toHex()); lRootObject.addUInt64("height", lBlockHeight); lRootObject.addInt("version", lHeader.version()); lRootObject.addUInt64("time", lHeader.time()); lRootObject.addString("prev", lHeader.prev().toHex()); lRootObject.addString("root", lHeader.root().toHex()); lRootObject.addString("origin", lHeader.origin().toHex()); lRootObject.addInt("bits", lHeader.bits()); lRootObject.addInt("nonce", lHeader.nonce()); json::Value lPowObject = lRootObject.addArray("pow"); int lIdx = 0; for (std::vector<uint32_t>::iterator lNumber = lHeader.cycle_.begin(); lNumber != lHeader.cycle_.end(); lNumber++, lIdx++) { // json::Value lItem = lPowObject.newArrayItem(); //lItem.toObject(); //lItem.addInt("index", lIdx); //lItem.addUInt("number", *lNumber); lItem.setUInt(*lNumber); } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateAsset::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createasset", "params": [ "<address>", -- (string) owners' address "<short_name>", -- (string) asset short name, should be unique "<description>", -- (string) asset description "<chunk>", -- (long) asset single chunk "<scale>", -- (long) asset unit scale "<chunks>", -- (long) asset unspend chunks "<type>" -- (string, optional) asset type: limited, unlimited, pegged ] } */ /* reply { "result": "<tx_asset_id>", -- (string) txid = asset_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 std::string lShortName; // 1 std::string lDescription; // 2 amount_t lChunk; // 3 amount_t lScale; // 4 amount_t lChunks; // 5 std::string lType = "limited"; // 6 if (lParams.size() == 6 || lParams.size() == 7) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lShortName = lP1.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) lDescription = lP2.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[3] json::Value lP3 = lParams[3]; if (lP3.isString()) { amount_t lValue; if (!convert<amount_t>(lP3.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lChunk = lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[4] json::Value lP4 = lParams[4]; if (lP4.isString()) { amount_t lValue; if (!convert<amount_t>(lP4.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lScale = lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[5] json::Value lP5 = lParams[5]; if (lP5.isString()) { amount_t lValue; if (!convert<amount_t>(lP5.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lChunks = lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[6] if (lParams.size() == 7) { json::Value lP6 = lParams[6]; if (lP6.isString()) lType = lP6.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxAssetType(lAddress, lShortName, lDescription, lChunk, lScale, lChunks, (lType == "limited" ? TxAssetType::LIMITED : TxAssetType::UNLIMITED)); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_ASSET", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateAssetEmission::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createassetemission", "params": [ "<address>", -- (string) owners' address "<asset>" -- (string) asset id ] } */ /* reply { "result": "<tx_emission_id>", -- (string) txid = emission_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 uint256 lAsset; // 1 if (lParams.size() == 2) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lAsset.setHex(lP1.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxLimitedAssetEmission(lAddress, lAsset); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_ASSET_EMISSION", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetState::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getstate", "params": [] } */ /* reply { "result": { "state": { ... } } }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); json::Value lStateObject = lKeyObject.addObject("state"); // get peers std::list<IPeerPtr> lPeers; peerManager_->allPeers(lPeers); // peer manager lStateObject.addString("version", strprintf("%d.%d.%d.%d", QBIT_VERSION_MAJOR, QBIT_VERSION_MINOR, QBIT_VERSION_REVISION, QBIT_VERSION_BUILD)); lStateObject.addUInt("clients", peerManager_->clients()); lStateObject.addUInt("peers_count", lPeers.size()); uint64_t lInQueue = 0; uint64_t lOutQueue = 0; uint64_t lPendingQueue = 0; uint64_t lReceivedCount = 0; uint64_t lReceivedBytes = 0; uint64_t lSentCount = 0; uint64_t lSentBytes = 0; for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) { // if ((*lPeer)->status() == IPeer::UNDEFINED) continue; // if ((*lPeer)->status() == IPeer::BANNED || (*lPeer)->status() == IPeer::POSTPONED) { // lInQueue += (*lPeer)->inQueueLength(); lOutQueue += (*lPeer)->outQueueLength(); lPendingQueue += (*lPeer)->pendingQueueLength(); lReceivedCount += (*lPeer)->receivedMessagesCount(); lReceivedBytes += (*lPeer)->bytesReceived(); lSentCount += (*lPeer)->sentMessagesCount(); lSentBytes += (*lPeer)->bytesSent(); continue; } lInQueue += (*lPeer)->inQueueLength(); lOutQueue += (*lPeer)->outQueueLength(); lPendingQueue += (*lPeer)->pendingQueueLength(); lReceivedCount += (*lPeer)->receivedMessagesCount(); lReceivedBytes += (*lPeer)->bytesReceived(); lSentCount += (*lPeer)->sentMessagesCount(); lSentBytes += (*lPeer)->bytesSent(); } // lStateObject.addUInt("in_queue", lInQueue); lStateObject.addUInt("out_queue", lOutQueue); lStateObject.addUInt("pending_queue", lPendingQueue); lStateObject.addUInt("received_count", lReceivedCount); lStateObject.addUInt64("received_bytes", lReceivedBytes); lStateObject.addUInt("sent_count", lSentCount); lStateObject.addUInt64("sent_bytes", lSentBytes); // StatePtr lState = peerManager_->consensusManager()->currentState(); // json::Value lChainsObject = lStateObject.addArray("chains"); std::vector<State::BlockInfo> lInfos = lState->infos(); for (std::vector<State::BlockInfo>::iterator lInfo = lInfos.begin(); lInfo != lInfos.end(); lInfo++) { // json::Value lChain = lChainsObject.newArrayItem(); lChain.toObject(); // make object // get mempool IMemoryPoolPtr lMempool = peerManager_->memoryPoolManager()->locate(lInfo->chain()); if (lMempool) { // json::Value lMempoolObject = lChain.addObject("mempool"); size_t lTx = 0, lCandidatesTx = 0, lPostponedTx = 0; lMempool->statistics(lTx, lCandidatesTx, lPostponedTx); lMempoolObject.addUInt64("txs", lTx); lMempoolObject.addUInt64("candidates", lCandidatesTx); lMempoolObject.addUInt64("postponed", lPostponedTx); } // get consensus IConsensusPtr lConsensus = peerManager_->consensusManager()->locate(lInfo->chain()); lChain.addString("dapp", lInfo->dApp().size() ? lInfo->dApp() : "none"); lChain.addUInt64("height", lInfo->height()); lChain.addString("chain", lInfo->chain().toHex()); lChain.addString("block", lInfo->hash().toHex()); if (lConsensus) { lChain.addUInt64("time", lConsensus->currentTime()); lChain.addString("state", lConsensus->chainStateString()); } // sync job IConsensus::ChainState lState = lConsensus->chainState(); if (lState == IConsensus::SYNCHRONIZING) { SynchronizationJobPtr lJob = nullptr; for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) { // if ((*lPeer)->status() == IPeer::ACTIVE) { // SynchronizationJobPtr lNewJob = (*lPeer)->locateJob(lInfo->chain()); if (!lJob) lJob = lNewJob; else if (lNewJob && lJob && lJob->timestamp() < lNewJob->timestamp()) { lJob = lNewJob; } } } if (lJob) { json::Value lSyncObject = lChain.addObject("synchronization"); lSyncObject.addString("type", lJob->typeString()); if (lJob->type() != SynchronizationJob::PARTIAL) lSyncObject.addUInt64("remains", lJob->pendingBlocks()); } } } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpReleasePeer::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "releasepeer", "params": [ "<peer_address>" -- (string) peer IP address ] } */ /* reply { "result": "<peer_address>", -- (string) peer IP address "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lAddress; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); peerManager_->release(lAddress); lReply.addString("result", lAddress); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetEntitiesCount::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getentitiescount", "params": [ "<dapp_name>" -- (string, required) dapp name ] } */ /* reply { "result": -- (object) details { ... }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lDApp; // 0 if (lParams.size()) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lDApp = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // json::Document lReply; lReply.loadFromString("{}"); json::Value lRootObject = lReply.addObject("result"); json::Value lDAppObject = lRootObject.addArray(lDApp); // std::map<uint256, uint32_t> lShardInfo; ITransactionStorePtr lStorage = peerManager_->consensusManager()->storeManager()->locate(MainChain::id()); // std::vector<ISelectEntityCountByShardsHandler::EntitiesCount> lEntitiesCount; if (lStorage->entityStore()->entityCountByDApp(lDApp, lShardInfo)) { for (std::map<uint256, uint32_t>::iterator lItem = lShardInfo.begin(); lItem != lShardInfo.end(); lItem++) { // json::Value lDAppItem = lDAppObject.newArrayItem(); lDAppItem.toObject(); lDAppItem.addString("shard", lItem->first.toHex()); lDAppItem.addUInt("count", lItem->second); } } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetUnconfirmedTransactions::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getunconfirmedtxs", "params": [ "<chain_id>" -- (string) chain hash (id) ] } */ /* reply { "result": { "txs": [ "...", "..." ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lChainId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lChainId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lResultObject = lReply.addObject("result"); json::Value lTxsArrayObject = lResultObject.addArray("txs"); // process std::string lCode, lMessage; // try to lookup transaction IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager(); if (lMempoolManager) { // IMemoryPoolPtr lMempool = lMempoolManager->locate(lChainId); // if (lMempool) { // uint64_t lTotal = 0; std::list<uint256> lTxs; lMempool->selectTransactions(lTxs, lTotal, 10000 /*max*/); lResultObject.addUInt64("total", lTotal); // for (std::list<uint256>::iterator lTx = lTxs.begin(); lTx != lTxs.end(); lTx++) { // json::Value lItem = lTxsArrayObject.newArrayItem(); lItem.setString(lTx->toHex()); } } else { reply = HttpReply::stockReply("E_MEMPOOL_NOT_FOUND", "Memory pool was not found"); return; } } else { reply = HttpReply::stockReply("E_POOLMANAGER", "Pool manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } }
29.487834
171
0.627141
qbit-t
9734163529bf58d4bd81ddf95bf6f89ab05f743b
1,032
cpp
C++
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
/* A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The number of ways decoding "12" is 2. */ // https://stackoverflow.com/questions/20342462/review-an-answer-decode-ways // https://www.youtube.com/watch?v=aCKyFYF9_Bg // Solution from http://bangbingsyb.blogspot.com/2014/11/leetcode-decode-ways.html int numDecodings(string s) { if(s.empty() || s[0]<'1' || s[0]>'9') return 0; vector<int> dp(s.size()+1,0); dp[0] = dp[1] = 1; // dp[i] is the number of ways to decode str[0:i] for(int i=1; i<s.size(); i++) { if(!isdigit(s[i])) return 0; int v = (s[i-1]-'0')*10 + (s[i]-'0'); if(v<=26 && v>9) dp[i+1] += dp[i-1]; if(s[i]!='0') dp[i+1] += dp[i]; if(dp[i+1]==0) return 0; } return dp[s.size()]; }
32.25
97
0.592054
animeshramesh
9734922a52146c96dae481fb1d6da9230ee6ff94
1,810
cpp
C++
libraries/physics/src/ContactConstraint.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
libraries/physics/src/ContactConstraint.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
libraries/physics/src/ContactConstraint.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
// // ContactConstraint.cpp // libraries/physcis/src // // Created by Andrew Meadows 2014.07.24 // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <SharedUtil.h> #include "ContactConstraint.h" #include "VerletPoint.h" ContactConstraint::ContactConstraint(VerletPoint* pointA, VerletPoint* pointB) : _pointA(pointA), _pointB(pointB), _strength(1.0f) { assert(_pointA != NULL && _pointB != NULL); _offset = _pointB->_position - _pointA->_position; } float ContactConstraint::enforce() { _pointB->_position += _strength * (_pointA->_position + _offset - _pointB->_position); return 0.0f; } float ContactConstraint::enforceWithNormal(const glm::vec3& normal) { glm::vec3 delta = _pointA->_position + _offset - _pointB->_position; // split delta into parallel (pDelta) and perpendicular (qDelta) components glm::vec3 pDelta = glm::dot(delta, normal) * normal; glm::vec3 qDelta = delta - pDelta; // use the relative sizes of the components to decide how much perpenducular delta to use // (i.e. dynamic friction) float lpDelta = glm::length(pDelta); float lqDelta = glm::length(qDelta); float qFactor = lqDelta > lpDelta ? (lpDelta / lqDelta - 1.0f) : 0.0f; // recombine the two components to get the final delta delta = pDelta + qFactor * qDelta; // attenuate strength by how much _offset is perpendicular to normal float distance = glm::length(_offset); float strength = _strength * ((distance > EPSILON) ? glm::abs(glm::dot(_offset, normal)) / distance : 1.0f); // move _pointB _pointB->_position += strength * delta; return strength * glm::length(delta); }
33.518519
112
0.692265
ey6es
9734eb840112ee3d67af26b01b7786ba873b5526
2,839
hpp
C++
include/boost/http_proto/detail/copied_strings.hpp
alandefreitas/http_proto
dc64cbdd44048a2c06671282b736f7edacb39a42
[ "BSL-1.0" ]
6
2021-11-17T03:23:50.000Z
2021-11-25T15:58:02.000Z
include/boost/http_proto/detail/copied_strings.hpp
alandefreitas/http_proto
dc64cbdd44048a2c06671282b736f7edacb39a42
[ "BSL-1.0" ]
6
2021-11-17T16:13:52.000Z
2022-01-31T04:17:47.000Z
include/boost/http_proto/detail/copied_strings.hpp
samd2/http_proto
486729f1a68b7611f143e18c7bae8df9b908e9aa
[ "BSL-1.0" ]
3
2021-11-17T03:01:12.000Z
2021-11-17T14:14:45.000Z
// // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/CPPAlliance/http_proto // #ifndef BOOST_HTTP_PROTO_DETAIL_COPIED_STRINGS_HPP #define BOOST_HTTP_PROTO_DETAIL_COPIED_STRINGS_HPP #include <boost/http_proto/string_view.hpp> #include <functional> namespace boost { namespace http_proto { namespace detail { // Makes copies of string_view parameters as // needed when the storage for the parameters // overlap the container being modified. class basic_copied_strings { struct dynamic_buf { dynamic_buf* next; }; string_view s_; char* local_buf_; std::size_t local_remain_; dynamic_buf* dynamic_list_ = nullptr; bool is_overlapping( string_view s) const noexcept { auto const b1 = s_.data(); auto const e1 = b1 + s_.size(); auto const b2 = s.data(); auto const e2 = b2 + s.size(); auto const less_equal = std::less_equal<char const*>(); if(less_equal(e1, b2)) return false; if(less_equal(e2, b1)) return false; return true; } public: ~basic_copied_strings() { while(dynamic_list_) { auto p = dynamic_list_; dynamic_list_ = dynamic_list_->next; delete[] p; } } basic_copied_strings( string_view s, char* local_buf, std::size_t local_size) noexcept : s_(s) , local_buf_(local_buf) , local_remain_(local_size) { } string_view maybe_copy( string_view s) { if(! is_overlapping(s)) return s; if(local_remain_ >= s.size()) { std::memcpy(local_buf_, s.data(), s.size()); s = string_view( local_buf_, s.size()); local_buf_ += s.size(); local_remain_ -= s.size(); return s; } auto const n = sizeof(dynamic_buf); auto p = new dynamic_buf[1 + sizeof(n) * ((s.size() + sizeof(n) - 1) / sizeof(n))]; std::memcpy(p + 1, s.data(), s.size()); s = string_view(reinterpret_cast< char const*>(p + 1), s.size()); p->next = dynamic_list_; dynamic_list_ = p; return s; } }; class copied_strings : public basic_copied_strings { char buf_[4096]; public: copied_strings( string_view s) : basic_copied_strings( s, buf_, sizeof(buf_)) { } }; } // detail } // http_proto } // boost #endif
22.712
79
0.559352
alandefreitas
97384c308cf5a7f11846cde620d00a08f7c3b3c2
536
cpp
C++
ALP/sequencia/L01_ex01.cpp
khrystie/fatec_ads
a5fec2c612943342f731a46814d4f6df67eb692f
[ "MIT" ]
null
null
null
ALP/sequencia/L01_ex01.cpp
khrystie/fatec_ads
a5fec2c612943342f731a46814d4f6df67eb692f
[ "MIT" ]
null
null
null
ALP/sequencia/L01_ex01.cpp
khrystie/fatec_ads
a5fec2c612943342f731a46814d4f6df67eb692f
[ "MIT" ]
null
null
null
/* Exercício: Faça um algoritmo que receba 2 números inteiros e apresente a soma desses números. */ #include <iostream> int main() { //declaração de variáveis int num1, num2; // atribuir valor 0 num1=0; num2=0; std::cout << "Programa que lê dois números inteiros e retorna o valor da soma\n"; std::cout <<"Digite o primeiro número inteiro: \n"; std::cin >> num1; std::cout <<"Digite o segundo número inteiro: \n"; std::cin >> num2; std::cout <<"A soma dos dois números inteiros é: \n" <<num1+num2; }
22.333333
95
0.652985
khrystie
9738b40e93cc34db346f6f331cea0a1ca13bae6d
372
cp
C++
Lin/Mod/X11.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
2
2016-03-17T08:27:55.000Z
2020-05-02T08:42:08.000Z
Lin/Mod/X11.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
null
null
null
Lin/Mod/X11.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
null
null
null
MODULE LinX11 ["libX11.so"]; IMPORT LinLibc; TYPE Display* = INTEGER; PROCEDURE XFreeFontNames* (list: LinLibc.StrArray); PROCEDURE XListFonts* (display: Display; pattern: LinLibc.PtrSTR; maxnames: INTEGER; VAR actual_count_return: INTEGER): LinLibc.StrArray; PROCEDURE XOpenDisplay* (VAR [nil] display_name: LinLibc.PtrSTR): Display; END LinX11.
26.571429
86
0.733871
romiras
9738eda77042cec54309a95c28906a00687bea7c
8,818
cpp
C++
Classes/Helpers/AnimationHelper.cpp
funkyzooink/fresh-engine
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
[ "MIT" ]
3
2019-10-09T09:17:49.000Z
2022-03-02T17:57:05.000Z
Classes/Helpers/AnimationHelper.cpp
funkyzooink/fresh-engine
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
[ "MIT" ]
33
2019-10-08T18:45:48.000Z
2022-01-05T21:53:02.000Z
Classes/Helpers/AnimationHelper.cpp
funkyzooink/fresh-engine
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
[ "MIT" ]
7
2019-10-10T11:31:58.000Z
2021-02-08T14:24:30.000Z
/**************************************************************************** Copyright (c) 2014-2019 Gabriel Heilig fresh-engine funkyzooink@gmail.com ****************************************************************************/ #include "AnimationHelper.h" #include "../GameData/Constants.h" #include "../GameData/GameConfig.h" #include "../GameData/Gamedata.h" #include "cocos2d.h" // MARK: Animation Helper void AnimationHelper::levelinfoFadeInAnimation(cocos2d::Node* node1, cocos2d::Node* node2) { auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); switch (GAMECONFIG.getLevelInfoPopupType()) { case 1: { node1->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create( 1.0F, cocos2d::Vec2(visibleSize.width / 2 - CONSTANTS.getOffset() * 2, node1->getPosition().y)), nullptr)); node2->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.0F, cocos2d::Vec2(visibleSize.width / 2 - node2->getContentSize().width / 2, node2->getPosition().y)), nullptr)); break; } default: { auto position = node1->getPosition(); node1->setPosition(position.x, visibleSize.height); node2->setVisible(true); node1->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(1.0F, position), nullptr)); break; } } } void AnimationHelper::levelInfoFadeOutAnimation(cocos2d::Node* node1, cocos2d::Node* node2) { auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); switch (GAMECONFIG.getLevelInfoPopupType()) { case 1: { node1->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.0F, cocos2d::Vec2(visibleSize.width, node1->getPosition().y)), nullptr)); node2->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.5F, cocos2d::Vec2(-visibleSize.width, node2->getPosition().y)), nullptr)); break; } default: { node2->setVisible(true); node1->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.5F, cocos2d::Vec2(node1->getPosition().x, -visibleSize.height)), nullptr)); break; } } } void AnimationHelper::fadeIn(cocos2d::Node* from, cocos2d::Node* to) { auto duration = 0.8F; auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); if (to != nullptr) { to->setVisible(true); // make sure both nodes are visible auto toPosition = cocos2d::Vec2(to->getPosition().x, 0.0); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { to->setPosition(toPosition.x, visibleSize.height); to->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, toPosition), nullptr)); break; } default: { to->setPosition(toPosition); break; } } } if (from != nullptr) { from->setVisible(true); // make sure both nodes are visible auto fromPosition = cocos2d::Vec2(from->getPosition().x, -visibleSize.height); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { from->setPosition(0.0, 0.0); from->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, fromPosition), nullptr)); break; } default: { from->setPosition(fromPosition); break; } } } } void AnimationHelper::fadeOut(cocos2d::Node* from, cocos2d::Node* to) { auto duration = 0.8F; auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); if (to != nullptr) { to->setVisible(true); // make sure both nodes are visible auto toPosition = cocos2d::Vec2(to->getPosition().x, 0.0F); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { to->setPosition(toPosition.x, -visibleSize.height); to->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, toPosition), nullptr)); break; } default: { to->setPosition(toPosition); break; } } } if (from != nullptr) { from->setVisible(true); // make sure both nodes are visible auto fromPosition = cocos2d::Vec2(from->getPosition().x, visibleSize.height); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { from->setPosition(0.0, 0.0); from->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, fromPosition), nullptr)); break; } default: { from->setPosition(fromPosition); break; } } } } cocos2d::TransitionScene* AnimationHelper::sceneTransition(cocos2d::Scene* scene) { return cocos2d::TransitionFade::create(0.2f, scene); } cocos2d::FiniteTimeAction* AnimationHelper::blinkAnimation() { float blinkDuration = 0.05F; return cocos2d::Sequence::create(cocos2d::FadeOut::create(blinkDuration), cocos2d::FadeIn::create(blinkDuration), cocos2d::FadeOut::create(blinkDuration), cocos2d::FadeIn::create(blinkDuration), nullptr); } cocos2d::Action* AnimationHelper::getActionForTag(const std::string& tag) { auto animationCache = cocos2d::AnimationCache::getInstance()->getAnimation(tag); if (animationCache == nullptr) { return nullptr; } auto animation = cocos2d::Animate::create(animationCache); auto repeatForever = cocos2d::RepeatForever::create(animation); return repeatForever; } std::map<AnimationHelper::AnimationTagEnum, std::string> AnimationHelper::initAnimations( const std::string& type, const std::map<std::string, std::vector<std::string>>& animationMap) { std::map<AnimationHelper::AnimationTagEnum, std::string> _animationEnumMap; _animationEnumMap[AnimationHelper::AnimationTagEnum::ATTACK_LEFT_ANIMATION] = type + "_attack_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::FALL_LEFT_ANIMATION] = type + "_jump_left_down"; _animationEnumMap[AnimationHelper::AnimationTagEnum::HIT_LEFT_ANIMATION] = type + "_hit_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::IDLE_LEFT_ANIMATION] = type + "_idle_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::JUMP_LEFT_ANIMATION] = type + "_jump_left_up"; _animationEnumMap[AnimationHelper::AnimationTagEnum::WALK_LEFT_ANIMATION] = type + "_walk_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::ATTACK_RIGHT_ANIMATION] = type + "_attack_right"; _animationEnumMap[AnimationHelper::AnimationTagEnum::FALL_RIGHT_ANIMATION] = type + "_jump_right_down"; _animationEnumMap[AnimationHelper::AnimationTagEnum::HIT_RIGHT_ANIMATION] = type + "_hit_right"; _animationEnumMap[AnimationHelper::AnimationTagEnum::IDLE_RIGHT_ANIMATION] = type + "_idle_right"; _animationEnumMap[AnimationHelper::AnimationTagEnum::JUMP_RIGHT_ANIMATION] = type + "_jump_right_up"; _animationEnumMap[AnimationHelper::AnimationTagEnum::WALK_RIGHT_ANIMATION] = type + "_walk_right"; cocos2d::Animation* animation = nullptr; for (auto const& entry : animationMap) { auto animationTag = type + "_" + entry.first; // TODO this needs to be the same as in animationEnumMap // TODO check if created tag is part of animationEnum otherwise abort animation = prepareVector(entry.second, 0.2F); // check times! 0.5 for staticshooter idle // check times! 0.2 for jumps falls and walking animation cocos2d::AnimationCache::getInstance()->addAnimation(animation, animationTag); } return _animationEnumMap; } cocos2d::Animation* AnimationHelper::prepareVector(const std::vector<std::string>& filenames, float duration) { cocos2d::Vector<cocos2d::SpriteFrame*> spriteVector(filenames.size()); for (const std::string& file : filenames) { cocos2d::SpriteFrame* spriteFrame = cocos2d::SpriteFrameCache::getInstance()->getSpriteFrameByName(file); spriteVector.pushBack(spriteFrame); } cocos2d::Animation* animation = cocos2d::Animation::createWithSpriteFrames(spriteVector, duration, 1); return animation; };
37.683761
118
0.612611
funkyzooink
973c113401f4674b562d4ebf3724e179531270e7
185
cpp
C++
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#include "expression07_grammar_def.hpp" #include "iterator_typedefs.hpp" namespace stan { namespace lang { template struct expression07_grammar<pos_iterator_t>; } } // namespace stan
20.555556
53
0.8
alashworth
973c1d1aef3085b665141d6b9dfc1f5600ed76b1
838
cpp
C++
Classes/Device.cpp
Tang1705/Happy-Reconstruction
2040310be4475deff0a8d251feaf32d7ba82d0ff
[ "Apache-2.0" ]
5
2021-12-13T08:48:07.000Z
2022-01-04T01:28:40.000Z
Classes/Device.cpp
xmtc56606/Reconstruction
7eadf91b397fa2067b983be1a31c9603043d1360
[ "Apache-2.0" ]
null
null
null
Classes/Device.cpp
xmtc56606/Reconstruction
7eadf91b397fa2067b983be1a31c9603043d1360
[ "Apache-2.0" ]
1
2022-03-28T06:04:34.000Z
2022-03-28T06:04:34.000Z
#include "Device.h" #include <QDebug> Device* Device::instance = nullptr; Device::Device() { vector<CameraInfo> cams = CameraPointGrey::getCameraList(); if (cams.size() != 0) { hasCamera = true; camera = Camera::NewCamera(0, cams[0].busID, triggerModeSoftware); CameraSettings camSettings; camSettings.shutter = 25; camSettings.gain = 0.0; camera->setCameraSettings(camSettings); camera->startCapture(); } projector = new ProjectorLC4500(0); if (projector->getIsRunning())hasProjector = true; } Device* Device::getInstance() { if (instance == nullptr) instance = new Device(); return instance; } Camera* Device::getCamera() { return camera; } Projector* Device::getProjector() { return projector; } bool Device::getHasCamera() { return hasCamera; } bool Device::getHasProjector() { return hasProjector; }
17.458333
68
0.711217
Tang1705
973fe8eaa908632171eb72d68bcb6ed1e1b0ba35
4,253
cpp
C++
test/cfgTest.cpp
arminnh/Machines-and-Computability-project
7e7be2541074ca8a177335aaad1b09394145fcf6
[ "MIT" ]
null
null
null
test/cfgTest.cpp
arminnh/Machines-and-Computability-project
7e7be2541074ca8a177335aaad1b09394145fcf6
[ "MIT" ]
null
null
null
test/cfgTest.cpp
arminnh/Machines-and-Computability-project
7e7be2541074ca8a177335aaad1b09394145fcf6
[ "MIT" ]
1
2017-01-30T19:16:19.000Z
2017-01-30T19:16:19.000Z
/* * * File Name : * * Creation Date : 21-01-2015 * Last Modified : do 22 jan 12:34:27 2015 * Created By : Bruno De Deken * */ #include "comparefiles.h" #include <string> #include <set> #include <gtest/gtest.h> #include <UTM/util.h> #include <UTM/dot.h> #include <UTM/finiteautomaton.h> #include <UTM/CFG.h> #include <UTM/CFGParser.h> #include <UTM/CFG2CNF.h> /** CFG TESTS **/ class CFGTest : public ::testing::Test { protected: CFG cfg; virtual void SetUp() { CFGParser parser("./data/cfg1Test.xml"); cfg = CFG(parser.getVariables(), parser.getTerminals(), parser.getProductionRules(), parser.getStartSymbol(), parser.getName()); } }; TEST_F(CFGTest, parser) { std::set<Symbol> vars{cfg.getVariables()}; EXPECT_EQ(vars.size(), 1); EXPECT_EQ(vars.begin()->getValue(), "P"); std::set<Symbol> ters{cfg.getTerminals()}; EXPECT_EQ(ters.size(), 2); auto it = ters.begin(); EXPECT_EQ(it->getValue(), "0"); ++it; EXPECT_EQ(it->getValue(), "1"); EXPECT_EQ(cfg.getRules().at(0).first.getValue(), "P"); EXPECT_EQ(cfg.getRules().at(0).second.size(), 3); EXPECT_EQ(cfg.getRules().at(0).second.at(0).getValue(), "0"); EXPECT_EQ(cfg.getRules().at(0).second.at(1).getValue(), "P"); EXPECT_EQ(cfg.getRules().at(0).second.at(2).getValue(), "0"); EXPECT_EQ(cfg.getRules().at(1).first.getValue(), "P"); EXPECT_EQ(cfg.getRules().at(1).second.size(), 3); EXPECT_EQ(cfg.getRules().at(1).second.at(0).getValue(), "1"); EXPECT_EQ(cfg.getRules().at(1).second.at(1).getValue(), "P"); EXPECT_EQ(cfg.getRules().at(1).second.at(2).getValue(), "1"); } TEST_F(CFGTest, checks) { EXPECT_TRUE(cfg.isConsistent()); EXPECT_FALSE(cfg.isDefinedSymbol(Symbol{"X", true})); EXPECT_FALSE(cfg.isDefinedSymbol(Symbol{"P", true})); EXPECT_TRUE(cfg.isDefinedSymbol(Symbol{"P", false})); EXPECT_FALSE(cfg.isDefinedSymbol(Symbol{"0", false})); EXPECT_TRUE(cfg.isDefinedSymbol(Symbol{"0", true})); EXPECT_TRUE(cfg.isDefinedSymbol(Symbol{"1", true})); EXPECT_FALSE(cfg.isDefinedVariable(Symbol{"T", false})); EXPECT_FALSE(cfg.isDefinedVariable(Symbol{"P", true})); EXPECT_TRUE(cfg.isDefinedVariable(Symbol{"P", false})); EXPECT_FALSE(cfg.isDefinedTerminal(Symbol{"P", false})); EXPECT_FALSE(cfg.isDefinedTerminal(Symbol{"0", false})); EXPECT_TRUE(cfg.isDefinedTerminal(Symbol{"0", true})); auto rule = *cfg.getRules().begin(); EXPECT_TRUE(cfg.isDefinedRule(rule)); rule.first = Symbol{"X", true}; EXPECT_FALSE(cfg.isDefinedRule(rule)); EXPECT_FALSE(cfg.isUsedWithinProduction(Symbol{"P", true})); EXPECT_FALSE(cfg.isUsedWithinProduction(Symbol{"0", false})); EXPECT_TRUE(cfg.isUsedWithinProduction(Symbol{"P", false})); EXPECT_TRUE(cfg.isUsedWithinProduction(Symbol{"1", true})); } TEST_F(CFGTest, methodBasics) { auto r = *cfg.getRules().begin(); auto r2 = cfg.useRule(r.second, 1, 1); EXPECT_EQ(r.second, (std::vector<Symbol>{Symbol{"0", true}, Symbol{"P", false}, Symbol{"0", true}})); EXPECT_EQ(r2, (std::vector<Symbol>{Symbol{"0", true}, Symbol{"0", true}, Symbol{"P", false}, Symbol{"0", true}, Symbol{"0", true}})); std::vector< std::pair <int, int > > rulesToUse { std::make_pair(1, 1), std::make_pair(1, 1), std::make_pair(2, 1)}; EXPECT_EQ(cfg.useRules(rulesToUse), "001P100"); } TEST_F(CFGTest, automaton) { FiniteAutomaton* fa = new FiniteAutomaton(cfg.generatePDA()); writeDotFile(fa, "result.dot"); EXPECT_TRUE(compareFiles("result.dot", "./data/expected.dot")); delete fa; } TEST_F(CFGTest, result){ CFG2CNF converter; cfg = converter(cfg); EXPECT_TRUE(cfg.isMember(std::string{"00010001000"})); EXPECT_TRUE(cfg.isMember(std::string{"00"})); EXPECT_FALSE(cfg.isMember(std::string{""})); //Empty string never alowed. EXPECT_FALSE(cfg.isMember(std::string{"0010"})); } TEST_F(CFGTest, xmlWriter) { CFGParser parser("./data/cfg1Test.xml"); CFG cfg1 = CFG(parser.getVariables(), parser.getTerminals(), parser.getProductionRules(), parser.getStartSymbol(), parser.getName()); cfg1.generateXML("result.xml"); CFGParser _parser("result.xml"); CFG cfg2 = CFG(_parser.getVariables(), _parser.getTerminals(), _parser.getProductionRules(), _parser.getStartSymbol(), _parser.getName()); EXPECT_EQ(cfg2, cfg1); }
33.226563
140
0.682577
arminnh
9741c086d1b97a36b72febad8eb1f70578664ab7
2,492
cpp
C++
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
2
2015-04-17T11:28:57.000Z
2016-11-13T13:03:08.000Z
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
null
null
null
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
null
null
null
/********************************** * args_test.cpp * **********************************/ #include "args_test.h" #include "args.h" #include "fileman.h" #include <string> using std::string; ArgsTest::ArgsTest() : Test("Args") { const char* files[] = { "Chuck.S05E01.HDTV.XviD-LOL.avi", "Community.S04E02.HDTV.x264-LOL.mp4", "subdir/Chuck.S05E02.HDTV.XviD-LOL.avi", "The.Prestige.2006.720p.Bluray.x264.anoXmous.mp4", }; const int filec = sizeof(files) / sizeof(*files); const string indir = getdir() + "input/"; const string outdir = getdir() + "output/"; { // Prepare workspace Args args; FileMan fileman(args); fileman.remove_all(getdir()); for (int i = 0; i < filec; i++) fileman.touch(indir + files[i]); fileman.dig(outdir); } { // Test 1: minimal char* argv[] = { (char*) "video-organizer", (char*) indir.c_str(), (char*) "--verbosity=-1", // suppress warnings }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, "./"); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::MOVE); EQ(args.verbosity, -1); EQ(args.recursive, false); EQ(args.include_part, false); EQ(args.clean, 0); } { // Test 2: short options char* argv[] = { (char*) "video-organizer", (char*) indir.c_str(), (char*) "-v", (char*) "-1", (char*) "-o", (char*) outdir.c_str(), (char*) "-c", (char*) "-r", (char*) "-p", }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, outdir); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::COPY); EQ(args.verbosity, -1); EQ(args.recursive, true); EQ(args.include_part, true); EQ(args.clean, 0); } { // Test 3: long options string outdirarg = "--outdir=" + outdir; // put on stack char* argv[] = { (char*) "video-organizer", (char*) "--link", (char*) indir.c_str(), (char*) "--verbosity=-1", (char*) outdirarg.c_str(), (char*) "--recursive", (char*) "--part", (char*) "--clean=3M", }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, outdir); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::LINK); EQ(args.verbosity, -1); EQ(args.recursive, true); EQ(args.include_part, true); EQ(args.clean, 3*1024*1024); } }
26.795699
58
0.554575
JoelSjogren
97466246b549d44e5bfbfba129449c424b573d6e
2,501
cpp
C++
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
71
2017-12-18T10:35:41.000Z
2021-12-11T19:57:34.000Z
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
1
2017-12-19T09:31:46.000Z
2017-12-20T07:08:01.000Z
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
7
2017-12-20T01:55:44.000Z
2019-12-06T12:25:55.000Z
#include <gtest/gtest.h> #include <futures/EventExecutor.h> #include <futures/Timeout.h> #include <futures/Timer.h> #include <futures/Future.h> using namespace futures; TEST(Executor, Timer) { EventExecutor ev; auto f = TimerFuture(&ev, 1) .andThen([&ev] (Unit) { std::cerr << "DONE" << std::endl; return makeOk(); }); ev.spawn(std::move(f)); ev.run(); std::cerr << "END" << std::endl; } TEST(Future, Timeout) { EventExecutor ev; auto f = makeEmpty<int>(); auto f1 = timeout(&ev, std::move(f), 1.0) .then([] (Try<int> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; return makeOk(); }); ev.spawn(std::move(f1)); ev.run(); } TEST(Future, AllTimeout) { EventExecutor ev; std::vector<BoxedFuture<int>> f; f.emplace_back(TimerFuture(&ev, 1.0) .then([] (Try<Unit> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; else std::cerr << "Timer1 done" << std::endl; return makeOk(1); }).boxed()); f.emplace_back(TimerFuture(&ev, 2.0) .then([] (Try<Unit> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; else std::cerr << "Timer2 done" << std::endl; return makeOk(2); }).boxed()); auto all = makeWhenAll(f.begin(), f.end()) .andThen([] (std::vector<int> ids) { std::cerr << "done" << std::endl; return makeOk(); }); ev.spawn(std::move(all)); ev.run(); } BoxedFuture<std::vector<int>> rwait(EventExecutor &ev, std::vector<int> &v, int n) { if (n == 0) return makeOk(std::move(v)).boxed(); return TimerFuture(&ev, 0.1) .andThen( [&ev, &v, n] (Unit) { v.push_back(n); return rwait(ev, v, n - 1); }).boxed(); } TEST(Future, RecursiveTimer) { EventExecutor ev; std::vector<int> idxes; auto w10 = rwait(ev, idxes, 10) .andThen([] (std::vector<int> idxes) { for (auto e: idxes) std::cerr << e << std::endl; return makeOk(); }); ev.spawn(std::move(w10)); ev.run(); } TEST(Future, TimerKeeper) { EventExecutor ev; auto timer = std::make_shared<TimerKeeper>(&ev, 1); auto f = [timer, &ev] (double sec) { return delay(&ev, sec) .andThen([timer] (Unit) { return TimerKeeperFuture(timer); }) .then([] (Try<Unit> err) { if (err.hasException()) { std::cerr << "ERR: " << err.exception().what() << std::endl; } else { std::cerr << "Timeout: " << (uint64_t)(EventExecutor::current()->getNow() * 1000.0) << std::endl; } return makeOk(); }); }; ev.spawn(f(0.2)); ev.spawn(f(0.4)); ev.run(); }
21.376068
102
0.580968
chyh1990
974aa1b66be0b4d7e57c440ac9130fdb6c4d7a61
960
cpp
C++
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
1
2021-04-19T12:10:01.000Z
2021-04-19T12:10:01.000Z
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
null
null
null
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
null
null
null
#include "Food.h" void Food::Initilize(Position * position) { this->position = position; drawing = CreateBitmap(position); CollisionDetection::Instance()->Add(this); } Food::Food(int x, int y) { Initilize(new Position(x - FOOD_RADIUS, y - FOOD_RADIUS)); } Food::Food(Position * position) { Initilize(position); } Bitmap * Food::CreateBitmap(Position * position) { #ifdef DEBUG if (position == 0) throw new NullReferenceException("position", "Food::CreateBitmap"); #endif Bitmap * bmp = new Bitmap(2 * FOOD_RADIUS + 1, 2 * FOOD_RADIUS + 1, position->X(), position->Y()); Color * color = new Color(FOOD_COLOR_R, FOOD_COLOR_G, FOOD_COLOR_B); bmp->Clean(); bmp->DrawFilledCircle(FOOD_RADIUS, FOOD_RADIUS, FOOD_RADIUS, color); return bmp; } void Food::WasEaten() { DrawingElement::WasEaten(); Reconstruction::Instance()->FoodEaten(); }
22.857143
106
0.628125
prakashutoledo
974c5c2a8c7403ab4d50628b70c73d0b2bb150e3
2,200
hpp
C++
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
2
2019-11-13T13:57:37.000Z
2019-11-25T09:55:17.000Z
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
#pragma once #include <boxpp/base/BaseMacros.hpp> #include <boxpp/base/BaseTypes.hpp> #include <boxpp/base/opacities/posix.hpp> #include <boxpp/base/opacities/windows.hpp> namespace boxpp { /* Barrior is for guarding specific blocks. */ class BOXPP FBarrior { public: FASTINLINE FBarrior() { #if PLATFORM_WINDOWS w32_compat::InitializeCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_init(&__MUTEX__, nullptr); #endif } FASTINLINE ~FBarrior() { #if PLATFORM_WINDOWS w32_compat::DeleteCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_destroy(&__MUTEX__); #endif } public: /* Enter to behind of barrior. */ FASTINLINE void Enter() const { #if PLATFORM_WINDOWS if (!w32_compat::TryEnterCriticalSection(&__CS__)) w32_compat::EnterCriticalSection(&__CS__); #endif #if PLATFORM_POSIX if (pthread_mutex_trylock(&__MUTEX__)) pthread_mutex_lock(&__MUTEX__); #endif } /* Try enter to behind of barrior. */ FASTINLINE bool TryEnter() const { register bool RetVal = false; #if PLATFORM_WINDOWS RetVal = w32_compat::TryEnterCriticalSection(&__CS__); #endif #if PLATFORM_POSIX RetVal = !pthread_mutex_trylock(&__MUTEX__); #endif return RetVal; } /* Leave from behind of barrior. */ FASTINLINE void Leave() const { #if PLATFORM_WINDOWS w32_compat::LeaveCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_unlock(&__MUTEX__); #endif } private: #if PLATFORM_WINDOWS mutable w32_compat::CRITICAL_SECTION __CS__; #endif #if PLATFORM_POSIX mutable pthread_mutex_t __MUTEX__; #endif }; /* Barrior scope. */ class FBarriorScope { public: FASTINLINE FBarriorScope(FBarrior& Barrior) : Barrior(&Barrior) { Barrior.Enter(); } FASTINLINE FBarriorScope(const FBarrior& Barrior) : Barrior(&Barrior) { Barrior.Enter(); } FASTINLINE ~FBarriorScope() { Barrior->Leave(); } private: const FBarrior* Barrior; }; #define BOX_BARRIOR_SCOPED(BarriorInstance) \ boxpp::FBarriorScope BOX_CONCAT(__Scope_At_, __LINE__) (BarriorInstance) #define BOX_DO_WITH_BARRIOR(BarriorInstance, ...) \ if (true) { BOX_BARRIOR_SCOPED(BarriorInstance); __VA_ARGS__ } }
20.754717
73
0.735
whoamiho1006
9752b0ceb7349ca95afc55b5ed16da2d464af0a3
3,746
cpp
C++
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
1
2020-05-02T14:33:42.000Z
2020-05-02T14:33:42.000Z
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
null
null
null
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
null
null
null
#include <core/vector.hpp> #include <catch2/catch.hpp> TEMPLATE_TEST_CASE( "[Vector] - specialised constructors", "[core]", float, double, int) { SECTION("Empty constructor: size 2") { core::Vector2<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); } SECTION("Empty constructor: size 3") { core::Vector3<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); REQUIRE(v.z == TestType{0}); } SECTION("Empty constructor: size 4") { core::Vector4<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); REQUIRE(v.z == TestType{0}); REQUIRE(v.w == TestType{0}); } SECTION("Uniform constructor: size 2") { core::Vector2<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); } SECTION("Uniform constructor: size 3") { core::Vector3<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); REQUIRE(v.z == TestType{1}); } SECTION("Uniform constructor: size 2") { core::Vector4<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); REQUIRE(v.z == TestType{1}); REQUIRE(v.w == TestType{1}); } SECTION("Parameterised constructor: size 2") { core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); } SECTION("Parameterised constructor: size 3") { core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); REQUIRE(v.z == TestType{3}); } SECTION("Parameterised constructor: size 4") { core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); REQUIRE(v.z == TestType{3}); REQUIRE(v.w == TestType{4}); } } TEMPLATE_TEST_CASE( "[Vector] - specialised operator[]", "[core]", float, double, int) { SECTION("Non-const version: size 2") { core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); } SECTION("Const version: size 2") { const core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); } SECTION("Non-const version: size 3") { core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); } SECTION("Const version: size 3") { const core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); } SECTION("Non-const version: size 4") { core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); REQUIRE(v[3] == TestType{4}); } SECTION("Const version: size 4") { const core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); REQUIRE(v[3] == TestType{4}); } }
24.973333
79
0.533102
marovira
97530a740cbd510778a20901f769a6207c46fb76
2,688
cpp
C++
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
3
2021-08-07T07:01:34.000Z
2021-08-07T07:03:02.000Z
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/redundant-connection-ii/ // In this problem, a rooted tree is a directed graph such that, there is exactly // one node (the root) for which all other nodes are descendants of this node, plus // every node has exactly one parent, except for the root node which has no // parents. // The given input is a directed graph that started as a rooted tree with n nodes // (with distinct values from 1 to n), with one additional directed edge added. The // added edge has two different vertices chosen from 1 to n, and was not an edge // that already existed. // The resulting graph is given as a 2D-array of edges. Each element of edges is a // pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where // ui is a parent of child vi. // Return an edge that can be removed so that the resulting graph is a rooted tree // of n nodes. If there are multiple answers, return the answer that occurs last in // the given 2D-array. //////////////////////////////////////////////////////////////////////////////// // union find not work, since edge has direction may cause cycle // search for node with two parents -> edgeA, edgeB // perform union find without edgeB // -> 1) if tree is valid, return edgeB // -> 2) if found a cycle return a) edgeA or the causing edge // -> 3) return edgeB class Solution { public: vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { int n = edges.size(); vector<int> edgeA, edgeB; // search for node with two parents for (int i = 1; i <= n; ++i) parents[i] = 0; for (auto& edge : edges) { // (parent) edge[0] -> (child) edge[1] if (parents[edge[1]] == 0) { // new edge parents[edge[1]] = edge[0]; } else { // edge with two parents edgeA = {parents[edge[1]], edge[1]}; edgeB = edge; } } // union find without edgeB for (int i = 1; i <= n; ++i) parents[i] = i; for (auto& edge : edges) { if (edge == edgeB) continue; // skip edgeB if (!unionNodes(edge[0], edge[1])) { if (edgeA.empty()) return edge; return edgeA; } } return edgeB; } private: unordered_map<int, int> parents; int find(int x) { if (parents[x] != x) parents[x] = find(parents[x]); return parents[x]; } bool unionNodes(int x, int y) { // (parent) x -> (child) y int xP = find(x); if (xP == y) return false; // found a cycle int yP = find(y); if (xP != yP) parents[yP] = xP; return true; } };
38.4
83
0.579241
longwangjhu
97545d9fcf31e1ca0b370f0a32ea117b6cfedd49
3,899
cpp
C++
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
170
2015-10-20T08:31:16.000Z
2021-12-01T01:47:32.000Z
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
42
2015-10-20T23:20:17.000Z
2022-03-18T05:47:08.000Z
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
83
2015-10-22T14:53:00.000Z
2021-11-04T03:09:48.000Z
// This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015 Orbbec 3D // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Be excellent to each other. #include <astra_core/capi/astra_types.h> #include <astra/capi/astra_ctypes.h> #include "astra_generic_stream_api.hpp" #include <astra/capi/streams/point_capi.h> #include <astra/capi/streams/point_types.h> #include <astra/capi/streams/stream_types.h> #include <string.h> #include <cassert> #include <astra/capi/streams/image_capi.h> ASTRA_BEGIN_DECLS ASTRA_API_EX astra_status_t astra_reader_get_pointstream(astra_reader_t reader, astra_pointstream_t* pointStream) { return astra_reader_get_stream(reader, ASTRA_STREAM_COLOR, DEFAULT_SUBTYPE, pointStream); } ASTRA_API_EX astra_status_t astra_frame_get_pointframe(astra_reader_frame_t readerFrame, astra_pointframe_t* pointFrame) { return astra_reader_get_imageframe(readerFrame, ASTRA_STREAM_POINT, DEFAULT_SUBTYPE, pointFrame); } ASTRA_API_EX astra_status_t astra_frame_get_pointframe_with_subtype(astra_reader_frame_t readerFrame, astra_stream_subtype_t subtype, astra_pointframe_t* pointFrame) { return astra_reader_get_imageframe(readerFrame, ASTRA_STREAM_POINT, subtype, pointFrame); } ASTRA_API_EX astra_status_t astra_pointframe_get_frameindex(astra_pointframe_t pointFrame, astra_frame_index_t* index) { return astra_generic_frame_get_frameindex(pointFrame, index); } ASTRA_API_EX astra_status_t astra_pointframe_get_data_byte_length(astra_pointframe_t pointFrame, size_t* byteLength) { return astra_imageframe_get_data_byte_length(pointFrame, byteLength); } ASTRA_API_EX astra_status_t astra_pointframe_get_data_ptr(astra_pointframe_t pointFrame, astra_vector3f_t** data, size_t* byteLength) { void* voidData = nullptr; astra_imageframe_get_data_ptr(pointFrame, &voidData, byteLength); *data = static_cast<astra_vector3f_t*>(voidData); return ASTRA_STATUS_SUCCESS; } ASTRA_API_EX astra_status_t astra_pointframe_copy_data(astra_pointframe_t pointFrame, astra_vector3f_t* data) { return astra_imageframe_copy_data(pointFrame, data); } ASTRA_API_EX astra_status_t astra_pointframe_get_metadata(astra_pointframe_t pointFrame, astra_image_metadata_t* metadata) { return astra_imageframe_get_metadata(pointFrame, metadata); } ASTRA_END_DECLS
41.478723
108
0.595794
Delicode
97545f1944b626487fa100e059cfbcfc2a64195d
129
cpp
C++
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:d16864b0d69d3a425328f013d6bb2842892c448c6a7cdc5077078ae6564113f8 size 3329
32.25
75
0.883721
realtehcman
975467ff92a3e30d15262dd5d6e95dc133ef5092
1,795
cpp
C++
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
#include <ysu/crypto_lib/random_pool.hpp> #include <ysu/node/testing.hpp> #include <ysu/test_common/testutil.hpp> #include <gtest/gtest.h> #include <cstdlib> #include <numeric> using namespace std::chrono_literals; /* Convenience constants for tests which are always on the test network */ namespace { ysu::ledger_constants dev_constants (ysu::ysu_networks::ysu_dev_network); } ysu::keypair const & ysu::zero_key (dev_constants.zero_key); ysu::keypair const & ysu::dev_genesis_key (dev_constants.dev_genesis_key); ysu::account const & ysu::ysu_dev_account (dev_constants.ysu_dev_account); std::string const & ysu::ysu_dev_genesis (dev_constants.ysu_dev_genesis); ysu::account const & ysu::genesis_account (dev_constants.genesis_account); ysu::block_hash const & ysu::genesis_hash (dev_constants.genesis_hash); ysu::uint128_t const & ysu::genesis_amount (dev_constants.genesis_amount); ysu::account const & ysu::burn_account (dev_constants.burn_account); void ysu::wait_peer_connections (ysu::system & system_a) { auto wait_peer_count = [&system_a](bool in_memory) { auto num_nodes = system_a.nodes.size (); system_a.deadline_set (20s); size_t peer_count = 0; while (peer_count != num_nodes * (num_nodes - 1)) { ASSERT_NO_ERROR (system_a.poll ()); peer_count = std::accumulate (system_a.nodes.cbegin (), system_a.nodes.cend (), std::size_t{ 0 }, [in_memory](auto total, auto const & node) { if (in_memory) { return total += node->network.size (); } else { auto transaction = node->store.tx_begin_read (); return total += node->store.peer_count (transaction); } }); } }; // Do a pre-pass with in-memory containers to reduce IO if still in the process of connecting to peers wait_peer_count (true); wait_peer_count (false); }
33.240741
145
0.732591
lik2129
975504aa4082edaf5699b688a1441696cf8721dc
24,484
cpp
C++
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
13
2019-01-23T04:36:05.000Z
2022-02-21T11:20:25.000Z
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
null
null
null
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
3
2019-01-24T07:48:15.000Z
2021-06-11T13:34:44.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2011-2018比特币核心开发者 //根据MIT软件许可证分发,请参见随附的 //文件复制或http://www.opensource.org/licenses/mit-license.php。 #include <qt/transactiontablemodel.h> #include <qt/addresstablemodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/transactiondesc.h> #include <qt/transactionrecord.h> #include <qt/walletmodel.h> #include <core_io.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <sync.h> #include <uint256.h> #include <util/system.h> #include <validation.h> #include <QColor> #include <QDateTime> #include <QDebug> #include <QIcon> #include <QList> //金额列右对齐,包含数字 static int column_alignments[] = { /*:AlignLeft qt::AlignvCenter,/*状态*/ qt::AlignLeft qt::AlignvCenter,/*仅监视*/ /*:AlignLeft qt::AlignvCenter,/*日期*/ qt::AlignLeft qt::AlignvCenter,/*类型*/ /*:AlignLeft qt::AlignvCenter,/*地址*/ qt::AlignRight qt::AlignvCenter/*数量*/ }; //Tx型列表排序/二进制搜索的比较运算符 struct TxLessThan { bool operator()(const TransactionRecord &a, const TransactionRecord &b) const { return a.hash < b.hash; } bool operator()(const TransactionRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const TransactionRecord &b) const { return a < b.hash; } }; //私有实施 class TransactionTablePriv { public: explicit TransactionTablePriv(TransactionTableModel *_parent) : parent(_parent) { } TransactionTableModel *parent; /*钱包的本地缓存。 *根据定义,它与cwallet的顺序相同。 *按sha256排序。 **/ QList<TransactionRecord> cachedWallet; /*从核心重新查询整个钱包。 **/ void refreshWallet(interfaces::Wallet& wallet) { qDebug() << "TransactionTablePriv::refreshWallet"; cachedWallet.clear(); { for (const auto& wtx : wallet.getWalletTxs()) { if (TransactionRecord::showTransaction()) { cachedWallet.append(TransactionRecord::decomposeTransaction(wtx)); } } } } /*逐步更新钱包模型,以同步钱包模型 和核心的那个。 调用已添加、删除或更改的事务。 **/ void updateWallet(interfaces::Wallet& wallet, const uint256 &hash, int status, bool showTransaction) { qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status); //在模型中查找此事务的边界 QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); if(status == CT_UPDATED) { if(showTransaction && !inModel) /*tus=ct_new;/*不在模型中,但要显示,视为新的*/ 如果(!)ShowTransaction和InModel) status=ct_deleted;/*在模型中,但要隐藏,视为已删除*/ } qDebug() << " inModel=" + QString::number(inModel) + " Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) + " showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status); switch(status) { case CT_NEW: if(inModel) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is already in model"; break; } if(showTransaction) { //在钱包中查找交易 interfaces::WalletTx wtx = wallet.getWalletTx(hash); if(!wtx.tx) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet"; break; } //添加--在正确位置插入 QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wtx); /*!to insert.isEmpty())/*仅当要插入的内容时*/ { parent->beginInsertRows(qmodelIndex(),lowerindex,lowerindex+toinsert.size()-1); int insert_idx=lowerindex; 用于(const transactionrecord&rec:toinsert) { cachedWallet.insert(插入_idx,rec); 插入_idx+=1; } parent->endinsertrows(); } } 断裂; 删除的案例: 如果(!)内模) { qwarning()<“transactionTablepriv::updateWallet:warning:got ct_deleted,but transaction is not in model”; 断裂; } //已删除--从表中删除整个事务 parent->beginremoverws(qmodelindex(),lowerindex,upperindex-1); cachedWallet.erase(下,上); parent->endremoves(); 断裂; 案例CT更新: //其他更新——不做任何事情,状态更新将处理此问题,并且只计算 //可见事务。 对于(int i=lowerindex;i<upperindex;i++) transactionrecord*rec=&cachedwallet[i]; rec->status.needsupdate=true; } 断裂; } } int siz() { 返回cachedWallet.size(); } 交易记录*索引(接口::Wallet&Wallet,int IDX) { 如果(idx>=0&&idx<cachedWallet.size()) { transactionrecord*rec=&cachedwallet[idx]; //预先获取所需的锁。这样就避免了图形用户界面 //如果核心持有锁的时间更长,则会卡住- //例如,在钱包重新扫描期间。 / / //如果需要状态更新(自上次检查以来出现块), //从钱包更新此交易的状态。否则, //只需重新使用缓存状态。 接口::wallettxstatus wtx; int数字块; Int64阻塞时间; if(wallet.trygettxstatus(rec->hash,wtx,numblocks,block_time)&&rec->statusupdateeneeded(numblocks)); rec->updateStatus(wtx,numblocks,block_time); } 返回记录; } 返回null pTR; } qString描述(interfaces::node&node,interfaces::wallet&wallet,transactionrecord*rec,int unit) { 返回事务描述::tohtml(节点、钱包、记录、单位); } qstring gettxhex(接口::wallet&wallet,transactionrecord*rec) { auto tx=wallet.gettx(rec->hash); 如果(Tx){ std::string strhex=encodehextx(*tx); 返回qstring::fromstdstring(strhex); } 返回qString(); } }; TransactionTableModel::TransactionTableModel(const platformStyle*_platformStyle,walletModel*父级): QabstractTableModel(父级) 墙模型(父) priv(新交易表priv(this)), fprocessingQueuedTransactions(假), 平台样式(_PlatformStyle) { 列<<qString()<<qString()<<tr(“日期”)<<tr(“类型”)<<tr(“标签”)<<bitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); priv->refreshwallet(walletmodel->wallet()); Connect(walletModel->getOptionsModel(),&OptionsModel::DisplayUnitChanged,this,&TransactionTableModel::UpdateDisplayUnit); subscriptOCoreginals(); } TransactionTableModel::~TransactionTableModel()。 { 取消订阅coresignals(); 删除PRIV; } /**将列标题更新为“amount(displayUnit)”,并发出headerDataChanged()信号,以便表头作出反应。*/ void TransactionTableModel::updateAmountColumnTitle() { columns[Amount] = BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount); } void TransactionTableModel::updateTransaction(const QString &hash, int status, bool showTransaction) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(walletModel->wallet(), updated, status, showTransaction); } void TransactionTableModel::updateConfirmations() { //自上次投票以来,出现了一些障碍。 //失效状态(确认数量)和(可能)描述 //对于所有行。qt足够智能,只实际请求 //可见行。 Q_EMIT dataChanged(index(0, Status), index(priv->size()-1, Status)); Q_EMIT dataChanged(index(0, ToAddress), index(priv->size()-1, ToAddress)); } int TransactionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int TransactionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QString TransactionTableModel::formatTxStatus(const TransactionRecord *wtx) const { QString status; switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: status = tr("Open for %n more block(s)","",wtx->status.open_for); break; case TransactionStatus::OpenUntilDate: status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for)); break; case TransactionStatus::Unconfirmed: status = tr("Unconfirmed"); break; case TransactionStatus::Abandoned: status = tr("Abandoned"); break; case TransactionStatus::Confirming: status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations); break; case TransactionStatus::Confirmed: status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth); break; case TransactionStatus::Conflicted: status = tr("Conflicted"); break; case TransactionStatus::Immature: status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in); break; case TransactionStatus::NotAccepted: status = tr("Generated but not accepted"); break; } return status; } QString TransactionTableModel::formatTxDate(const TransactionRecord *wtx) const { if(wtx->time) { return GUIUtil::dateTimeStr(wtx->time); } return QString(); } /*在通讯簿中查找地址,如果找到,则返回标签(地址) 否则只需返回(地址) **/ QString TransactionTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label; } if(label.isEmpty() || tooltip) { description += QString(" (") + QString::fromStdString(address) + QString(")"); } return description; } QString TransactionTableModel::formatTxType(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::RecvWithAddress: return tr("Received with"); case TransactionRecord::RecvFromOther: return tr("Received from"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return tr("Sent to"); case TransactionRecord::SendToSelf: return tr("Payment to yourself"); case TransactionRecord::Generated: return tr("Mined"); default: return QString(); } } QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::Generated: return QIcon(":/icons/tx_mined"); case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: return QIcon(":/icons/tx_input"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return QIcon(":/icons/tx_output"); default: return QIcon(":/icons/tx_inout"); } } QString TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const { QString watchAddress; if (tooltip) { //通过添加“(仅监视)”标记涉及仅监视地址的事务。 watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : ""; } switch(wtx->type) { case TransactionRecord::RecvFromOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: return lookupAddress(wtx->address, tooltip) + watchAddress; case TransactionRecord::SendToOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::SendToSelf: default: return tr("(n/a)") + watchAddress; } } QVariant TransactionTableModel::addressColor(const TransactionRecord *wtx) const { //以不太明显的颜色显示不带标签的地址 switch(wtx->type) { case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address)); if(label.isEmpty()) return COLOR_BAREADDRESS; } break; case TransactionRecord::SendToSelf: return COLOR_BAREADDRESS; default: break; } return QVariant(); } QString TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed, BitcoinUnits::SeparatorStyle separators) const { QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators); if(showUnconfirmed) { if(!wtx->status.countsForBalance) { str = QString("[") + str + QString("]"); } } return QString(str); } QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) const { switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: case TransactionStatus::OpenUntilDate: return COLOR_TX_STATUS_OPENUNTILDATE; case TransactionStatus::Unconfirmed: return QIcon(":/icons/transaction_0"); case TransactionStatus::Abandoned: return QIcon(":/icons/transaction_abandoned"); case TransactionStatus::Confirming: switch(wtx->status.depth) { case 1: return QIcon(":/icons/transaction_1"); case 2: return QIcon(":/icons/transaction_2"); case 3: return QIcon(":/icons/transaction_3"); case 4: return QIcon(":/icons/transaction_4"); default: return QIcon(":/icons/transaction_5"); }; case TransactionStatus::Confirmed: return QIcon(":/icons/transaction_confirmed"); case TransactionStatus::Conflicted: return QIcon(":/icons/transaction_conflicted"); case TransactionStatus::Immature: { int total = wtx->status.depth + wtx->status.matures_in; int part = (wtx->status.depth * 4 / total) + 1; return QIcon(QString(":/icons/transaction_%1").arg(part)); } case TransactionStatus::NotAccepted: return QIcon(":/icons/transaction_0"); default: return COLOR_BLACK; } } QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord *wtx) const { if (wtx->involvesWatchAddress) return QIcon(":/icons/eye"); else return QVariant(); } QString TransactionTableModel::formatTooltip(const TransactionRecord *rec) const { QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec); if(rec->type==TransactionRecord::RecvFromOther || rec->type==TransactionRecord::SendToOther || rec->type==TransactionRecord::SendToAddress || rec->type==TransactionRecord::RecvWithAddress) { tooltip += QString(" ") + formatTxToAddress(rec, true); } return tooltip; } QVariant TransactionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer()); switch(role) { case RawDecorationRole: switch(index.column()) { case Status: return txStatusDecoration(rec); case Watchonly: return txWatchonlyDecoration(rec); case ToAddress: return txAddressDecoration(rec); } break; case Qt::DecorationRole: { QIcon icon = qvariant_cast<QIcon>(index.data(RawDecorationRole)); return platformStyle->TextColorIcon(icon); } case Qt::DisplayRole: switch(index.column()) { case Date: return formatTxDate(rec); case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, false); case Amount: return formatTxAmount(rec, true, BitcoinUnits::separatorAlways); } break; case Qt::EditRole: //编辑角色用于排序,因此返回未格式化的值 switch(index.column()) { case Status: return QString::fromStdString(rec->status.sortKey); case Date: return rec->time; case Type: return formatTxType(rec); case Watchonly: return (rec->involvesWatchAddress ? 1 : 0); case ToAddress: return formatTxToAddress(rec, true); case Amount: return qint64(rec->credit + rec->debit); } break; case Qt::ToolTipRole: return formatTooltip(rec); case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: //对放弃的交易使用“危险”颜色 if(rec->status.status == TransactionStatus::Abandoned) { return COLOR_TX_STATUS_DANGER; } //未确认(但不未成熟),因为交易是灰色的 if(!rec->status.countsForBalance && rec->status.status != TransactionStatus::Immature) { return COLOR_UNCONFIRMED; } if(index.column() == Amount && (rec->credit+rec->debit) < 0) { return COLOR_NEGATIVE; } if(index.column() == ToAddress) { return addressColor(rec); } break; case TypeRole: return rec->type; case DateRole: return QDateTime::fromTime_t(static_cast<uint>(rec->time)); case WatchonlyRole: return rec->involvesWatchAddress; case WatchonlyDecorationRole: return txWatchonlyDecoration(rec); case LongDescriptionRole: return priv->describe(walletModel->node(), walletModel->wallet(), rec, walletModel->getOptionsModel()->getDisplayUnit()); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); case AmountRole: return qint64(rec->credit + rec->debit); case TxHashRole: return rec->getTxHash(); case TxHexRole: return priv->getTxHex(walletModel->wallet(), rec); case TxPlainTextRole: { QString details; QDateTime date = QDateTime::fromTime_t(static_cast<uint>(rec->time)); QString txLabel = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); details.append(date.toString("M/d/yy HH:mm")); details.append(" "); details.append(formatTxStatus(rec)); details.append(". "); if(!formatTxType(rec).isEmpty()) { details.append(formatTxType(rec)); details.append(" "); } if(!rec->address.empty()) { if(txLabel.isEmpty()) details.append(tr("(no label)") + " "); else { details.append("("); details.append(txLabel); details.append(") "); } details.append(QString::fromStdString(rec->address)); details.append(" "); } details.append(formatTxAmount(rec, false, BitcoinUnits::separatorNever)); return details; } case ConfirmedRole: return rec->status.countsForBalance; case FormattedAmountRole: //用于复制/导出,因此不包括分隔符 return formatTxAmount(rec, false, BitcoinUnits::separatorNever); case StatusRole: return rec->status.status; } return QVariant(); } QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Status: return tr("Transaction status. Hover over this field to show number of confirmations."); case Date: return tr("Date and time that the transaction was received."); case Type: return tr("Type of transaction."); case Watchonly: return tr("Whether or not a watch-only address is involved in this transaction."); case ToAddress: return tr("User-defined intent/purpose of the transaction."); case Amount: return tr("Amount removed from or added to balance."); } } } return QVariant(); } QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); TransactionRecord *data = priv->index(walletModel->wallet(), row); if(data) { return createIndex(row, column, priv->index(walletModel->wallet(), row)); } return QModelIndex(); } void TransactionTableModel::updateDisplayUnit() { //发出datachanged以使用当前单位更新amount列 updateAmountColumnTitle(); Q_EMIT dataChanged(index(0, Amount), index(priv->size()-1, Amount)); } //排队通知以显示非冻结进度对话框,例如用于重新扫描 struct TransactionNotification { public: TransactionNotification() {} TransactionNotification(uint256 _hash, ChangeType _status, bool _showTransaction): hash(_hash), status(_status), showTransaction(_showTransaction) {} void invoke(QObject *ttm) { QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged: " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, strHash), Q_ARG(int, status), Q_ARG(bool, showTransaction)); } private: uint256 hash; ChangeType status; bool showTransaction; }; static bool fQueueNotifications = false; static std::vector< TransactionNotification > vQueueNotifications; static void NotifyTransactionChanged(TransactionTableModel *ttm, const uint256 &hash, ChangeType status) { //在钱包中查找交易 //确定是否显示事务(在这里确定,以便在GUI线程中不需要重新锁定) bool showTransaction = TransactionRecord::showTransaction(); TransactionNotification notification(hash, status, showTransaction); if (fQueueNotifications) { vQueueNotifications.push_back(notification); return; } notification.invoke(ttm); } static void ShowProgress(TransactionTableModel *ttm, const std::string &title, int nProgress) { if (nProgress == 0) fQueueNotifications = true; if (nProgress == 100) { fQueueNotifications = false; if (vQueueNotifications.size() > 10) //防止气球垃圾邮件,最多显示10个气球 QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true)); for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) { if (vQueueNotifications.size() - i <= 10) QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false)); vQueueNotifications[i].invoke(ttm); } std::vector<TransactionNotification >().swap(vQueueNotifications); //清楚的 } } void TransactionTableModel::subscribeToCoreSignals() { //将信号连接到钱包 m_handler_transaction_changed = walletModel->wallet().handleTransactionChanged(std::bind(NotifyTransactionChanged, this, std::placeholders::_1, std::placeholders::_2)); m_handler_show_progress = walletModel->wallet().handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2)); } void TransactionTableModel::unsubscribeFromCoreSignals() { //断开钱包信号 m_handler_transaction_changed->disconnect(); m_handler_show_progress->disconnect(); }
31.592258
172
0.628247
yinchengtsinghua
97562bbcc8ce6931c6929edab6d5e82527117d3a
4,330
cpp
C++
test/MutationTest.cpp
ATsahikian/PeProtector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
43
2016-07-30T13:50:21.000Z
2021-06-17T22:45:00.000Z
test/MutationTest.cpp
ATsahikian/pe-protector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
null
null
null
test/MutationTest.cpp
ATsahikian/pe-protector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
16
2016-09-08T09:10:27.000Z
2020-06-14T00:30:59.000Z
#define BOOST_TEST_MODULE mutation test #include <boost/test/included/unit_test.hpp> #include "pe-protector/Mutation.h" using namespace NPeProtector; BOOST_AUTO_TEST_SUITE(MutationTest); // method for testing mutateCommands with Mov instruction BOOST_AUTO_TEST_CASE(testMutateCommandsMov) { // create command for testing "MOV EAX, EBX" SOperand operand1; operand1.mType = NOperand::REG32; operand1.mRegister = NRegister::EAX; SOperand operand2; operand2.mType = NOperand::REG32; operand2.mRegister = NRegister::EBX; SInstruction instruction{ NPrefix::NON, NInstruction::MOV, {operand1, operand2}}; SCommand movCommand; movCommand.mType = NCommand::INSTRUCTION; movCommand.mInstruction = instruction; std::vector<SCommand> commands = {movCommand}; // pass command "MOV EAX, EBX" mutateCommands(commands); // create instruction "PUSH EBX" SCommand pushCommand; pushCommand.mType = NCommand::INSTRUCTION; pushCommand.mInstruction.mType = NInstruction::PUSH; pushCommand.mInstruction.mOperands.push_back(operand2); // create instruction "POP EAX" SCommand popCommand; popCommand.mType = NCommand::INSTRUCTION; popCommand.mInstruction.mType = NInstruction::POP; popCommand.mInstruction.mOperands.push_back(operand1); std::vector<SCommand> expectedResult = {pushCommand, popCommand}; // compare results BOOST_TEST(expectedResult[0].mType == commands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mType == commands[0].mInstruction.mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mType == commands[0].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mRegister == commands[0].mInstruction.mOperands[0].mRegister); BOOST_TEST(expectedResult[1].mType == commands[1].mType); BOOST_TEST(expectedResult[1].mInstruction.mType == commands[1].mInstruction.mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mType == commands[1].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mRegister == commands[1].mInstruction.mOperands[0].mRegister); } // method for testing mutateCommands with Push instruction BOOST_AUTO_TEST_CASE(testMutateCommandsPush) { // create instruction "PUSH EAX" SOperand operand1; operand1.mType = NOperand::REG32; operand1.mRegister = NRegister::EAX; SInstruction instruction{NPrefix::NON, NInstruction::PUSH, {operand1}}; SCommand pushCommand; pushCommand.mType = NCommand::INSTRUCTION; pushCommand.mInstruction = instruction; std::vector<SCommand> commands = {pushCommand}; // pass instruction "PUSH EAX" mutateCommands(commands); // create instruction "SUB ESP, 4" SCommand subCommand; subCommand.mType = NCommand::INSTRUCTION; subCommand.mInstruction.mType = NInstruction::SUB; SOperand espOperand; espOperand.mType = NOperand::REG32; espOperand.mRegister = NRegister::ESP; subCommand.mInstruction.mOperands.push_back(espOperand); SOperand constOperand; constOperand.mType = NOperand::CONSTANT; constOperand.mConstant.mValue = 4; subCommand.mInstruction.mOperands.push_back(constOperand); // create instruction "MOV DWORD PTR [ESP], EAX" SCommand movCommand; movCommand.mType = NCommand::INSTRUCTION; movCommand.mInstruction.mType = NInstruction::MOV; SOperand memOperand; memOperand.mType = NOperand::MEM32; memOperand.mMemory.mRegisters.push_back(NRegister::ESP); movCommand.mInstruction.mOperands.push_back(memOperand); movCommand.mInstruction.mOperands.push_back(operand1); std::vector<SCommand> expectedResult = {subCommand, movCommand}; // compare results BOOST_TEST(expectedResult[0].mType == commands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mType == commands[0].mInstruction.mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mType == commands[0].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[1].mType == commands[1].mType); BOOST_TEST(expectedResult[1].mInstruction.mType == commands[1].mInstruction.mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mType == commands[1].mInstruction.mOperands[0].mType); } BOOST_AUTO_TEST_SUITE_END();
34.365079
73
0.748037
ATsahikian
9758a9719e4fec47c6d0eb4501ade7763f26887c
1,913
cpp
C++
openqube/testing/testatom.cpp
OpenChemistry/openqube
dc396bcf6c74cbfd9fb94201312e70bb377b0805
[ "BSD-3-Clause" ]
2
2015-05-05T19:49:55.000Z
2021-03-30T12:27:40.000Z
openqube/testing/testatom.cpp
OpenChemistry/openqube
dc396bcf6c74cbfd9fb94201312e70bb377b0805
[ "BSD-3-Clause" ]
null
null
null
openqube/testing/testatom.cpp
OpenChemistry/openqube
dc396bcf6c74cbfd9fb94201312e70bb377b0805
[ "BSD-3-Clause" ]
4
2015-01-29T16:25:12.000Z
2021-01-06T17:47:47.000Z
#include <iostream> #include <openqube/molecule.h> #include <openqube/atom.h> #include <Eigen/Geometry> using std::cout; using std::cerr; using std::endl; using OpenQube::Atom; using OpenQube::Molecule; using Eigen::Vector3d; namespace { template<typename A, typename B> void checkResult(const A& result, const B& expected, bool &error) { if (result != expected) { cerr << "Error, expected result " << expected << ", got " << result << endl; error = true; } } } short testAtomConst(const Molecule& mol, size_t index) { return mol.atom(index).atomicNumber(); } int testatom(int , char *[]) { bool error = false; cout << "Testing the atom class..." << endl; Molecule mol; Atom a = mol.addAtom(Vector3d(0.0, 1.0, 0.0), 1); checkResult(a.isValid(), true, error); checkResult(a.isHydrogen(), true, error); checkResult(a.atomicNumber(), 1, error); a.setAtomicNumber(69); checkResult(a.isHydrogen(), false, error); checkResult(a.atomicNumber(), 69, error); checkResult(a.pos(), Vector3d(0.0, 1.0, 0.0), error); a.setPos(Vector3d(1.0, 1.0, 1.0)); checkResult(a.pos(), Vector3d(1.0, 1.0, 1.0), error); Atom a2 = mol.atom(1); checkResult(a2.isValid(), false, error); checkResult(a2.isHydrogen(), false, error); a2.setAtomicNumber(1); checkResult(a2.isHydrogen(), false, error); a2.setPos(Vector3d(1.0, 1.0, 1.0)); checkResult(a2.pos(), Vector3d::Zero(), error); cout << "Number of atoms = " << mol.numAtoms() << endl; Atom carbon = mol.addAtom(Vector3d::Zero(), 6); cout << "Number of atoms = " << mol.numAtoms() << endl; const Atom carbonCopy = mol.atom(1); checkResult(carbon.atomicNumber(), carbonCopy.atomicNumber(), error); checkResult(carbon.atomicNumber(), testAtomConst(mol, 1), error); carbon.setAtomicNumber(7); checkResult(carbon.atomicNumber(), carbonCopy.atomicNumber(), error); mol.print(); return error ? 1 : 0; }
24.525641
80
0.664924
OpenChemistry
9759ce0c8aec21542ab1727ba287d9376bdd192c
606
cpp
C++
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
/** * @file ComputePipeline.cpp * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2016.10.30 * * @brief Implementation of a vulkan compute pipeline object. */ #include "gfx/vk/pipeline/ComputePipeline.h" #include "gfx/vk/LogicalDevice.h" #include "core/resources/ShaderManager.h" namespace vkfw_core::gfx { ComputePipeline::ComputePipeline(const std::string& shaderStageId, gfx::LogicalDevice* device) : Resource(shaderStageId, device) { throw std::runtime_error("NOT YET IMPLEMENTED!"); } ComputePipeline::~ComputePipeline() = default; }
25.25
100
0.709571
dasmysh
975cebfc63316babaaa98c51f6a47676e5c47673
169
cpp
C++
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
#include "VSC.h" #include <boost/date_time/posix_time/posix_time.hpp> VSC::Time VSC::CurrentTime() { return boost::posix_time::microsec_clock::universal_time(); }
18.777778
63
0.739645
jbat100
975e930eb1006c6956faf01e14b61bb51426f222
6,452
hpp
C++
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
// Copyright Yamaha 2021 // MIT License // https://github.com/yamaha-bps/cbr_drivers/blob/master/LICENSE #ifndef CBR_DRIVERS__V4L2_DRIVER_HPP_ #define CBR_DRIVERS__V4L2_DRIVER_HPP_ #include <linux/videodev2.h> #include <atomic> #include <functional> #include <memory> #include <mutex> #include <string> #include <thread> #include <utility> #include <vector> #include <iostream> namespace cbr { class V4L2Driver { public: /** * Helper structures for interfacing with the driver */ struct buffer_t { void * pos; // memory location of buffer std::size_t len; // size in bytes }; struct format_t { std::string format; uint32_t width, height; float fps; }; enum class ctrl_type { INTEGER = V4L2_CTRL_TYPE_INTEGER, BOOLEAN = V4L2_CTRL_TYPE_BOOLEAN, MENU = V4L2_CTRL_TYPE_MENU }; struct ival_t { int32_t minimum; int32_t maximum; int32_t step; }; struct menu_entry_t { uint32_t index; std::string name; }; struct ctrl_t { uint32_t id; ctrl_type type; std::string name; int32_t def; // default value ival_t ival; // only populated for INTEGER, BOOLEAN std::vector<menu_entry_t> menu; // ony populated for MENU }; /** * @brief v4l2 driver for capturing image streams * * This driver is flexible in terms of management: a user can supply a callback * that is called on frames containing new buffers, and also custom allocation and * de-allocation functions for allocating said buffers. * * If no allocation functions are provided malloc()/free() is used. * * @param device the v4l object (default /dev/video0) * @param n_buf the number of buffers to use (default 4) */ explicit V4L2Driver(std::string device = "/dev/video0", uint32_t n_buf = 4); V4L2Driver(const V4L2Driver &) = delete; V4L2Driver & operator=(const V4L2Driver & other) = delete; V4L2Driver(V4L2Driver &&) = delete; V4L2Driver & operator=(V4L2Driver &&) = delete; ~V4L2Driver(); /** * @brief Set the callback * * NOTE: the callback should return quickly or frames will be missed * * The callback should have signature * void(const uint8_t *, const v4l2_pix_format &) * and is called on every new frame. */ template<typename T> void set_callback(T && cb) { cb_ = std::forward<T>(cb); } /** * @brief Set a custom allocator * * NOTE: Use only in conjuction with set_custom_deallocator * * The allocator should have signature * void *(std::size_t) * * The returned pointer is freed with the custom deallocator */ template<typename T> void set_custom_allocator(T && cb) { custom_alloc_ = std::forward<T>(cb); } /** * @brief Set a custom deallocator * * NOTE: Use only in conjuction with set_custom_allocator * * The deallocator should have signature * void(void *, std::size_t) */ template<typename T> void set_custom_deallocator(T && cb) { custom_dealloc_ = std::forward<T>(cb); } /** * @brief Initialize the driver and start capturing */ bool start(); /** * @brief Stop capturing and de-initialize the driver */ void stop(); /** * @brief Get current fps */ float get_fps(); /** * @brief List all formats supported by the device */ std::vector<format_t> list_formats(); /** * @brief Get active video format */ v4l2_pix_format get_format(); /** * @brief Request a format from v4l2 * * @param width desired frame pixel width * @param height desired frame pixel height * @param fps desired fps * @param fourcc desired image format in fourcc format (must be string with four characters) */ bool set_format(uint32_t width, uint32_t height, uint32_t fps, std::string fourcc = "YUYV"); /** * @brief List controls for the device */ std::vector<ctrl_t> list_controls(); /** * @brief Get control value for the device * * @param id control identifier * @returns the value of the control */ std::optional<int32_t> get_control(uint32_t id); /** * @brief Set control for the device * * @param id control identifier * @param value desired value for control * * @return the new value of the control (should be equal to value) */ bool set_control(uint32_t id, int32_t value); /** * @brief One-way uvc write * @param unit uvc unit (device-specific) * @param control_selector uvc control selector (device-specific) * @param buf buffer to send over UVC (length 384 for USB3, length 64 for USB2) */ bool uvc_set(uint8_t unit, uint8_t control_selector, std::vector<uint8_t> & buf); /** * @brief Two-way uvc communication (write followed by read) * @param unit uvc unit (device-specific) * @param control_selector uvc control selector (device-specific) * @param buf buffer to send over UVC (length 384 for USB3, length 64 for USB2) * * The result is written into buf in accordance with the device protocol */ bool uvc_set_get(uint8_t unit, uint8_t control_selector, std::vector<uint8_t> & buf); protected: /** * @brief Internal method to read the current frame format from V4L2 */ bool update_format(); /** * @brief Internal method for capturing frames */ bool capture_frame(); /** * @brief Internal method that runs in the streaming thread */ void streaming_fcn(); /** * @brief Wrapper around system ioctl call */ int xioctl(uint64_t request, void * arg); protected: uint32_t n_buf_; std::atomic<bool> running_{false}; std::mutex fd_mtx_; int fd_{0}; // file descriptor handle // user buffers that v4l writes into std::vector<buffer_t> buffers_{}; // current device configuration v4l2_pix_format fmt_cur_{}; float fps_{}; std::thread streaming_thread_; std::optional<std::function<void(const uint8_t *, const std::chrono::nanoseconds &, const v4l2_pix_format &)>> cb_{std::nullopt}; std::optional<std::function<void *(std::size_t)>> custom_alloc_{std::nullopt}; std::optional<std::function<void(void *, std::size_t)>> custom_dealloc_{std::nullopt}; }; /** * @brief Convert fourcc code to string */ inline static std::string fourcc_to_str(uint32_t fourcc) { std::string ret(' ', 4); for (uint32_t i = 0; i < 4; ++i) { ret[i] = ((fourcc >> (i * 8)) & 0xFF); } return ret; } } // namespace cbr #endif // CBR_DRIVERS__V4L2_DRIVER_HPP_
23.720588
94
0.6677
yamaha-bps
975ed7bf6d419192ca9632a124ac2c327956a8d4
3,797
cpp
C++
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
3
2018-05-18T19:06:27.000Z
2020-07-07T17:17:51.000Z
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
15
2018-04-25T17:41:36.000Z
2019-11-20T16:06:20.000Z
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
5
2018-04-03T09:12:29.000Z
2022-02-21T11:37:04.000Z
#include "ModulesFactory.hpp" #include <gtest/gtest.h> #include "CommandHook.hpp" #include "CommandIsolator.hpp" using namespace criteo::mesos; // *************************************** // **************** Hook ***************** // *************************************** TEST(ModulesFactoryTest, should_create_hook_with_correct_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("hook_slave_run_task_label_decorator_command"); var->set_value("command_slave_run_task_label_decorator"); var = parameters.add_parameter(); var->set_key("hook_slave_executor_environment_decorator_command"); var->set_value("command_slave_executor_environment_decorator"); var = parameters.add_parameter(); var->set_key("hook_slave_remove_executor_hook_command"); var->set_value("command_slave_remove_executor_hook"); std::unique_ptr<CommandHook> hook( dynamic_cast<CommandHook*>(createHook(parameters))); ASSERT_EQ(hook->runTaskLabelCommand().get(), Command("command_slave_run_task_label_decorator", 30)); ASSERT_EQ(hook->executorEnvironmentCommand().get(), Command("command_slave_executor_environment_decorator", 30)); ASSERT_EQ(hook->removeExecutorCommand().get(), Command("command_slave_remove_executor_hook", 30)); } TEST(ModulesFactoryTest, should_create_hook_with_empty_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("hook_slave_executor_environment_decorator_command"); var->set_value("command_slave_executor_environment_decorator"); std::unique_ptr<CommandHook> hook( dynamic_cast<CommandHook*>(createHook(parameters))); ASSERT_TRUE(hook->runTaskLabelCommand().isNone()); ASSERT_EQ(hook->executorEnvironmentCommand().get(), Command("command_slave_executor_environment_decorator", 30)); ASSERT_TRUE(hook->removeExecutorCommand().isNone()); } // *************************************** // ************** Isolator *************** // *************************************** TEST(ModulesFactoryTest, should_create_isolator_with_correct_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("isolator_prepare_command"); var->set_value("command_prepare"); var = parameters.add_parameter(); var->set_key("isolator_isolate_command"); var->set_value("command_isolate"); var = parameters.add_parameter(); var->set_key("isolator_cleanup_command"); var->set_value("command_cleanup"); std::unique_ptr<CommandIsolator> isolator( dynamic_cast<CommandIsolator*>(createIsolator(parameters))); ASSERT_EQ(isolator->prepareCommand().get(), Command("command_prepare", 30)); ASSERT_EQ(isolator->isolateCommand().get(), Command("command_isolate", 30)); ASSERT_EQ(isolator->cleanupCommand().get(), Command("command_cleanup", 30)); } TEST(ModulesFactoryTest, should_create_isolator_with_empty_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("isolator_prepare_command"); var->set_value("command_prepare"); std::unique_ptr<CommandIsolator> isolator( dynamic_cast<CommandIsolator*>(createIsolator(parameters))); ASSERT_EQ(isolator->prepareCommand().get(), Command("command_prepare", 30)); ASSERT_TRUE(isolator->cleanupCommand().isNone()); ASSERT_TRUE(isolator->isolateCommand().isNone()); }
35.485981
78
0.709244
transdz
975fadcee50dd19822b817bae9019daf61fc3ee1
788
cc
C++
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
#include "./XPlaneModel.h" #include "PairsimClient.h" Define_Module(PairsimClient); PairsimClient::PairsimClient() { tickTimeout = nullptr; } PairsimClient::~PairsimClient() { cancelAndDelete(tickTimeout); } void PairsimClient::initialize() { tickTimeout = new cMessage("tick"); client.setServerAddr("tcp://localhost:4001"); client.setTickDuration(std::chrono::seconds(1)); client.setModel(std::make_shared<XPlaneModel>(this)); EV << "Setup completed." << std::endl; client.setup(); scheduleAt(simTime() + (static_cast<double>(client.getTickDuration().count())) / 1000, tickTimeout); } void PairsimClient::handleMessage(cMessage *msg) { client.tick(); scheduleAt(simTime() + ((double) client.getTickDuration().count()) / 1000, msg); }
24.625
104
0.694162
Hyodar
9761c71959084ae5a77e0308ba2d9ced7f754c3d
27,752
cpp
C++
stp/sat/Solver.cpp
dslab-epfl/state-merging
abe500674ab3013f266836315e9c4ef18d0fb55c
[ "BSD-3-Clause" ]
null
null
null
stp/sat/Solver.cpp
dslab-epfl/state-merging
abe500674ab3013f266836315e9c4ef18d0fb55c
[ "BSD-3-Clause" ]
null
null
null
stp/sat/Solver.cpp
dslab-epfl/state-merging
abe500674ab3013f266836315e9c4ef18d0fb55c
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************************[Solver.C] MiniSat -- Copyright (c) 2003-2005, Niklas Een, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #include "Solver.h" #include "Sort.h" #include <cmath> namespace MINISAT { //================================================================================================= // Operations on clauses: /*_________________________________________________________________________________________________ | | newClause : (ps : const vec<Lit>&) (learnt : bool) -> [void] | | Description: | Allocate and add a new clause to the SAT solvers clause database. | | Input: | ps - The new clause as a vector of literals. | learnt - Is the clause a learnt clause? For learnt clauses, 'ps[0]' is assumed to be the | asserting literal. An appropriate 'enqueue()' operation will be performed on this | literal. One of the watches will always be on this literal, the other will be set to | the literal with the highest decision level. | | Effect: | Activity heuristics are updated. |________________________________________________________________________________________________@*/ bool Solver::newClause(const vec<Lit>& ps_, bool learnt, bool normalized) { vec<Lit> qs; if (!learnt && !normalized){ assert(decisionLevel() == 0); ps_.copyTo(qs); // Make a copy of the input vector. // Remove duplicates: sortUnique(qs); // Check if clause is satisfied: for (int i = 0; i < qs.size()-1; i++){ if (qs[i] == ~qs[i+1]) return true; } for (int i = 0; i < qs.size(); i++){ if (value(qs[i]) == l_True) return true; } // Remove false literals: int i, j; for (i = j = 0; i < qs.size(); i++) if (value(qs[i]) != l_False) qs[j++] = qs[i]; qs.shrink(i - j); } const vec<Lit>& ps = learnt || normalized ? ps_ : qs; // 'ps' is now the (possibly) reduced vector of literals. if (ps.size() == 0) return false; else if (ps.size() == 1){ assert(decisionLevel() == 0); return enqueue(ps[0]); }else{ // Allocate clause: Clause* c = Clause_new(ps, learnt); if (learnt){ // Put the second watch on the first literal with highest decision level: // (requires that this method is called at the level where the clause is asserting!) int i; for (i = 1; i < ps.size() && position(trailpos[var(ps[i])]) < trail_lim.last(); i++) ; (*c)[1] = ps[i]; (*c)[i] = ps[1]; // Bump, enqueue, store clause: claBumpActivity(*c); // (newly learnt clauses should be considered active) check(enqueue((*c)[0], c)); learnts.push(c); stats.learnts_literals += c->size(); }else{ // Store clause: clauses.push(c); stats.clauses_literals += c->size(); if (subsumption){ c->calcAbstraction(); for (int i = 0; i < c->size(); i++){ assert(!find(occurs[var((*c)[i])], c)); occurs[var((*c)[i])].push(c); n_occ[toInt((*c)[i])]++; touched[var((*c)[i])] = 1; if (heap.inHeap(var((*c)[i]))) updateHeap(var((*c)[i])); } } } // Watch clause: watches[toInt(~(*c)[0])].push(c); watches[toInt(~(*c)[1])].push(c); } return true; } // Disposes a clauses and removes it from watcher lists. NOTE! // Low-level; does NOT change the 'clauses' and 'learnts' vector. // void Solver::removeClause(Clause& c, bool dealloc) { //fprintf(stderr, "delete %d: ", _c); printClause(c); fprintf(stderr, "\n"); assert(c.mark() == 0); if (c.size() > 1){ assert(find(watches[toInt(~c[0])], &c)); assert(find(watches[toInt(~c[1])], &c)); remove(watches[toInt(~c[0])], &c); remove(watches[toInt(~c[1])], &c); } if (c.learnt()) stats.learnts_literals -= c.size(); else stats.clauses_literals -= c.size(); if (subsumption && !c.learnt()){ for (int i = 0; i < c.size(); i++){ if (dealloc){ assert(find(occurs[var(c[i])], &c)); remove(occurs[var(c[i])], &c); } n_occ[toInt(c[i])]--; updateHeap(var(c[i])); } } if (dealloc) xfree(&c); else c.mark(1); } bool Solver::satisfied(Clause& c) const { for (int i = 0; i < c.size(); i++) if (value(c[i]) == l_True) return true; return false; } bool Solver::strengthen(Clause& c, Lit l) { assert(decisionLevel() == 0); assert(c.size() > 1); assert(c.mark() == 0); assert(toInt(~c[0]) < watches.size()); assert(toInt(~c[1]) < watches.size()); assert(find(watches[toInt(~c[0])], &c)); assert(find(watches[toInt(~c[1])], &c)); assert(find(c,l)); if (c.learnt()) stats.learnts_literals -= 1; else stats.clauses_literals -= 1; if (c[0] == l || c[1] == l){ assert(find(watches[toInt(~l)], &c)); remove(c,l); remove(watches[toInt(~l)], &c); if (c.size() > 1){ assert(!find(watches[toInt(~c[1])], &c)); watches[toInt(~c[1])].push(&c); } else { assert(find(watches[toInt(~c[0])], &c)); remove(watches[toInt(~c[0])], &c); removeClause(c, false); } } else remove(c,l); assert(c.size() == 1 || find(watches[toInt(~c[0])], &c)); assert(c.size() == 1 || find(watches[toInt(~c[1])], &c)); if (subsumption){ assert(find(occurs[var(l)], &c)); remove(occurs[var(l)], &c); assert(!find(occurs[var(l)], &c)); c.calcAbstraction(); n_occ[toInt(l)]--; updateHeap(var(l)); } return c.size() == 1 ? enqueue(c[0]) : true; } //================================================================================================= // Minor methods: // Creates a new SAT variable in the solver. If 'decision_var' is cleared, variable will not be // used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result). // Var Solver::newVar(bool polarity, bool dvar) { int index; index = nVars(); watches .push(); // (list for positive literal) watches .push(); // (list for negative literal) reason .push(NULL); assigns .push(toInt(l_Undef)); trailpos .push(TrailPos(0,0)); activity .push(0); order .newVar(polarity,dvar); seen .push(0); touched .push(0); if (subsumption){ occurs .push(); n_occ .push(0); n_occ .push(0); heap .setBounds(index+1); } return index; } // Returns FALSE if immediate conflict. bool Solver::assume(Lit p) { trail_lim.push(trail.size()); return enqueue(p); } // Revert to the state at given level. void Solver::cancelUntil(int level) { if (decisionLevel() > level){ for (int c = trail.size()-1; c >= trail_lim[level]; c--){ Var x = var(trail[c]); assigns[x] = toInt(l_Undef); reason [x] = NULL; order.undo(x); } qhead = trail_lim[level]; trail.shrink(trail.size() - trail_lim[level]); trail_lim.shrink(trail_lim.size() - level); } } //================================================================================================= // Major methods: /*_________________________________________________________________________________________________ | | analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&) -> [void] | | Description: | Analyze conflict and produce a reason clause. | | Pre-conditions: | * 'out_learnt' is assumed to be cleared. | * Current decision level must be greater than root level. | | Post-conditions: | * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'. | | Effect: | Will undo part of the trail, upto but not beyond the assumption of the current decision level. |________________________________________________________________________________________________@*/ void Solver::analyze(Clause* confl, vec<Lit>& out_learnt, int& out_btlevel) { int pathC = 0; int btpos = -1; Lit p = lit_Undef; // Generate conflict clause: // out_learnt.push(); // (leave room for the asserting literal) int index = trail.size()-1; do{ assert(confl != NULL); // (otherwise should be UIP) Clause& c = *confl; if (c.learnt()) claBumpActivity(c); for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){ Lit q = c[j]; if (!seen[var(q)] && position(trailpos[var(q)]) >= trail_lim[0]){ varBumpActivity(q); seen[var(q)] = 1; if (position(trailpos[var(q)]) >= trail_lim.last()) pathC++; else{ out_learnt.push(q); btpos = max(btpos, position(trailpos[var(q)])); } } } // Select next clause to look at: while (!seen[var(trail[index--])]) ; p = trail[index+1]; confl = reason[var(p)]; seen[var(p)] = 0; pathC--; }while (pathC > 0); out_learnt[0] = ~p; // Find correct backtrack level for (out_btlevel = trail_lim.size()-1; out_btlevel > 0 && trail_lim[out_btlevel-1] > btpos; out_btlevel--) ; int i, j; if (expensive_ccmin){ // Simplify conflict clause (a lot): // uint min_level = 0; for (i = 1; i < out_learnt.size(); i++) min_level |= abstractLevel(trailpos[var(out_learnt[i])]); // (maintain an abstraction of levels involved in conflict) out_learnt.copyTo(analyze_toclear); for (i = j = 1; i < out_learnt.size(); i++) if (reason[var(out_learnt[i])] == NULL || !analyze_removable(out_learnt[i], min_level)) out_learnt[j++] = out_learnt[i]; }else{ // Simplify conflict clause (a little): // out_learnt.copyTo(analyze_toclear); for (i = j = 1; i < out_learnt.size(); i++){ Clause& c = *reason[var(out_learnt[i])]; for (int k = 1; k < c.size(); k++) if (!seen[var(c[k])] && position(trailpos[var(c[k])]) >= trail_lim[0]){ out_learnt[j++] = out_learnt[i]; break; } } } stats.max_literals += out_learnt.size(); out_learnt.shrink(i - j); stats.tot_literals += out_learnt.size(); for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared) } // Check if 'p' can be removed. 'min_level' is used to abort early if visiting literals at a level that cannot be removed. // bool Solver::analyze_removable(Lit p, uint min_level) { analyze_stack.clear(); analyze_stack.push(p); int top = analyze_toclear.size(); while (analyze_stack.size() > 0){ assert(reason[var(analyze_stack.last())] != NULL); Clause& c = *reason[var(analyze_stack.last())]; analyze_stack.pop(); for (int i = 1; i < c.size(); i++){ Lit p = c[i]; TrailPos tp = trailpos[var(p)]; if (!seen[var(p)] && position(tp) >= trail_lim[0]){ if (reason[var(p)] != NULL && (abstractLevel(tp) & min_level) != 0){ seen[var(p)] = 1; analyze_stack.push(p); analyze_toclear.push(p); }else{ for (int j = top; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; analyze_toclear.shrink(analyze_toclear.size() - top); return false; } } } } return true; } /*_________________________________________________________________________________________________ | | analyzeFinal : (p : Lit) -> [void] | | Description: | Specialized analysis procedure to express the final conflict in terms of assumptions. | Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and | stores the result in 'out_conflict'. |________________________________________________________________________________________________@*/ void Solver::analyzeFinal(Lit p, vec<Lit>& out_conflict) { out_conflict.clear(); out_conflict.push(p); if (decisionLevel() == 0) return; seen[var(p)] = 1; int start = position(trailpos[var(p)]); for (int i = start; i >= trail_lim[0]; i--){ Var x = var(trail[i]); if (seen[x]){ if (reason[x] == NULL){ assert(position(trailpos[x]) >= trail_lim[0]); out_conflict.push(~trail[i]); }else{ Clause& c = *reason[x]; for (int j = 1; j < c.size(); j++) if (position(trailpos[var(c[j])]) >= trail_lim[0]) seen[var(c[j])] = 1; } seen[x] = 0; } } } /*_________________________________________________________________________________________________ | | enqueue : (p : Lit) (from : Clause*) -> [bool] | | Description: | Puts a new fact on the propagation queue as well as immediately updating the variable's value. | Should a conflict arise, FALSE is returned. | | Input: | p - The fact to enqueue | from - [Optional] Fact propagated from this (currently) unit clause. Stored in 'reason[]'. | Default value is NULL (no reason). | | Output: | TRUE if fact was enqueued without conflict, FALSE otherwise. |________________________________________________________________________________________________@*/ bool Solver::enqueue(Lit p, Clause* from) { if (value(p) != l_Undef) return value(p) != l_False; else{ assigns [var(p)] = toInt(lbool(!sign(p))); trailpos[var(p)] = TrailPos(trail.size(),decisionLevel()); reason [var(p)] = from; trail.push(p); return true; } } /*_________________________________________________________________________________________________ | | propagate : [void] -> [Clause*] | | Description: | Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned, | otherwise NULL. | | Post-conditions: | * the propagation queue is empty, even if there was a conflict. |________________________________________________________________________________________________@*/ Clause* Solver::propagate() { if (decisionLevel() == 0 && subsumption) return backwardSubsumptionCheck() ? NULL : propagate_tmpempty; Clause* confl = NULL; //fprintf(stderr, "propagate, qhead = %d, qtail = %d\n", qhead, qtail); while (qhead < trail.size()){ stats.propagations++; simpDB_props--; Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate. vec<Clause*>& ws = watches[toInt(p)]; Clause **i, **j, **end; for (i = j = (Clause**)ws, end = i + ws.size(); i != end;){ Clause& c = **i++; // Make sure the false literal is data[1]: Lit false_lit = ~p; if (c[0] == false_lit) c[0] = c[1], c[1] = false_lit; assert(c[1] == false_lit); // If 0th watch is true, then clause is already satisfied. Lit first = c[0]; if (value(first) == l_True){ *j++ = &c; }else{ // Look for new watch: for (int k = 2; k < c.size(); k++) if (value(c[k]) != l_False){ c[1] = c[k]; c[k] = false_lit; watches[toInt(~c[1])].push(&c); goto FoundWatch; } // Did not find watch -- clause is unit under assignment: *j++ = &c; if (!enqueue(first, &c)){ confl = &c; qhead = trail.size(); // Copy the remaining watches: while (i < end) *j++ = *i++; } FoundWatch:; } } ws.shrink(i - j); } return confl; } /*_________________________________________________________________________________________________ | | reduceDB : () -> [void] | | Description: | Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked | clauses are clauses that are reason to some assignment. Binary clauses are never removed. |________________________________________________________________________________________________@*/ struct reduceDB_lt { bool operator () (Clause* x, Clause* y) { return x->size() > 2 && (y->size() == 2 || x->activity() < y->activity()); } }; void Solver::reduceDB() { int i, j; double extra_lim = cla_inc / learnts.size(); // Remove any clause below this activity sort(learnts, reduceDB_lt()); for (i = j = 0; i < learnts.size() / 2; i++){ if (learnts[i]->size() > 2 && !locked(*learnts[i])) removeClause(*learnts[i]); else learnts[j++] = learnts[i]; } for (; i < learnts.size(); i++){ if (learnts[i]->size() > 2 && !locked(*learnts[i]) && learnts[i]->activity() < extra_lim) removeClause(*learnts[i]); else learnts[j++] = learnts[i]; } learnts.shrink(i - j); } /*_________________________________________________________________________________________________ | | simplifyDB : [void] -> [bool] | | Description: | Simplify the clause database according to the current top-level assigment. Currently, the only | thing done here is the removal of satisfied clauses, but more things can be put here. |________________________________________________________________________________________________@*/ bool Solver::simplifyDB(bool expensive) { assert(decisionLevel() == 0); if (!ok || propagate() != NULL) return ok = false; if (nAssigns() == simpDB_assigns || (!subsumption && simpDB_props > 0)) // (nothing has changed or preformed a simplification too recently) return true; if (subsumption){ if (expensive && !eliminate()) return ok = false; // Move this cleanup code to its own method ? int i , j; vec<Var> dirty; for (i = 0; i < clauses.size(); i++) if (clauses[i]->mark() == 1){ Clause& c = *clauses[i]; for (int k = 0; k < c.size(); k++) if (!seen[var(c[k])]){ seen[var(c[k])] = 1; dirty.push(var(c[k])); } } for (i = 0; i < dirty.size(); i++){ cleanOcc(dirty[i]); seen[dirty[i]] = 0; } for (i = j = 0; i < clauses.size(); i++) if (clauses[i]->mark() == 1) xfree(clauses[i]); else clauses[j++] = clauses[i]; clauses.shrink(i - j); } // Remove satisfied clauses: for (int type = 0; type < (subsumption ? 1 : 2); type++){ // (only scan learnt clauses if subsumption is on) vec<Clause*>& cs = type ? learnts : clauses; int j = 0; for (int i = 0; i < cs.size(); i++){ assert(cs[i]->mark() == 0); if (satisfied(*cs[i])) removeClause(*cs[i]); else cs[j++] = cs[i]; } cs.shrink(cs.size()-j); } order.cleanup(); simpDB_assigns = nAssigns(); simpDB_props = stats.clauses_literals + stats.learnts_literals; // (shouldn't depend on 'stats' really, but it will do for now) return true; } /*_________________________________________________________________________________________________ | | search : (nof_conflicts : int) (nof_learnts : int) (params : const SearchParams&) -> [lbool] | | Description: | Search for a model the specified number of conflicts, keeping the number of learnt clauses | below the provided limit. NOTE! Use negative value for 'nof_conflicts' or 'nof_learnts' to | indicate infinity. | | Output: | 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If | all variables are decision variables, this means that the clause set is satisfiable. 'l_False' | if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached. |________________________________________________________________________________________________@*/ lbool Solver::search(int nof_conflicts, int nof_learnts) { assert(ok); int backtrack_level; int conflictC = 0; vec<Lit> learnt_clause; stats.starts++; var_decay = 1 / params.var_decay; cla_decay = 1 / params.clause_decay; for (;;){ Clause* confl = propagate(); if (confl != NULL){ // CONFLICT stats.conflicts++; conflictC++; if (decisionLevel() == 0) return l_False; learnt_clause.clear(); analyze(confl, learnt_clause, backtrack_level); cancelUntil(backtrack_level); newClause(learnt_clause, true); varDecayActivity(); claDecayActivity(); }else{ // NO CONFLICT if (nof_conflicts >= 0 && conflictC >= nof_conflicts){ // Reached bound on number of conflicts: progress_estimate = progressEstimate(); cancelUntil(0); return l_Undef; } // Simplify the set of problem clauses: if (decisionLevel() == 0 && !simplifyDB()) return l_False; if (nof_learnts >= 0 && learnts.size()-nAssigns() >= nof_learnts) // Reduce the set of learnt clauses: reduceDB(); Lit next = lit_Undef; if (decisionLevel() < assumptions.size()){ // Perform user provided assumption: next = assumptions[decisionLevel()]; if (value(next) == l_False){ analyzeFinal(~next, conflict); return l_False; } }else{ // New variable decision: stats.decisions++; next = order.select(params.random_var_freq, decisionLevel()); } if (next == lit_Undef) // Model found: return l_True; check(assume(next)); } } } // Return search-space coverage. Not extremely reliable. // double Solver::progressEstimate() { double progress = 0; double F = 1.0 / nVars(); for (int i = 0; i <= decisionLevel(); i++){ int beg = i == 0 ? 0 : trail_lim[i - 1]; int end = i == decisionLevel() ? trail.size() : trail_lim[i]; progress += pow(F, i) * (end - beg); } return progress / nVars(); } // Divide all variable activities by 1e100. // void Solver::varRescaleActivity() { for (int i = 0; i < nVars(); i++) activity[i] *= 1e-100; var_inc *= 1e-100; } // Divide all constraint activities by 1e100. // void Solver::claRescaleActivity() { for (int i = 0; i < learnts.size(); i++) learnts[i]->activity() *= 1e-20; cla_inc *= 1e-20; } /*_________________________________________________________________________________________________ | | solve : (assumps : const vec<Lit>&) -> [bool] | | Description: | Top-level solve. |________________________________________________________________________________________________@*/ bool Solver::solve(const vec<Lit>& assumps) { model.clear(); conflict.clear(); if (!simplifyDB(true)) return false; double nof_conflicts = params.restart_first; double nof_learnts = nClauses() * params.learntsize_factor; lbool status = l_Undef; assumps.copyTo(assumptions); if (verbosity >= 1){ printf("==================================[MINISAT]====================================\n"); printf("| Conflicts | ORIGINAL | LEARNT | Progress |\n"); printf("| | Vars Clauses Literals | Limit Clauses Lit/Cl | |\n"); printf("===============================================================================\n"); } // Search: while (status == l_Undef){ if (verbosity >= 1) //printf("| %9d | %7d %8d | %7d %7d %8d %7.1f | %6.3f %% |\n", (int)stats.conflicts, nClauses(), (int)stats.clauses_literals, (int)nof_learnts, nLearnts(), (int)stats.learnts_literals, (double)stats.learnts_literals/nLearnts(), progress_estimate*100); printf("| %9d | %7d %8d %8d | %8d %8d %6.0f | %6.3f %% |\n", (int)stats.conflicts, order.size(), nClauses(), (int)stats.clauses_literals, (int)nof_learnts, nLearnts(), (double)stats.learnts_literals/nLearnts(), progress_estimate*100); status = search((int)nof_conflicts, (int)nof_learnts); nof_conflicts *= params.restart_inc; nof_learnts *= params.learntsize_inc; } if (verbosity >= 1) { printf("==============================================================================\n"); fflush(stdout); } if (status == l_True){ // Copy model: extendModel(); #if 1 //fprintf(stderr, "Verifying model.\n"); for (int i = 0; i < clauses.size(); i++) assert(satisfied(*clauses[i])); for (int i = 0; i < eliminated.size(); i++) assert(satisfied(*eliminated[i])); #endif model.growTo(nVars()); for (int i = 0; i < nVars(); i++) model[i] = value(i); }else{ assert(status == l_False); if (conflict.size() == 0) ok = false; } cancelUntil(0); return status == l_True; } } //end of MINISAT namespace
34.093366
263
0.543636
dslab-epfl
9765efe8e7544ab882e9e5264173796a133f3e0d
2,114
hpp
C++
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
27
2021-02-15T00:02:12.000Z
2022-03-24T04:34:17.000Z
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
2
2021-02-23T01:04:19.000Z
2022-03-24T04:38:10.000Z
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
1
2022-02-20T09:41:09.000Z
2022-02-20T09:41:09.000Z
#pragma once #include <felspar/coro/coroutine.hpp> namespace felspar::coro { /** * Wait at the suspension point until resumed from an external location. */ class cancellable { coroutine_handle<> continuation = {}; bool signalled = false; void resume_if_needed() { if (continuation) { std::exchange(continuation, {}).resume(); } } public: /// Used externally to cancel the controlled coroutine void cancel() { signalled = true; resume_if_needed(); } bool cancelled() const noexcept { return signalled; } /// Wrap an awaitable so that an early resumption can be signalled template<typename A> auto signal_or(A coro_awaitable) { struct awaitable { A a; cancellable &b; bool await_ready() const noexcept { return b.signalled or a.await_ready(); } auto await_suspend(coroutine_handle<> h) noexcept { /// `h` is the coroutine making use of the `cancellable` b.continuation = h; return a.await_suspend(h); } auto await_resume() -> decltype(std::declval<A>().await_resume()) { if (b.signalled) { return {}; } else { return a.await_resume(); } } }; return awaitable{std::move(coro_awaitable), *this}; } /// This can be directly awaited until signalled auto operator co_await() { struct awaitable { cancellable &b; bool await_ready() const noexcept { return b.signalled; } auto await_suspend(coroutine_handle<> h) noexcept { b.continuation = h; } auto await_resume() noexcept {} }; return awaitable{*this}; } }; }
28.958904
76
0.487228
Felspar
97660134541a53225eb378fe906c3d3842bd97d8
9,027
hpp
C++
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
1,513
2015-01-02T17:36:20.000Z
2022-03-21T00:10:17.000Z
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
335
2015-01-02T21:48:21.000Z
2022-01-31T23:10:46.000Z
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
281
2015-01-08T01:23:41.000Z
2022-03-26T12:31:41.000Z
/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *All rights reserved. * *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF *THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef REDIS_REPLY_HPP_ #define REDIS_REPLY_HPP_ #include "common.hpp" #include "types.hpp" #include <deque> #include <vector> #include <string> #define REDIS_REPLY_STRING 1 #define REDIS_REPLY_ARRAY 2 #define REDIS_REPLY_INTEGER 3 #define REDIS_REPLY_NIL 4 #define REDIS_REPLY_STATUS 5 #define REDIS_REPLY_ERROR 6 #define REDIS_REPLY_DOUBLE 1001 #define FIRST_CHUNK_FLAG 0x01 #define LAST_CHUNK_FLAG 0x02 #define STORAGE_ENGINE_ERR_OFFSET -100000 namespace ardb { namespace codec { enum ErrorCode { //STATUS_OK = 0, ERR_ENTRY_NOT_EXIST = -1000, ERR_INVALID_INTEGER_ARGS = -1001, ERR_INVALID_FLOAT_ARGS = -1002, ERR_INVALID_SYNTAX = -1003, ERR_AUTH_FAILED = -1004, ERR_NOTPERFORMED = -1005, ERR_STRING_EXCEED_LIMIT = -1006, ERR_NOSCRIPT = -1007, ERR_BIT_OFFSET_OUTRANGE = -1008, ERR_BIT_OUTRANGE = -1009, ERR_CORRUPTED_HLL_OBJECT = -1010, ERR_INVALID_HLL_STRING = -1011, ERR_SCORE_NAN = -1012, ERR_EXEC_ABORT = -1013, ERR_UNSUPPORT_DIST_UNIT = -1014, ERR_NOREPLICAS = -1015, ERR_READONLY_SLAVE = -1016, ERR_MASTER_DOWN = -1017, ERR_LOADING = -1018, ERR_NOTSUPPORTED = -1019, ERR_INVALID_ARGS = -1020, ERR_KEY_EXIST = -1021, ERR_WRONG_TYPE = -1022, ERR_OUTOFRANGE = -1023, }; enum StatusCode { STATUS_OK = 1000, STATUS_PONG = 1001, STATUS_QUEUED = 1002, STATUS_NOKEY = 1003, }; struct RedisDumpFileChunk { int64 len; uint32 flag; std::string chunk; RedisDumpFileChunk() : len(0), flag(0) { } bool IsLastChunk() { return (flag & LAST_CHUNK_FLAG) == (LAST_CHUNK_FLAG); } bool IsFirstChunk() { return (flag & FIRST_CHUNK_FLAG) == (FIRST_CHUNK_FLAG); } }; class RedisReplyPool; struct RedisReply { private: public: int type; std::string str; /* * If the type is REDIS_REPLY_STRING, and the str's length is large, * the integer value also used to identify chunk state. */ int64_t integer; std::deque<RedisReply*>* elements; RedisReplyPool* pool; //use object pool if reply is array with hundreds of elements RedisReply(); RedisReply(uint64 v); RedisReply(double v); RedisReply(const std::string& v); bool IsErr() const { return type == REDIS_REPLY_ERROR; } bool IsNil() const { return type == REDIS_REPLY_NIL; } bool IsString() const { return type == REDIS_REPLY_STRING; } bool IsArray() const { return type == REDIS_REPLY_ARRAY; } const std::string& Status(); const std::string& Error(); int64_t ErrCode() const { return integer; } void SetEmpty() { Clear(); type = 0; } double GetDouble(); const std::string& GetString() const { return str; } int64 GetInteger() const { return integer; } void SetDouble(double v); void SetInteger(int64_t v) { type = REDIS_REPLY_INTEGER; integer = v; } void SetString(const Data& v) { Clear(); if (!v.IsNil()) { type = REDIS_REPLY_STRING; v.ToString(str); } } void SetString(const std::string& v) { Clear(); type = REDIS_REPLY_STRING; str = v; } void SetErrCode(int err) { Clear(); type = REDIS_REPLY_ERROR; integer = err; } void SetErrorReason(const std::string& reason) { Clear(); type = REDIS_REPLY_ERROR; str = reason; } void SetStatusCode(int status) { Clear(); type = REDIS_REPLY_STATUS; integer = status; } void SetStatusString(const char* v) { Clear(); type = REDIS_REPLY_STATUS; str.assign(v); } void SetStatusString(const std::string& v) { Clear(); type = REDIS_REPLY_STATUS; str = v; } void SetPool(RedisReplyPool* pool); bool IsPooled() { return pool != NULL; } RedisReply& AddMember(bool tail = true); void ReserveMember(int64_t num); size_t MemberSize(); RedisReply& MemberAt(uint32 i); void Clear(); void Clone(const RedisReply& r) { Clear(); type = r.type; integer = r.integer; str = r.str; if (r.elements != NULL && !r.elements->empty()) { for (uint32 i = 0; i < r.elements->size(); i++) { RedisReply& rr = AddMember(); rr.Clone(*(r.elements->at(i))); } } } virtual ~RedisReply(); }; class RedisReplyPool { private: uint32 m_max_size; uint32 m_cursor; std::vector<RedisReply> elements; std::deque<RedisReply> pending; public: RedisReplyPool(uint32 size = 5); void SetMaxSize(uint32 size); RedisReply& Allocate(); void Clear(); }; typedef std::vector<RedisReply*> RedisReplyArray; void reply_status_string(int code, std::string& str); void reply_error_string(int code, std::string& str); void clone_redis_reply(RedisReply& src, RedisReply& dst); uint64_t living_reply_count(); } } #endif /* REDIS_REPLY_HPP_ */
32.825455
100
0.484657
vorjdux
976af6da8799161d7d6f8e1eb734ed3146607c60
4,092
cc
C++
content/browser/indexed_db/indexed_db_pre_close_task_queue.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/indexed_db/indexed_db_pre_close_task_queue.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/indexed_db/indexed_db_pre_close_task_queue.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/indexed_db_pre_close_task_queue.h" #include <utility> #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/threading/sequenced_task_runner_handle.h" #include "third_party/blink/public/common/indexeddb/indexeddb_metadata.h" #include "third_party/leveldatabase/env_chromium.h" using blink::IndexedDBDatabaseMetadata; namespace content { IndexedDBPreCloseTaskQueue::PreCloseTask::PreCloseTask(leveldb::DB* database) : database_(database) {} IndexedDBPreCloseTaskQueue::PreCloseTask::~PreCloseTask() = default; bool IndexedDBPreCloseTaskQueue::PreCloseTask::RequiresMetadata() const { return false; } void IndexedDBPreCloseTaskQueue::PreCloseTask::SetMetadata( const std::vector<blink::IndexedDBDatabaseMetadata>* metadata) {} IndexedDBPreCloseTaskQueue::IndexedDBPreCloseTaskQueue( std::list<std::unique_ptr<IndexedDBPreCloseTaskQueue::PreCloseTask>> tasks, base::OnceClosure on_complete, base::TimeDelta max_run_time, std::unique_ptr<base::OneShotTimer> timer) : tasks_(std::move(tasks)), on_done_(std::move(on_complete)), timeout_time_(max_run_time), timeout_timer_(std::move(timer)), task_runner_(base::SequencedTaskRunnerHandle::Get()) {} IndexedDBPreCloseTaskQueue::~IndexedDBPreCloseTaskQueue() = default; void IndexedDBPreCloseTaskQueue::StopForNewConnection() { if (!started_ || done_) return; DCHECK(!tasks_.empty()); while (!tasks_.empty()) { tasks_.front()->Stop(StopReason::NEW_CONNECTION); tasks_.pop_front(); } OnComplete(); } void IndexedDBPreCloseTaskQueue::Start(MetadataFetcher metadata_fetcher) { DCHECK(!started_); started_ = true; if (tasks_.empty()) { OnComplete(); return; } timeout_timer_->Start( FROM_HERE, timeout_time_, base::BindOnce(&IndexedDBPreCloseTaskQueue::StopForTimout, ptr_factory_.GetWeakPtr())); metadata_fetcher_ = std::move(metadata_fetcher); task_runner_->PostTask(FROM_HERE, base::BindOnce(&IndexedDBPreCloseTaskQueue::RunLoop, ptr_factory_.GetWeakPtr())); } void IndexedDBPreCloseTaskQueue::OnComplete() { DCHECK(started_); DCHECK(!done_); ptr_factory_.InvalidateWeakPtrs(); timeout_timer_->Stop(); done_ = true; std::move(on_done_).Run(); } void IndexedDBPreCloseTaskQueue::StopForTimout() { DCHECK(started_); if (done_) return; while (!tasks_.empty()) { tasks_.front()->Stop(StopReason::TIMEOUT); tasks_.pop_front(); } OnComplete(); } void IndexedDBPreCloseTaskQueue::StopForMetadataError( const leveldb::Status& status) { if (done_) return; LOCAL_HISTOGRAM_ENUMERATION( "WebCore.IndexedDB.IndexedDBPreCloseTaskList.MetadataError", leveldb_env::GetLevelDBStatusUMAValue(status), leveldb_env::LEVELDB_STATUS_MAX); while (!tasks_.empty()) { tasks_.front()->Stop(StopReason::METADATA_ERROR); tasks_.pop_front(); } OnComplete(); } void IndexedDBPreCloseTaskQueue::RunLoop() { if (done_) return; if (tasks_.empty()) { OnComplete(); return; } PreCloseTask* task = tasks_.front().get(); if (task->RequiresMetadata() && !task->set_metadata_was_called_) { if (!has_metadata_) { leveldb::Status status = std::move(metadata_fetcher_).Run(&metadata_); has_metadata_ = true; if (!status.ok()) { StopForMetadataError(status); return; } } task->SetMetadata(&metadata_); task->set_metadata_was_called_ = true; } bool done = task->RunRound(); if (done) { tasks_.pop_front(); if (tasks_.empty()) { OnComplete(); return; } } task_runner_->PostTask(FROM_HERE, base::BindOnce(&IndexedDBPreCloseTaskQueue::RunLoop, ptr_factory_.GetWeakPtr())); } } // namespace content
28.615385
79
0.695015
sarang-apps
976ba55f7c4e4a84dc80156378219097dd50d09b
952
cpp
C++
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
1
2021-03-15T10:02:10.000Z
2021-03-15T10:02:10.000Z
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
class CombinationIterator { private: int len, mask; string s; public: CombinationIterator(string characters, int combinationLength) : s(characters), len(combinationLength) { mask = (1 << characters.length()) - 1; } string next() { while(mask && __builtin_popcount(mask) != len) { mask--; } string next_combination; for(int i = 0; i < s.length(); i++) { if(mask & (1 << (s.length() - i - 1))) { next_combination.push_back(s[i]); } } mask--; return next_combination; } bool hasNext() { while(mask && __builtin_popcount(mask) != len) { mask--; } return mask; } }; /** * Your CombinationIterator object will be instantiated and called as such: * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); * string param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
28.848485
107
0.578782
ShehabMMohamed
976c95ec96dd46eac812664839e16ac76885907f
1,114
cpp
C++
src/vulkan_helper/image_view.cpp
LesleyLai/Vulkan-Renderer
fd03a69fbc21bfaf3177e43811d21dba634a1949
[ "Apache-2.0" ]
4
2019-04-17T17:44:23.000Z
2020-09-14T04:24:37.000Z
src/vulkan_helper/image_view.cpp
LesleyLai/Vulkan-Renderer
fd03a69fbc21bfaf3177e43811d21dba634a1949
[ "Apache-2.0" ]
3
2020-06-10T00:43:44.000Z
2020-06-10T00:59:47.000Z
src/vulkan_helper/image_view.cpp
LesleyLai/Vulkan-Renderer
fd03a69fbc21bfaf3177e43811d21dba634a1949
[ "Apache-2.0" ]
null
null
null
#include "image_view.hpp" namespace vkh { [[nodiscard]] auto create_image_view(VkDevice device, const ImageViewCreateInfo& image_view_create_info) -> beyond::expected<VkImageView, VkResult> { const VkImageViewCreateInfo create_info = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = image_view_create_info.image, .viewType = image_view_create_info.view_type, .format = image_view_create_info.format, .subresourceRange = image_view_create_info.subresource_range}; VkImageView image_view = nullptr; if (auto res = vkCreateImageView(device, &create_info, nullptr, &image_view); res != VK_SUCCESS) { return beyond::unexpected(res); } return image_view; } [[nodiscard]] auto create_unique_image_view(VkDevice device, const ImageViewCreateInfo& image_view_create_info) -> beyond::expected<UniqueImageView, VkResult> { return create_image_view(device, image_view_create_info) .map([&](VkImageView image_view) { return UniqueImageView(device, image_view); }); } } // namespace vkh
30.108108
79
0.71544
LesleyLai
976ca940c560635702dfc2c725418346a5e9e5de
3,196
cxx
C++
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
1
2022-02-16T03:48:29.000Z
2022-02-16T03:48:29.000Z
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
null
null
null
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Copyright 2011 Emmanuel Christophe Contributed to ORFEO Toolbox under license Apache 2 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Command line: // // ./bin/BaselineComputation ~/project/Images/TSX1_SAR__SSC______HS_S_SRA_20090212T204239_20090212T204240/TSX1_SAR__SSC______HS_S_SRA_20090212T204239_20090212T204240.xml ~/project/Images/TSX1_SAR__SSC______HS_S_SRA_20090223T204240_20090223T204241/TSX1_SAR__SSC______HS_S_SRA_20090223T204240_20090223T204241.xml #include <iomanip> #include "otbImage.h" #include "otbImageFileReader.h" #include "otbBaselineCalculator.h" #include "otbLengthOrientationBaselineFunctor.h" #include "otbPlatformPositionToBaselineCalculator.h" int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " masterImageFile slaveImageFile" << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 2 ; typedef std::complex<double> PixelType; typedef otb::Image<PixelType,Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer master = ReaderType::New(); ReaderType::Pointer slave = ReaderType::New(); master->SetFileName(argv[1]); slave->SetFileName(argv[2]); master->UpdateOutputInformation(); slave->UpdateOutputInformation(); typedef otb::Functor::LengthOrientationBaselineFunctor BaselineFunctorType; typedef otb::BaselineCalculator<BaselineFunctorType> BaselineCalculatorType; typedef BaselineCalculatorType::PlateformPositionToBaselineCalculatorType PlateformPositionToBaselineCalculatorType; BaselineCalculatorType::Pointer baselineCalculator = BaselineCalculatorType::New(); BaselineCalculatorType::PlateformPositionToBaselinePointer plateformPositionToBaseline = PlateformPositionToBaselineCalculatorType::New(); plateformPositionToBaseline->SetMasterPlateform(master->GetOutput()->GetImageKeywordlist()); plateformPositionToBaseline->SetSlavePlateform(slave->GetOutput()->GetImageKeywordlist()); baselineCalculator->SetPlateformPositionToBaselineCalculator(plateformPositionToBaseline); baselineCalculator->Compute(otb::Functor::LengthOrientationBaselineFunctor::Length); double row = 0; double col = 0; std::cout << "(row,col) : " << row << ", " << col << " -> Baseline : "; std::cout << baselineCalculator->EvaluateBaseline(row,col)<< std::endl; row = 1000; col = 1000; std::cout << "(row,col) : " << row << ", " << col << " -> Baseline : "; std::cout << baselineCalculator->EvaluateBaseline(row,col)<< std::endl; }
39.45679
310
0.731852
jmichel-otb
97703f3fa284c9cc26f37748d1b33de03287c40a
211
cpp
C++
Fall-17/CSE/CPP/Assignments/Basic/ASCIIValuesChart.cpp
2Dsharp/college
239fb4c85878f082529a3668544d1ad305b46170
[ "MIT" ]
1
2021-05-18T06:34:53.000Z
2021-05-18T06:34:53.000Z
Fall-17/CSE/CPP/Assignments/Basic/ASCIIValuesChart.cpp
2Dsharp/college
239fb4c85878f082529a3668544d1ad305b46170
[ "MIT" ]
null
null
null
Fall-17/CSE/CPP/Assignments/Basic/ASCIIValuesChart.cpp
2Dsharp/college
239fb4c85878f082529a3668544d1ad305b46170
[ "MIT" ]
1
2018-11-12T16:01:39.000Z
2018-11-12T16:01:39.000Z
#include <iostream> int main(){ std::cout << "ASCII "<< "Representation" << std::endl; for(int i=0;i<=127;i++){ char temp = i; std::cout << i << "\t" << temp << std::endl; } return 0; }
14.066667
56
0.492891
2Dsharp
977424df8367635d711cef34f5ced409cc8ceeca
38,699
cpp
C++
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
114
2017-08-13T22:37:32.000Z
2022-03-25T12:28:39.000Z
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
7
2019-10-14T18:19:11.000Z
2021-06-11T09:41:52.000Z
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
18
2017-08-14T01:22:05.000Z
2022-03-12T12:35:07.000Z
#include <glbinding/gl/functions.h> #include <vector> #include <glbinding/gl/functions-patches.h> namespace gl { void glConvolutionParameteri(GLenum target, GLenum pname, GLenum params) { glConvolutionParameteri(target, pname, static_cast<GLint>(params)); } void glConvolutionParameteriEXT(GLenum target, GLenum pname, GLenum params) { glConvolutionParameteriEXT(target, pname, static_cast<GLint>(params)); } void glFogi(GLenum pname, GLenum param) { glFogi(pname, static_cast<GLint>(param)); } void glFogiv(GLenum pname, const GLenum* params) { glFogiv(pname, reinterpret_cast<const GLint*>(params)); } void glGetBufferParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetBufferParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetBufferParameterivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetBufferParameterivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetBufferParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetBufferParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetBufferParameterivARB(GLenum target, GLenum pname, GLenum* params) { glGetBufferParameterivARB(target, pname, reinterpret_cast<GLint*>(params)); } void glGetConvolutionParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetConvolutionParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetConvolutionParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetConvolutionParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetIntegerv(GLenum pname, GLenum* data) { glGetIntegerv(pname, reinterpret_cast<GLint*>(data)); } void glGetIntegeri_v(GLenum target, GLuint index, GLenum* data) { glGetIntegeri_v(target, index, reinterpret_cast<GLint*>(data)); } void glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLenum* params) { glGetFramebufferAttachmentParameteriv(target, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetFramebufferAttachmentParameterivEXT(GLenum target, GLenum attachment, GLenum pname, GLenum* params) { glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetFramebufferParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetFramebufferParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetFramebufferParameterivEXT(GLuint framebuffer, GLenum pname, GLboolean* params) { GLint params_; glGetFramebufferParameterivEXT(framebuffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetMinmaxParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetMinmaxParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetMinmaxParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetMinmaxParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedBufferParameteriv(GLuint buffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedBufferParameteriv(buffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedBufferParameterivEXT(GLuint buffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedBufferParameterivEXT(buffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedBufferParameteriv(GLuint buffer, GLenum pname, GLenum* params) { glGetNamedBufferParameteriv(buffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedBufferParameterivEXT(GLuint buffer, GLenum pname, GLenum* params) { glGetNamedBufferParameterivEXT(buffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferAttachmentParameteriv(GLuint framebuffer, GLenum attachment, GLenum pname, GLenum* params) { glGetNamedFramebufferAttachmentParameteriv(framebuffer, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferAttachmentParameterivEXT(GLuint framebuffer, GLenum attachment, GLenum pname, GLenum* params) { glGetNamedFramebufferAttachmentParameterivEXT(framebuffer, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferParameteriv(GLuint framebuffer, GLenum pname, GLboolean* param) { GLint params_; glGetNamedFramebufferParameteriv(framebuffer, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedFramebufferParameterivEXT(GLuint framebuffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedFramebufferParameterivEXT(framebuffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedProgramivEXT(GLuint program, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetNamedProgramivEXT(program, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedProgramivEXT(GLuint program, GLenum target, GLenum pname, GLenum* params) { glGetNamedProgramivEXT(program, target, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedRenderbufferParameteriv(GLuint renderbuffer, GLenum pname, GLenum* params) { glGetNamedRenderbufferParameteriv(renderbuffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedRenderbufferParameterivEXT(GLuint renderbuffer, GLenum pname, GLenum* params) { glGetNamedRenderbufferParameterivEXT(renderbuffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedStringivARB(GLint namelen, const GLchar* name, GLenum pname, GLenum* params) { glGetNamedStringivARB(namelen, name, pname, reinterpret_cast<GLint*>(params)); } void glGetObjectParameterivARB(GLhandleARB obj, GLenum pname, GLboolean* params) { GLint params_; glGetObjectParameterivARB(obj, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetObjectParameterivARB(GLhandleARB obj, GLenum pname, GLenum* params) { glGetObjectParameterivARB(obj, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramiv(GLuint program, GLenum pname, GLboolean* params) { GLint params_; glGetProgramiv(program, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetProgramivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetProgramivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetProgramiv(GLuint program, GLenum pname, GLenum* params) { glGetProgramiv(program, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramivARB(GLenum target, GLenum pname, GLenum* params) { glGetProgramivARB(target, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum* props, GLsizei bufSize, GLsizei* length, GLenum* params) { glGetProgramResourceiv(program, programInterface, index, propCount, props, bufSize, length, reinterpret_cast<GLint*>(params)); } void glGetQueryIndexediv(GLenum target, GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetQueryIndexediv(target, index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryObjectiv(GLuint id, GLenum pname, GLboolean* params) { GLint params_; glGetQueryObjectiv(id, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryObjectivARB(GLuint id, GLenum pname, GLboolean* params) { GLint params_; glGetQueryObjectivARB(id, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryiv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetQueryiv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetQueryivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetRenderbufferParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetRenderbufferParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetRenderbufferParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetSamplerParameterIiv(GLuint sampler, GLenum pname, GLenum* params) { glGetSamplerParameterIiv(sampler, pname, reinterpret_cast<GLint*>(params)); } void glGetSamplerParameteriv(GLuint sampler, GLenum pname, GLenum* params) { glGetSamplerParameteriv(sampler, pname, reinterpret_cast<GLint*>(params)); } void glGetShaderiv(GLuint shader, GLenum pname, GLboolean* params) { GLint params_; glGetShaderiv(shader, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetShaderiv(GLuint shader, GLenum pname, GLenum* params) { glGetShaderiv(shader, pname, reinterpret_cast<GLint*>(params)); } void glGetTexEnviv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexEnviv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexEnviv(GLenum target, GLenum pname, GLenum* params) { glGetTexEnviv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexGeniv(GLenum coord, GLenum pname, GLenum* params) { glGetTexGeniv(coord, pname, reinterpret_cast<GLint*>(params)); } void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTexLevelParameteriv(target, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLenum* params) { glGetTexLevelParameteriv(target, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameterIiv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameterIiv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameterIivEXT(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameterIivEXT(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameterIiv(GLenum target, GLenum pname, GLenum* params) { glGetTexParameterIiv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameterIivEXT(GLenum target, GLenum pname, GLenum* params) { glGetTexParameterIivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetTexParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureLevelParameteriv(GLuint texture, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTextureLevelParameteriv(texture, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureLevelParameterivEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTextureLevelParameterivEXT(texture, target, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureLevelParameteriv(GLuint texture, GLint level, GLenum pname, GLenum* params) { glGetTextureLevelParameteriv(texture, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureLevelParameterivEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLenum* params) { glGetTextureLevelParameterivEXT(texture, target, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterIiv(GLuint texture, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterIiv(texture, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterIivEXT(texture, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameteriv(GLuint texture, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameteriv(texture, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterivEXT(texture, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterIiv(GLuint texture, GLenum pname, GLenum* params) { glGetTextureParameterIiv(texture, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, GLenum* params) { glGetTextureParameterIivEXT(texture, target, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameteriv(GLuint texture, GLenum pname, GLenum* params) { glGetTextureParameteriv(texture, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, GLenum* params) { glGetTextureParameterivEXT(texture, target, pname, reinterpret_cast<GLint*>(params)); } void glGetTransformFeedbackiv(GLuint xfb, GLenum pname, GLboolean* param) { GLint params_; glGetTransformFeedbackiv(xfb, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexArrayIndexediv(GLuint vaobj, GLuint index, GLenum pname, GLboolean* param) { GLint params_; glGetVertexArrayIndexediv(vaobj, index, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexArrayIndexediv(GLuint vaobj, GLuint index, GLenum pname, GLenum* param) { glGetVertexArrayIndexediv(vaobj, index, pname, reinterpret_cast<GLint*>(param)); } void glGetVertexAttribIiv(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribIiv(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribIivEXT(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribIivEXT(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribiv(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribiv(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribivARB(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribivARB(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribIiv(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribIiv(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribIivEXT(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribIivEXT(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribiv(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribiv(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribivARB(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribivARB(index, pname, reinterpret_cast<GLint*>(params)); } void glLightModeli(GLenum pname, GLenum param) { glLightModeli(pname, static_cast<GLint>(param)); } void glLightModeliv(GLenum pname, const GLenum* params) { glLightModeliv(pname, reinterpret_cast<const GLint*>(params)); } void glMultiTexImage1DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage1DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glMultiTexImage2DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage2DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glMultiTexImage3DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage3DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glNamedFramebufferParameteri(GLuint framebuffer, GLenum pname, GLboolean param) { glNamedFramebufferParameteri(framebuffer, pname, static_cast<GLint>(param)); } void glNamedFramebufferParameteriEXT(GLuint framebuffer, GLenum pname, GLboolean param) { glNamedFramebufferParameteriEXT(framebuffer, pname, static_cast<GLint>(param)); } void glPixelStorei(GLenum pname, GLboolean param) { glPixelStorei(pname, static_cast<GLint>(param)); } void glPixelTransferi(GLenum pname, GLboolean param) { glPixelTransferi(pname, static_cast<GLint>(param)); } void glPointParameteri(GLenum pname, GLenum param) { glPointParameteri(pname, static_cast<GLint>(param)); } void glPointParameteriv(GLenum pname, const GLenum* params) { glPointParameteriv(pname, reinterpret_cast<const GLint*>(params)); } void glProgramParameteri(GLuint program, GLenum pname, GLboolean value) { glProgramParameteri(program, pname, static_cast<GLint>(value)); } void glProgramParameteriARB(GLuint program, GLenum pname, GLboolean value) { glProgramParameteriARB(program, pname, static_cast<GLint>(value)); } void glProgramParameteriEXT(GLuint program, GLenum pname, GLboolean value) { glProgramParameteriEXT(program, pname, static_cast<GLint>(value)); } void glProgramUniform1i(GLuint program, GLint location, GLboolean v0) { glProgramUniform1i(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iEXT(GLuint program, GLint location, GLboolean v0) { glProgramUniform1iEXT(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform1iv(program, location, count, data.data()); } void glProgramUniform1ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform1ivEXT(program, location, count, data.data()); } void glProgramUniform2i(GLuint program, GLint location, GLboolean v0, GLboolean v1) { glProgramUniform2i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1) { glProgramUniform2iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform2iv(program, location, count, data.data()); } void glProgramUniform2ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform2ivEXT(program, location, count, data.data()); } void glProgramUniform3i(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glProgramUniform3i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glProgramUniform3iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform3iv(program, location, count, data.data()); } void glProgramUniform3ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform3ivEXT(program, location, count, data.data()); } void glProgramUniform4i(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glProgramUniform4i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glProgramUniform4iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform4iv(program, location, count, data.data()); } void glProgramUniform4ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform4ivEXT(program, location, count, data.data()); } void glProgramUniform1i(GLuint program, GLint location, GLenum v0) { glProgramUniform1i(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iEXT(GLuint program, GLint location, GLenum v0) { glProgramUniform1iEXT(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform1iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform1ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform1ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform2i(GLuint program, GLint location, GLenum v0, GLenum v1) { glProgramUniform2i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iEXT(GLuint program, GLint location, GLenum v0, GLenum v1) { glProgramUniform2iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform2iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform2ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform2ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform3i(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2) { glProgramUniform3i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iEXT(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2) { glProgramUniform3iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform3iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform3ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform3ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform4i(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glProgramUniform4i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iEXT(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glProgramUniform4iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform4iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform4ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform4ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glSamplerParameterIiv(GLuint sampler, GLenum pname, const GLenum* param) { glSamplerParameterIiv(sampler, pname, reinterpret_cast<const GLint*>(param)); } void glSamplerParameteri(GLuint sampler, GLenum pname, GLenum param) { glSamplerParameteri(sampler, pname, static_cast<GLint>(param)); } void glSamplerParameteriv(GLuint sampler, GLenum pname, const GLenum* param) { glSamplerParameteriv(sampler, pname, reinterpret_cast<const GLint*>(param)); } void glTexEnvi(GLenum target, GLenum pname, GLboolean param) { glTexEnvi(target, pname, static_cast<GLint>(param)); } void glTexEnviv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexEnviv(target, pname, &params_); } void glTexEnvi(GLenum target, GLenum pname, GLenum param) { glTexEnvi(target, pname, static_cast<GLint>(param)); } void glTexEnviv(GLenum target, GLenum pname, const GLenum* params) { glTexEnviv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexGeni(GLenum coord, GLenum pname, GLenum param) { glTexGeni(coord, pname, static_cast<GLint>(param)); } void glTexGeniv(GLenum coord, GLenum pname, const GLenum* params) { glTexGeniv(coord, pname, reinterpret_cast<const GLint*>(params)); } void glTexImage1D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage1D(target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage2D(target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage3D(target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glTextureImage1DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage1DEXT(texture, target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glTextureImage2DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage2DEXT(texture, target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glTextureImage3DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage3DEXT(texture, target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glTexParameterIiv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameterIiv(target, pname, &params_); } void glTexParameterIivEXT(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameterIivEXT(target, pname, &params_); } void glTexParameteri(GLenum target, GLenum pname, GLboolean param) { glTexParameteri(target, pname, static_cast<GLint>(param)); } void glTexParameteriv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameteriv(target, pname, &params_); } void glTexParameterIiv(GLenum target, GLenum pname, const GLenum* params) { glTexParameterIiv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexParameterIivEXT(GLenum target, GLenum pname, const GLenum* params) { glTexParameterIivEXT(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexParameteri(GLenum target, GLenum pname, GLenum param) { glTexParameteri(target, pname, static_cast<GLint>(param)); } void glTexParameteriv(GLenum target, GLenum pname, const GLenum* params) { glTexParameteriv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameterIiv(GLuint texture, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterIiv(texture, pname, &params_); } void glTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterIivEXT(texture, target, pname, &params_); } void glTextureParameteri(GLuint texture, GLenum pname, GLboolean param) { glTextureParameteri(texture, pname, static_cast<GLint>(param)); } void glTextureParameteriEXT(GLuint texture, GLenum target, GLenum pname, GLboolean param) { glTextureParameteriEXT(texture, target, pname, static_cast<GLint>(param)); } void glTextureParameteriv(GLuint texture, GLenum pname, const GLboolean* param) { GLint params_ = static_cast<GLint>(param[0]); glTextureParameteriv(texture, pname, &params_); } void glTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterivEXT(texture, target, pname, &params_); } void glTextureParameterIiv(GLuint texture, GLenum pname, const GLenum* params) { glTextureParameterIiv(texture, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, const GLenum* params) { glTextureParameterIivEXT(texture, target, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameteri(GLuint texture, GLenum pname, GLenum param) { glTextureParameteri(texture, pname, static_cast<GLint>(param)); } void glTextureParameteriEXT(GLuint texture, GLenum target, GLenum pname, GLenum param) { glTextureParameteriEXT(texture, target, pname, static_cast<GLint>(param)); } void glTextureParameteriv(GLuint texture, GLenum pname, const GLenum* param) { glTextureParameteriv(texture, pname, reinterpret_cast<const GLint*>(param)); } void glTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, const GLenum* params) { glTextureParameterivEXT(texture, target, pname, reinterpret_cast<const GLint*>(params)); } void glUniform1i(GLint location, GLboolean v0) { glUniform1i(location, static_cast<GLint>(v0)); } void glUniform1iARB(GLint location, GLboolean v0) { glUniform1iARB(location, static_cast<GLint>(v0)); } void glUniform1iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform1iv(location, count, data.data()); } void glUniform1ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform1ivARB(location, count, data.data()); } void glUniform2i(GLint location, GLboolean v0, GLboolean v1) { glUniform2i(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iARB(GLint location, GLboolean v0, GLboolean v1) { glUniform2iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform2iv(location, count, data.data()); } void glUniform2ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform2ivARB(location, count, data.data()); } void glUniform3i(GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glUniform3i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iARB(GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glUniform3iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform3iv(location, count, data.data()); } void glUniform3ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform3ivARB(location, count, data.data()); } void glUniform4i(GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glUniform4i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iARB(GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glUniform4iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform4iv(location, count, data.data()); } void glUniform4ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform4ivARB(location, count, data.data()); } void glUniform1i(GLint location, GLenum v0) { glUniform1i(location, static_cast<GLint>(v0)); } void glUniform1iARB(GLint location, GLenum v0) { glUniform1iARB(location, static_cast<GLint>(v0)); } void glUniform1iv(GLint location, GLsizei count, const GLenum* value) { glUniform1iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform1ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform1ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform2i(GLint location, GLenum v0, GLenum v1) { glUniform2i(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iARB(GLint location, GLenum v0, GLenum v1) { glUniform2iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iv(GLint location, GLsizei count, const GLenum* value) { glUniform2iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform2ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform2ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform3i(GLint location, GLenum v0, GLenum v1, GLenum v2) { glUniform3i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iARB(GLint location, GLenum v0, GLenum v1, GLenum v2) { glUniform3iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iv(GLint location, GLsizei count, const GLenum* value) { glUniform3iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform3ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform3ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform4i(GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glUniform4i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iARB(GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glUniform4iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iv(GLint location, GLsizei count, const GLenum* value) { glUniform4iv(location, count, reinterpret_cast<const GLint*>(value)); } } // namespace gl
29.86034
120
0.733404
no33fewi
97747fcdd08eedf08f3e44b1c0025a9411d18f4a
9,657
cpp
C++
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
40
2016-11-18T06:14:47.000Z
2022-03-16T14:36:21.000Z
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
null
null
null
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
9
2017-01-23T01:49:41.000Z
2020-11-05T13:09:56.000Z
/** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka <uiii.dev@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "actionForm.hpp" #include <QHBoxLayout> #include <QVBoxLayout> #include <QLabel> #include <QStackedWidget> #include "keyboard.hpp" #include "mouse.hpp" #include "system.hpp" Q_DECLARE_METATYPE(FakeInput::KeyType); Q_DECLARE_METATYPE(FakeInput::MouseButton); Q_ENUMS(FakeInput::KeyType); Q_ENUMS(FakeInput::MouseButton); ActionForm::ActionForm(QWidget* parent): QWidget(parent) { QVBoxLayout* vbox = new QVBoxLayout(this); actionType_ = new QComboBox(this); actionType_->addItem("press & release key"); actionType_->addItem("click mouse button"); actionType_->addItem("move mouse"); actionType_->addItem("rotate wheel"); actionType_->addItem("run command"); actionType_->addItem("wait"); QWidget* keyOptions_ = new QWidget(); QWidget* mouseButtonOptions_ = new QWidget(); QWidget* mouseMotionOptions_ = new QWidget(); QWidget* mouseWheelOptions_ = new QWidget(); QWidget* commandOptions_ = new QWidget(); QWidget* waitOptions_ = new QWidget(); QHBoxLayout* keyHBox = new QHBoxLayout(); QHBoxLayout* mouseButtonHBox = new QHBoxLayout(); QHBoxLayout* mouseMotionHBox = new QHBoxLayout(); QHBoxLayout* mouseWheelHBox = new QHBoxLayout(); QHBoxLayout* commandHBox = new QHBoxLayout(); QHBoxLayout* waitHBox = new QHBoxLayout(); keySelector_ = new QComboBox(); keySelector_->addItem("A", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_A)); keySelector_->addItem("B", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_B)); keySelector_->addItem("C", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_C)); keySelector_->addItem("D", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_D)); keySelector_->addItem("E", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_E)); keySelector_->addItem("F", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_F)); keySelector_->addItem("G", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_G)); keySelector_->addItem("H", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_H)); keySelector_->addItem("I", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_I)); keySelector_->addItem("J", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_J)); keySelector_->addItem("K", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_K)); keySelector_->addItem("L", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_L)); keySelector_->addItem("M", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_M)); keySelector_->addItem("N", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_N)); keySelector_->addItem("O", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_O)); keySelector_->addItem("P", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_P)); keySelector_->addItem("Q", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Q)); keySelector_->addItem("R", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_R)); keySelector_->addItem("S", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_S)); keySelector_->addItem("T", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_T)); keySelector_->addItem("U", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_U)); keySelector_->addItem("V", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_V)); keySelector_->addItem("W", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_W)); keySelector_->addItem("X", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_X)); keySelector_->addItem("Y", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Y)); keySelector_->addItem("Z", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Z)); mouseButtonSelector_ = new QComboBox(); mouseButtonSelector_->addItem("Left", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Left)); mouseButtonSelector_->addItem("Middle", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Middle)); mouseButtonSelector_->addItem("Right", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Right)); QLabel* xLabel = new QLabel("dx: "); QLabel* yLabel = new QLabel("dy: "); mouseMotionX_ = new QSpinBox(); mouseMotionX_->setSingleStep(50); mouseMotionX_->setMinimum(-10000); mouseMotionX_->setMaximum(10000); mouseMotionY_ = new QSpinBox(); mouseMotionY_->setSingleStep(50); mouseMotionY_->setMinimum(-10000); mouseMotionY_->setMaximum(10000); mouseWheelDirection_ = new QComboBox(); mouseWheelDirection_->addItem("Up"); mouseWheelDirection_->addItem("Down"); command_ = new QLineEdit(); QLabel* timeLabel = new QLabel("miliseconds: "); waitTime_ = new QSpinBox(); waitTime_->setSingleStep(50); waitTime_->setMaximum(10000); keyHBox->addWidget(keySelector_); mouseButtonHBox->addWidget(mouseButtonSelector_); mouseMotionHBox->addWidget(xLabel); mouseMotionHBox->addWidget(mouseMotionX_); mouseMotionHBox->addWidget(yLabel); mouseMotionHBox->addWidget(mouseMotionY_); mouseWheelHBox->addWidget(mouseWheelDirection_); commandHBox->addWidget(command_); waitHBox->addWidget(timeLabel); waitHBox->addWidget(waitTime_); keyOptions_->setLayout(keyHBox); mouseButtonOptions_->setLayout(mouseButtonHBox); mouseMotionOptions_->setLayout(mouseMotionHBox); mouseWheelOptions_->setLayout(mouseWheelHBox); commandOptions_->setLayout(commandHBox); waitOptions_->setLayout(waitHBox); QStackedWidget* stack = new QStackedWidget(this); stack->addWidget(keyOptions_); stack->addWidget(mouseButtonOptions_); stack->addWidget(mouseMotionOptions_); stack->addWidget(mouseWheelOptions_); stack->addWidget(commandOptions_); stack->addWidget(waitOptions_); vbox->addWidget(actionType_); vbox->addWidget(stack); vbox->addStretch(1); setLayout(vbox); connect(actionType_, SIGNAL(currentIndexChanged(int)), stack, SLOT(setCurrentIndex(int))); } QString ActionForm::addActionToSequence(FakeInput::ActionSequence& sequence) { QString infoText = ""; switch(actionType_->currentIndex()) { case 0: { FakeInput::KeyType keyType = keySelector_->itemData(keySelector_->currentIndex()).value<FakeInput::KeyType>(); FakeInput::Key key(keyType); sequence.press(key).release(key); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(key.name().c_str()); break; } case 1: { FakeInput::MouseButton mouseButton = mouseButtonSelector_ ->itemData(mouseButtonSelector_->currentIndex()) .value<FakeInput::MouseButton>(); sequence.press(mouseButton).release(mouseButton); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(mouseButtonSelector_->currentText()); break; } case 2: { sequence.moveMouse( mouseMotionX_->text().toInt(), mouseMotionY_->text().toInt() ); infoText = actionType_->currentText(); infoText.append(": [ dx: "); infoText.append(mouseMotionX_->text()); infoText.append(" ; dy: "); infoText.append(mouseMotionY_->text()); infoText.append(" ]"); break; } case 3: { infoText = actionType_->currentText(); infoText.append(": "); if(mouseWheelDirection_->currentIndex() == 0) { sequence.wheelUp(); infoText.append("Up"); } else { sequence.wheelDown(); infoText.append("Down"); } break; } case 4: { sequence.runCommand(command_->text().toAscii().data()); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(command_->text()); break; } case 5: { sequence.wait(waitTime_->text().toInt()); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(waitTime_->text()); break; } default: break; } return infoText; }
40.57563
122
0.678264
perara-libs
977517e8392b771d384ba89083fc3b3c82cb0e5d
1,058
cpp
C++
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
joakimthun/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
16
2015-10-12T14:24:45.000Z
2021-07-20T01:56:04.000Z
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
null
null
null
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
2
2017-11-12T01:39:09.000Z
2021-07-20T01:56:09.000Z
#include "array_initializer_list_expression_builder.h" #include "../vm_expression_visitor.h" namespace elsa { namespace compiler { void ArrayInitializerListExpressionBuilder::build(VMProgram* program, VMExpressionVisitor* visitor, ArrayInitializerListExpression* expression) { program->emit(OpCode::iconst); auto size = expression->get_values().size(); program->emit(static_cast<int>(size)); program->emit(OpCode::new_arr); auto type = expression->get_type()->get_struct_declaration_expression()->get_generic_type(); program->emit(static_cast<int>(type->get_vm_type())); auto local_index = visitor->current_scope()->create_new_local(); program->emit(OpCode::s_local); program->emit(static_cast<int>(local_index)); for (const auto& exp : expression->get_values()) { program->emit(OpCode::l_local); program->emit(static_cast<int>(local_index)); exp->accept(visitor); program->emit(OpCode::a_ele); } program->emit(OpCode::l_local); program->emit(static_cast<int>(local_index)); } } }
27.128205
145
0.721172
joakimthun
977b9dcb68ea985497728997aedecb96580026b4
8,291
cpp
C++
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
#include<iostream> #include "solver.hpp" using namespace solver; using namespace std; double RealVariable::solveEquation(RealVariable& eq){ if(eq.a==0 && eq.b==0) throw std::exception(); if(!eq.power){ return -eq.c/eq.b; } else{ double SquareRoot = eq.b*eq.b - 4*eq.a*eq.c; double solveEq; if(SquareRoot>=0) { solveEq = (-eq.b + sqrt(SquareRoot)) / (2*eq.a); } else { throw std::exception(); } return solveEq; } } double solver::solve(RealVariable& eq){ return eq.solveEquation(eq); } RealVariable& RealVariable::copy (RealVariable& rv){ this->a=rv.a; this->b=rv.b; this->c=rv.c; this->power=rv.power; return *this; } //opertor + RealVariable& solver::operator+ (RealVariable& rv , double num){ RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); rvCopy->c=rv.c+num; return *rvCopy; } RealVariable& solver::operator+ (double num , RealVariable& rv){ return (rv + num); } RealVariable& solver::operator+ (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy=new RealVariable(); rvCopy->a=rv1.a+rv2.a; rvCopy->b=rv1.b+rv2.b; rvCopy->c=rv1.c+rv2.c; rvCopy->power= rv1.power? rv1.power : rv2.power; return *rvCopy; } //opertor - RealVariable& solver::operator- (RealVariable& rv , double num){ RealVariable* rvCopy=new RealVariable(); rvCopy->copy(rv); rvCopy->c=rv.c-num; return *rvCopy; } RealVariable& solver::operator- (double num , RealVariable& rv){ return (rv - num); } RealVariable& solver::operator- (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy=new RealVariable(); rvCopy->a=rv1.a-rv2.a; rvCopy->b=rv1.b-rv2.b; rvCopy->c=rv1.c-rv2.c; rvCopy->power = rv1.power ? rv1.power : rv2.power; return *rvCopy; } //opertor * RealVariable& solver::operator* (RealVariable& rv , double num){ return (num * rv); } RealVariable& solver::operator* (double num , RealVariable& rv){ cout<< "op * : a=" << rv.a <<" b=" << rv.b <<"c="<<rv.c<<endl; RealVariable* rvCopy=new RealVariable(); rvCopy->copy(rv); if(rv.power) { rvCopy->a*=num; } else if(rv.b==0){ rvCopy->b=num; } else rvCopy->b*=num; return *rvCopy; } RealVariable& solver::operator* (RealVariable& rv1 , RealVariable& rv2){ if(rv1.power || rv2.power) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv1); if(rv1.a != 0 && rv2.a !=0) rvCopy->a=rv1.a*rv2.a; rvCopy->a=rv1.a+rv2.a; rvCopy->power=true; return *rvCopy; } //opertor / RealVariable& solver::operator/ (RealVariable& rv , double num){ if(num==0) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->a=rv.a/num; rvCopy->b=rv.b/num; rvCopy->c=rv.c/num; rvCopy->power=rv.power; return *rvCopy; } RealVariable& solver::operator/ (double num , RealVariable& rv){ RealVariable *rvCopy= new RealVariable(); rvCopy->a=num/rv.a; rvCopy->b=num/rv.b; rvCopy->c=num/rv.c; rvCopy->power=rv.power; return *rvCopy; } //operator ^ RealVariable& solver::operator^ (RealVariable& rv, const int num){ if (num != 2 || rv.power) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); rvCopy->a=rv.b; rvCopy->power=true; rvCopy->b=0; return *rvCopy; } //opertor == RealVariable& solver::operator== (RealVariable& rv , double num){ RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); if(num>0) rvCopy->c-=num; else rvCopy->c+=-num; return *rvCopy; } RealVariable& solver::operator== (double num , RealVariable& rv){ cout<< "operator ==: a=" << rv.a << "b=" <<rv.b <<"c=" << rv.c<< endl; return (rv == num); } RealVariable& solver::operator== (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy = new RealVariable(); *rvCopy=rv1-rv2; return *rvCopy; } //complex variable std::complex<double> ComplexVariable::solveEquation(ComplexVariable& eq){ if(eq.a==std::complex<double>(0.0,0.0) && eq.b==std::complex<double>(0.0,0.0)) throw std::exception(); if(!eq.power){ return -eq.c/eq.b; } if (eq.b==std::complex<double>(0.0,0.0) && power){ std::complex<double> c=-eq.c/eq.a; return sqrt(c); } else{ std::complex<double> SquareRoot = sqrt(eq.b*eq.b - 4.0 *eq.a*eq.c); std::complex<double> solveEq= (-eq.b + SquareRoot) / (2.0*eq.a); return solveEq; } } std::complex<double> solver::solve(ComplexVariable& eq){ return eq.solveEquation(eq); } ComplexVariable& ComplexVariable::copy (ComplexVariable& cv){ this->a=cv.a; this->b=cv.b; this->c=cv.c; this->power=cv.power; return *this; } //operator + ComplexVariable& solver::operator+ (ComplexVariable& cv , complex<double> num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->c=cv.c+num; return *cvCopy; } ComplexVariable& solver::operator+ (complex<double> num, ComplexVariable& cv ){ return (cv + num); } ComplexVariable& solver::operator+ (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->a=cv1.a+cv2.a; cvCopy->b=cv1.b+cv2.b; cvCopy->c=cv1.c+cv2.c; cvCopy->power=cv1.power? cv1.power : cv2.power; return *cvCopy; } //operator - ComplexVariable& solver::operator- (ComplexVariable& cv , complex<double> num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->c=cv.c-num; return *cvCopy; } ComplexVariable& solver::operator- (complex<double> num, ComplexVariable& cv ){ return (cv - num); } ComplexVariable& solver::operator- (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->a=cv1.a-cv2.a; cvCopy->b=cv1.b-cv2.b; cvCopy->c=cv1.c-cv2.c; cvCopy->power = cv1.power ? cv1.power : cv2.power; return *cvCopy; } //operator * ComplexVariable& solver::operator* (ComplexVariable& cv1, ComplexVariable& cv2 ){ if(cv1.power || cv2.power) throw std::exception(); ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv1); if(cv1.a != std::complex(0.0,0.0) && cv2.a !=std::complex(0.0,0.0)) cvCopy->a=cv1.a*cv2.a; cvCopy->a=cv1.a+cv2.a; cvCopy->power=true; return *cvCopy; } ComplexVariable& solver::operator* (complex<double> c , ComplexVariable& cv ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->copy(cv); if(cv.power) { cvCopy->a*=c; } else if(cv.b==std::complex(0.0,0.0)){ cvCopy->b=c; } else cvCopy->b*=c; return *cvCopy; } ComplexVariable& solver::operator* (ComplexVariable& cv , complex<double> c ){ return (c * cv); } //operator / ComplexVariable& solver::operator/ (complex<double> c , ComplexVariable& cv ){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->a=c/cv.a; cvCopy->b=c/cv.b; cvCopy->c=c/cv.c; cvCopy->power=cv.power; return *cvCopy; } ComplexVariable& solver::operator/ (ComplexVariable& cv , complex<double> c ){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->a=cv.a/c; cvCopy->b=cv.b/c; cvCopy->c=cv.c/c; cvCopy->power=cv.power; return *cvCopy; } ComplexVariable& solver::operator^ (ComplexVariable& cv, const int num){ if (num != 2) throw std::exception(); ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->a=cv.b; cvCopy->b=std::complex<double>(0.0,0.0);; cvCopy->power=true; return *cvCopy; } //operator == ComplexVariable& solver::operator== (ComplexVariable& cv , double num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); if(num>0) cvCopy->c-=num; else cvCopy->c+=-num; return *cvCopy; } ComplexVariable& solver::operator== (double num, ComplexVariable& cv ){ return (cv == num); } ComplexVariable& solver::operator== (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy = new ComplexVariable(); *cvCopy=cv1-cv2; return *cvCopy; }
25.589506
102
0.624894
sapirp
977fc28e9f8f2c462a97235442bee7fc1b39503f
1,523
cpp
C++
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
2
2022-03-23T12:16:20.000Z
2022-03-31T06:19:40.000Z
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper, NaClSubprocess* subprocess, const Manifest* manifest, bool should_report_uma, ErrorInfo* error_info, pp::CompletionCallback init_done_cb, pp::CompletionCallback crash_cb) { ServiceRuntime* new_service_runtime = new ServiceRuntime(this, manifest, should_report_uma, init_done_cb, crash_cb); subprocess->set_service_runtime(new_service_runtime); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n", static_cast<void*>(new_service_runtime))); if (NULL == new_service_runtime) { error_info->SetReport(ERROR_SEL_LDR_INIT, "sel_ldr init failure " + subprocess->description()); return false; } bool service_runtime_started = new_service_runtime->Start(wrapper, error_info, manifest_base_url()); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n", service_runtime_started)); if (!service_runtime_started) { return false; } // Try to start the Chrome IPC-based proxy. const PPB_NaCl_Private* ppb_nacl = GetNaclInterface(); if (ppb_nacl->StartPpapiProxy(pp_instance())) { using_ipc_proxy_ = true; // We need to explicitly schedule this here. It is normally called in // response to starting the SRPC proxy. CHECK(init_done_cb.pp_completion_callback().func != NULL); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon, started ipc proxy.\n")); pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb, PP_OK); } return true; }
37.146341
77
0.74327
awsm-research
97800b9046f54f846dc4fdb8d5c33f66a9b324f2
1,770
cpp
C++
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> void dfs753(std::vector<int> &list, int N, std::string s); int main() { int N; int cnt = 0; std::cin >> N; // find number including only 7, 5, 3 std::vector<int> list; dfs753(list, N, ""); // find answer for (int i = 0; i < list.size(); i++) { int cnt3 = 0; int cnt5 = 0; int cnt7 = 0; int cnt_others = 0; std::string s; s = std::to_string(list[i]); for (int j = 0; j < s.length(); j++) { int n_target_digit = (s[j] - '0'); if (n_target_digit == 3) { cnt3++; } else if (n_target_digit == 5) { cnt5++; } else if (n_target_digit == 7) { cnt7++; } else { cnt_others++; } } if (cnt3 > 0 && cnt5 > 0 && cnt7 > 0 && cnt_others == 0) { cnt++; } } std::cout << cnt << std::endl; return 0; } void dfs753(std::vector<int> &list, int N, std::string s) { std::string s_tmp; int n_tmp; if (s.length() <= 8) { s_tmp = s + '3'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } s_tmp = s + '5'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } s_tmp = s + '7'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } } };
19.450549
64
0.388136
hsmtknj
978137d0c0dbfb68443bae856077cccbb6774a70
758
hpp
C++
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
39
2019-10-23T12:06:16.000Z
2022-01-26T04:28:29.000Z
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
20
2020-03-21T20:21:46.000Z
2021-11-19T14:34:03.000Z
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
7
2019-10-18T09:44:10.000Z
2021-06-11T13:05:16.000Z
#pragma once #include "utils/SimpleSignal.hpp" #include <chrono> namespace ServiceProviders::BatteryService::Settings { using namespace std::chrono_literals; constexpr std::chrono::seconds MeasurmentPeriod = 1s; constexpr std::uint8_t MinBatteryLevel = 0; constexpr std::uint8_t MaxBatteryLevel = 100; } // namespace ServiceProviders::BatteryService::Settings namespace ServiceProviders::BatteryService { class IBatteryLevelAppService { public: virtual ~IBatteryLevelAppService() = default; public: virtual std::chrono::seconds getMeasurmentPeriod() const noexcept = 0; virtual void startBatteryMeasure() noexcept = 0; Simple::Signal<void(std::uint8_t)> onBatteryLevelChangedSig; }; } // namespace ServiceProviders::BatteryService
22.294118
74
0.779683
ValentiWorkLearning
97815b3de040fd642726264a176aabf36379f628
457
cpp
C++
Algorithms/Warmup/Compare the Triplets/Solution.cpp
RAVURISREESAIHARIKRISHNA/Hackerrank
e7ec866a4d03259ed054163b1e9e536af50a1c3e
[ "MIT" ]
null
null
null
Algorithms/Warmup/Compare the Triplets/Solution.cpp
RAVURISREESAIHARIKRISHNA/Hackerrank
e7ec866a4d03259ed054163b1e9e536af50a1c3e
[ "MIT" ]
null
null
null
Algorithms/Warmup/Compare the Triplets/Solution.cpp
RAVURISREESAIHARIKRISHNA/Hackerrank
e7ec866a4d03259ed054163b1e9e536af50a1c3e
[ "MIT" ]
null
null
null
#include<iostream> // #include<conio.h> using namespace std; int main(void){ int a[3]; for(int i=0;i<=2;i++){ cin>>a[i]; } int alice,bob; alice = bob = 0; int x; for(int i=0;i<=2;i++){ cin>>x; if(x > a[i]){ bob++; continue; } if(x < a[i]){ alice++; continue; } } cout<<alice<<" "<<bob; // getch(); return 0; }
15.233333
26
0.380744
RAVURISREESAIHARIKRISHNA
9783189e5d4c4aa02546453c02c6a066e94391d3
423
hpp
C++
src/leader/leader_factory.hpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
7
2019-05-08T08:25:40.000Z
2021-06-19T10:42:56.000Z
src/leader/leader_factory.hpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
5
2020-03-07T15:24:27.000Z
2022-03-12T00:49:53.000Z
src/leader/leader_factory.hpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
4
2020-03-05T17:05:42.000Z
2021-11-21T16:00:56.000Z
#ifndef LEADER_FACTORY_HPP_ #define LEADER_FACTORY_HPP_ #include "leader_connections.hpp" #include "factory.hpp" #include "leader_storage.hpp" #include "server.hpp" class LeaderFactory : public Factory { public: virtual ILeaderStorage* newStorage(std::string path, Message::node node); virtual LeaderConnections* newConnections(int nThread); virtual Server* newServer(IConnections* conn, int port); }; #endif
26.4375
77
0.777778
mrc-g
97833df0227057c09fa51fbf52d1ba81477f4cff
5,366
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <limits> #include <exception> #include <functional> #include <type_traits> #include <msw/config.hpp> #include <msw/buffer.hpp> #include <msw/noncopyable.hpp> #include <msw/throw_runtime_error.hpp> namespace msw { namespace spp { template <typename SizeType = wbyte> struct packer : noncopyable { typedef SizeType size_type ; typedef std::function<void(range<byte>)> packet_ready ; static_assert(std::numeric_limits<size_type>::is_integer && std::is_unsigned<size_type>::value, "SizeType must be only unsigned integer type"); explicit packer(packet_ready packet_ready, size<byte> buffer_capacity = msw::KB * 64, size<byte> offset = 0) : offset_ ( offset ) , buf_ ( 0, buffer_capacity ) , last_packet_len_ ( 0 ) , packet_ready_ ( packet_ready ) {} ~packer() { if (!std::uncaught_exception()) flush(); } template <typename ...T> void add_packet(T&& ...v) { flush(); put_packet(std::forward<T>(v)...); zzz_flush(); } template <typename ...T> void add_packet_silent(T&& ...v) { flush(); put_packet_silent(std::forward<T>(v)...); zzz_flush(); } template <typename ...Ts> void put_packet(Ts&& ...vs) { zzz_add_header(); put_to_last_packet(std::forward<Ts>(vs)...); } template <typename ...Ts> void put_packet_silent(Ts&& ...vs) { zzz_add_header_silent(); put_to_last_packet_silent(std::forward<Ts>(vs)...); } void put_to_last_packet(range<byte const> block) { auto const max_block_size = size<byte>(std::numeric_limits<size_type>::max()); if ((size<byte>(last_packet_len_) + block.size()) > max_block_size) msw::throw_runtime_error("large block: ", last_packet_len_ , " + ", block.size(), " (max permissible size: ", max_block_size, ")"); if (buf_.empty()) zzz_add_header(); zzz_add_last_packet_len(static_cast<size_type>(block.size().count())); buf_.push_back(block); } template <typename T> void put_to_last_packet(T&& v) { #ifdef MSW_ODD_STD_FORWARD put_to_last_packet(make_range<byte const>(v)); #else put_to_last_packet(make_range<byte const>(std::forward<T>(v))); #endif } template <typename T, typename ...Ts> void put_to_last_packet(T&& v, Ts&& ...vs) { put_to_last_packet(std::forward<T>(v)); put_to_last_packet(std::forward<Ts>(vs)...); } void put_to_last_packet_silent(range<byte const> block) { MSW_ASSERT((size<byte>(last_packet_len_) + block.size()) <= size<byte>(std::numeric_limits<size_type>::max())); if (buf_.empty()) zzz_add_header_silent(); zzz_add_last_packet_len(static_cast<size_type>(block.size().count())); buf_.push_back_silent(block); } template <typename T> void put_to_last_packet_silent(T&& v) { put_to_last_packet_silent(make_range<byte const>(std::forward<T>(v))); } template <typename T, typename ...Ts> void put_to_last_packet_silent(T&& v, Ts&& ...vs) { put_to_last_packet_silent(std::forward<T>(v)); put_to_last_packet_silent(std::forward<Ts>(vs)...); } size<byte> packet_size() const { return buf_.size(); } size<byte> capacity() const { return buf_.capacity(); } size<byte> offset() const { return offset_; } bool empty() const { return buf_.empty(); } void flush() { if (buf_.has_items()) zzz_flush(); } void reset() { buf_.clear(); last_packet_len_ = 0; } private: void zzz_flush() { packet_ready_(buf_.all()); last_packet_len_ = 0; buf_.clear(); } void zzz_add_header() { if (buf_.empty()) buf_.resize(offset_); buf_.push_back(size_type(0)); last_packet_len_ = 0; } void zzz_add_header_silent() { if (buf_.empty()) buf_.resize(offset_); buf_.push_back_silent(size_type(0)); last_packet_len_ = 0; } void zzz_add_last_packet_len(size_type len) { size_type& packet_len = buf_.back(last_packet_len_ + sizeof(size_type)).template front<size_type>(); last_packet_len_ += len; packet_len += len; MSW_ASSERT(packet_len == last_packet_len_); } size<byte> const offset_ ; buffer<byte> buf_ ; size_type last_packet_len_ ; packet_ready packet_ready_ ; }; typedef packer<byte> packer_8 ; typedef packer<wbyte> packer_16 ; typedef packer<qbyte> packer_32 ; }}
30.488636
151
0.533545
yklishevich
97836c40c9b767bee00ff4f816050487973638fa
5,084
cpp
C++
sender.cpp
dcberumen/Shared-Memory
eaf3970df962db713317de9011aa952b6b13428f
[ "MIT" ]
null
null
null
sender.cpp
dcberumen/Shared-Memory
eaf3970df962db713317de9011aa952b6b13428f
[ "MIT" ]
null
null
null
sender.cpp
dcberumen/Shared-Memory
eaf3970df962db713317de9011aa952b6b13428f
[ "MIT" ]
null
null
null
#include <sys/shm.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "msg.h" /* For the message struct */ /* The size of the shared memory chunk */ #define SHARED_MEMORY_CHUNK_SIZE 1000 /* The ids for the shared memory segment and the message queue */ int shmid, msqid; /* The pointer to the shared memory */ void* sharedMemPtr; /** * Sets up the shared memory segment and message queue * @param shmid - the id of the allocated shared memory * @param msqid - the id of the shared memory */ void init(int& shmid, int& msqid, void*& sharedMemPtr) { int key; key = ftok("keyfile.txt", 'a'); if(key == -1) { perror("ftok"); exit(-1); } /* TODO: 1. Create a file called keyfile.txt containing string "Hello world" (you may do so manually or from the code). 2. Use ftok("keyfile.txt", 'a') in order to generate the key. 3. Use the key in the TODO's below. Use the same key for the queue and the shared memory segment. This also serves to illustrate the difference between the key and the id used in message queues and shared memory. The id for any System V objest (i.e. message queues, shared memory, and sempahores) is unique system-wide among all SYstem V objects. Two objects, on the other hand, may have the same key. */ /* TODO: Get the id of the shared memory segment. The size of the segment must be SHARED_MEMORY_CHUNK_SIZE */ shmid = shmget(key, SHARED_MEMORY_CHUNK_SIZE, 0644 | IPC_CREAT); if(shmid == -1) { perror("shmget"); exit(-1); } /* TODO: Attach to the shared memory */ sharedMemPtr = shmat(shmid, (void *)0, 0); if(sharedMemPtr == (void *)-1) { perror("shmat"); exit(-1); } /* TODO: Attach to the message queue */ /* Store the IDs and the pointer to the shared memory region in the corresponding parameters */ msqid = msgget(key,IPC_CREAT|0644); if(msqid == -1) { perror("msgget"); exit(-1); } } /** * Performs the cleanup functions * @param sharedMemPtr - the pointer to the shared memory * @param shmid - the id of the shared memory segment * @param msqid - the id of the message queue */ void cleanUp(const int& shmid, const int& msqid, void* sharedMemPtr) { /* TODO: Detach from shared memory */\ if (shmdt(sharedMemPtr) == -1) { perror("shmdt"); exit(1); } printf("Detatched from shared memory\n"); } /** * The main send function * @param fileName - the name of the file */ void send(const char* fileName) { /* Open the file for reading */ FILE* fp = fopen(fileName, "r"); /* A buffer to store message we will send to the receiver. */ message sndMsg; /* A buffer to store message received from the receiver. */ message recMsg; /* Was the file open? */ if(!fp) { perror("fopen"); exit(-1); } /* Read the whole file */ while(!feof(fp)) { /* Read at most SHARED_MEMORY_CHUNK_SIZE from the file and store them in shared memory. * fread will return how many bytes it has actually read (since the last chunk may be less * than SHARED_MEMORY_CHUNK_SIZE). */ if((sndMsg.size = fread(sharedMemPtr, sizeof(char), SHARED_MEMORY_CHUNK_SIZE, fp)) < 0) { perror("fread"); exit(-1); } /* TODO: Send a message to the receiver telling him that the data is ready * (message of type SENDER_DATA_TYPE) */ sndMsg.mtype = SENDER_DATA_TYPE; printf("Ready to send %d \n", sndMsg.size); if(msgsnd(msqid, &sndMsg.mtype, sndMsg.size, sndMsg.mtype) == -1) { perror("msgsnd"); exit(-1); } /* TODO: Wait until the receiver sends us a message of type RECV_DONE_TYPE telling us * that he finished saving the memory chunk. */ printf("Waiting for conformation of send\n"); recMsg.mtype = RECV_DONE_TYPE; if(msgrcv(msqid, &recMsg.mtype, 0, recMsg.mtype, 0) == -1) { perror("msgrcv"); exit(-1); } printf("Conformation recieved\n"); } /** TODO: once we are out of the above loop, we have finished sending the file. * Lets tell the receiver that we have nothing more to send. We will do this by * sending a message of type SENDER_DATA_TYPE with size field set to 0. */ sndMsg.mtype = SENDER_DATA_TYPE; if(msgsnd(msqid, &sndMsg.mtype, 0, sndMsg.mtype) == -1) { perror("msgsnd"); exit(-1); } /* Close the file */ fclose(fp); } int main(int argc, char** argv) { /* Check the command line arguments */ if(argc < 2) { fprintf(stderr, "USAGE: %s <FILE NAME>\n", argv[0]); exit(-1); } /* Connect to shared memory and the message queue */ init(shmid, msqid, sharedMemPtr); /* Send the file */ send(argv[1]); /* Cleanup */ cleanUp(shmid, msqid, sharedMemPtr); return 0; }
26.479167
111
0.608379
dcberumen
97839573dbebe5642e4b67d09a062c8bcb9e83d5
24,403
cpp
C++
system.cpp
YunzheZJU/GLSL_Edge
5b6a8ee1890747d2d898645594f4965d2ae114b1
[ "MIT" ]
null
null
null
system.cpp
YunzheZJU/GLSL_Edge
5b6a8ee1890747d2d898645594f4965d2ae114b1
[ "MIT" ]
null
null
null
system.cpp
YunzheZJU/GLSL_Edge
5b6a8ee1890747d2d898645594f4965d2ae114b1
[ "MIT" ]
null
null
null
// // System.cpp // Processing system display and control // Created by Yunzhe on 2017/12/4. // #include "system.h" Shader shader = Shader(); VBOPlane *plane; VBOTeapot *teapot; VBOTorus *torus; GLuint fboHandle; GLuint pass1Index; GLuint pass2Index; GLuint renderTex; GLuint fsQuad; mat4 model; mat4 view; mat4 projection; GLfloat angle = 0.0f; // Use this to control the rotation GLfloat edgeThreshold = 0.01f; // Threshold of edge detection GLfloat camera[3] = {0, 0, 5}; // Position of camera GLfloat target[3] = {0, 0, 0}; // Position of target of camera GLfloat camera_polar[3] = {5, -1.57f, 0}; // Polar coordinates of camera GLfloat camera_locator[3] = {0, -5, 10}; // Position of shadow of camera int fpsMode = 2; // 0:off, 1:on, 2:waiting int window[2] = {1280, 720}; // Window size int windowCenter[2]; // Center of this window, to be updated char message[70] = "Welcome!"; // Message string to be shown bool bMsaa = false; // Switch of multisampling anti-alias bool bCamera = true; // Switch of camera/target control bool bFocus = true; // Status of window focus bool bMouse = false; // Whether mouse postion should be moved void Idle() { glutPostRedisplay(); } void Reshape(int width, int height) { if (height == 0) { // Prevent A Divide By Zero By height = 1; // Making Height Equal One } glViewport(static_cast<GLint>(width / 2.0 - 640), static_cast<GLint>(height / 2.0 - 360), 1280, 720); window[W] = width; window[H] = height; shader.setUniform("Width", window[W]); shader.setUniform("Height", window[H]); updateWindowcenter(window, windowCenter); glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix gluPerspective(45.0f, 1.7778f, 0.1f, 30000.0f); // 1.7778 = 1280 / 720 glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix } void Redraw() { shader.use(); glBindFramebuffer(GL_FRAMEBUFFER, fboHandle); // Render scene glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); // Reset The Current Modelview Matrix // 必须定义,以在固定管线中绘制物体 gluLookAt(camera[X], camera[Y], camera[Z], target[X], target[Y], target[Z], 0, 1, 0); // Define the view matrix if (bMsaa) { glEnable(GL_MULTISAMPLE_ARB); } else { glDisable(GL_MULTISAMPLE_ARB); } angle += 0.5f; glUniformSubroutinesuiv(GL_FRAGMENT_SHADER, 1, &pass1Index); glEnable(GL_DEPTH_TEST); // Draw something here updateMVPZero(); updateMVPOne(); teapot->render(); // updateMVPTwo(); // plane->render(); updateMVPThree(); torus->render(); glFlush(); ////////////////////////////////////// glBindFramebuffer(GL_FRAMEBUFFER, 0); // Render filter Image glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, renderTex); glDisable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT); glUniformSubroutinesuiv(GL_FRAGMENT_SHADER, 1, &pass2Index); model = mat4(1.0f); view = mat4(1.0f); projection = mat4(1.0f); updateShaderMVP(); // Render the full-screen quad glBindVertexArray(fsQuad); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); shader.disable(); // Draw crosshair and locator in fps mode, or target when in observing mode(fpsMode == 0). if (fpsMode == 0) { glDisable(GL_DEPTH_TEST); drawLocator(target, LOCATOR_SIZE); glEnable(GL_DEPTH_TEST); } else { drawCrosshair(); camera_locator[X] = camera[X]; camera_locator[Z] = camera[Z]; glDisable(GL_DEPTH_TEST); drawLocator(camera_locator, LOCATOR_SIZE); glEnable(GL_DEPTH_TEST); } // Show fps, message and other information PrintStatus(); glutSwapBuffers(); } void ProcessMouseClick(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { bMsaa = !bMsaa; cout << "LMB pressed. Switch on/off multisampling anti-alias.\n" << endl; strcpy(message, "LMB pressed. Switch on/off multisampling anti-alias."); glutPostRedisplay(); } } void ProcessMouseMove(int x, int y) { cout << "Mouse moves to (" << x << ", " << y << ")" << endl; if (fpsMode) { // Track target and reverse mouse moving to center point. if (fpsMode == 2) { // 鼠标位置居中,为确保在glutPositionWindow()之后执行 updateWindowcenter(window, windowCenter); SetCursorPos(windowCenter[X], windowCenter[Y]); glutSetCursor(GLUT_CURSOR_NONE); fpsMode = 1; return; } if (x < window[W] * 0.25) { x += window[W] * 0.5; bMouse = !bMouse; } else if (x > window[W] * 0.75) { x -= window[W] * 0.5; bMouse = !bMouse; } if (y < window[H] * 0.25) { y = static_cast<int>(window[H] * 0.25); bMouse = !bMouse; } else if (y > window[H] * 0.75) { y = static_cast<int>(window[H] * 0.75); bMouse = !bMouse; } // 将新坐标与屏幕中心的差值换算为polar的变化 camera_polar[A] = static_cast<GLfloat>((window[W] / 2 - x) * (180 / 180.0 * PI) / (window[W] / 4.0) * PANNING_PACE); // Delta pixels * 180 degrees / (1/4 width) * PANNING_PACE camera_polar[T] = static_cast<GLfloat>((window[H] / 2 - y) * (90 / 180.0 * PI) / (window[H] / 4.0) * PANNING_PACE); // Delta pixels * 90 degrees / (1/4 height) * PANNING_PACE // 移动光标 if (bMouse) { SetCursorPos(glutGet(GLUT_WINDOW_X) + x, glutGet(GLUT_WINDOW_Y) + y); bMouse = !bMouse; } // 更新摄像机目标 updateTarget(camera, target, camera_polar); } } void ProcessFocus(int state) { if (state == GLUT_LEFT) { bFocus = false; cout << "Focus is on other window." << endl; } else if (state == GLUT_ENTERED) { bFocus = true; cout << "Focus is on this window." << endl; } } void ProcessNormalKey(unsigned char k, int x, int y) { switch (k) { // 退出程序 case 27: { cout << "Bye." << endl; exit(0); } // 切换摄像机本体/焦点控制 case 'Z': case 'z': { strcpy(message, "Z pressed. Switch camera control!"); bCamera = !bCamera; break; } // 切换第一人称控制 case 'C': case 'c': { strcpy(message, "C pressed. Switch fps control!"); // 摄像机归零 cameraMakeZero(camera, target, camera_polar); if (!fpsMode) { // 调整窗口位置 int windowmaxx = glutGet(GLUT_WINDOW_X) + window[W]; int windowmaxy = glutGet(GLUT_WINDOW_Y) + window[H]; if (windowmaxx >= glutGet(GLUT_SCREEN_WIDTH) || windowmaxy >= glutGet(GLUT_SCREEN_HEIGHT)) { // glutPositionWindow()并不会立即执行! glutPositionWindow(glutGet(GLUT_SCREEN_WIDTH) - window[W], glutGet(GLUT_SCREEN_HEIGHT) - window[H]); fpsMode = 2; break; } // 鼠标位置居中 updateWindowcenter(window, windowCenter); // windowCenter[X] - window[W] * 0.25 为什么要减? SetCursorPos(windowCenter[X], windowCenter[Y]); glutSetCursor(GLUT_CURSOR_NONE); fpsMode = 1; } else { glutSetCursor(GLUT_CURSOR_RIGHT_ARROW); fpsMode = 0; } break; } // 第一人称移动/摄像机本体移动/焦点移动 case 'A': case 'a': { strcpy(message, "A pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] -= cos(camera_polar[A]) * MOVING_PACE; camera[Z] += sin(camera_polar[A]) * MOVING_PACE; target[X] -= cos(camera_polar[A]) * MOVING_PACE; target[Z] += sin(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera_polar[A] -= OBSERVING_PACE * 0.1; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "A pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { target[X] -= OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "A pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'D': case 'd': { strcpy(message, "D pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] += cos(camera_polar[A]) * MOVING_PACE; camera[Z] -= sin(camera_polar[A]) * MOVING_PACE; target[X] += cos(camera_polar[A]) * MOVING_PACE; target[Z] -= sin(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera_polar[A] += OBSERVING_PACE * 0.1; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "D pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { target[X] += OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "D pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'W': case 'w': { strcpy(message, "W pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] -= sin(camera_polar[A]) * MOVING_PACE; camera[Z] -= cos(camera_polar[A]) * MOVING_PACE; target[X] -= sin(camera_polar[A]) * MOVING_PACE; target[Z] -= cos(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera[Y] += OBSERVING_PACE; cout << fixed << setprecision(1) << "W pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { target[Y] += OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "W pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'S': case 's': { strcpy(message, "S pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] += sin(camera_polar[A]) * MOVING_PACE; camera[Z] += cos(camera_polar[A]) * MOVING_PACE; target[X] += sin(camera_polar[A]) * MOVING_PACE; target[Z] += cos(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera[Y] -= OBSERVING_PACE; cout << fixed << setprecision(1) << "S pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; strcpy(message, "S pressed. Watch carefully!"); } else { target[Y] -= OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "S pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'Q': case 'q': { if (bCamera) { strcpy(message, "Q pressed. Camera is moved...nearer!"); camera_polar[R] *= 0.95; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "Q pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { strcpy(message, "Q pressed. Camera target is moving towards +Z!"); target[Z] += OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "Q pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } break; } case 'E': case 'e': { if (bCamera) { strcpy(message, "E pressed. Camera is moved...farther!"); camera_polar[R] *= 1.05; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "E pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { strcpy(message, "E pressed. Camera target is moving towards -Z!"); target[Z] -= OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "E pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } break; } // 边缘检测阈值 case '+': { cout << "+ pressed." << endl; if (edgeThreshold < EDGE_THRESHOLD_MAX) { edgeThreshold += EDGE_THRESHOLD_STEP; cout << fixed << setprecision(4) << "Threshold of edge detection is set to " << edgeThreshold << "." << endl; sprintf(message, "Threshold of edge detection is set to %.4f.", edgeThreshold); } break; } case '-': { cout << "- pressed." << endl; if (edgeThreshold > EDGE_THRESHOLD_MIX) { edgeThreshold -= EDGE_THRESHOLD_STEP; cout << fixed << setprecision(4) << "Threshold of edge detection is set to " << edgeThreshold << "." << endl; sprintf(message, "Threshold of edge detection is set to %.4f.", edgeThreshold); } break; } // 屏幕截图 case 'X': case 'x': { cout << "X pressed." << endl; if (screenshot(window[W], window[H])) { cout << "Screenshot is saved." << endl; strcpy(message, "X pressed. Screenshot is Saved."); } else { cout << "Screenshot failed." << endl; strcpy(message, "X pressed. Screenshot failed."); } break; } default: break; } } void PrintStatus() { static int frame = 0; static int currenttime; static int timebase = 0; static char fpstext[50]; char *c; char cameraPositionMessage[50]; char targetPositionMessage[50]; char cameraPolarPositonMessage[50]; frame++; currenttime = glutGet(GLUT_ELAPSED_TIME); if (currenttime - timebase > 1000) { sprintf(fpstext, "FPS:%4.2f", frame * 1000.0 / (currenttime - timebase)); timebase = currenttime; frame = 0; } sprintf(cameraPositionMessage, "Camera Position %2.1f %2.1f %2.1f", camera[X], camera[Y], camera[Z]); sprintf(targetPositionMessage, "Target Position %2.1f %2.1f %2.1f", target[X], target[Y], target[Z]); sprintf(cameraPolarPositonMessage, "Camera Polar %2.1f %2.3f %2.3f", camera_polar[R], camera_polar[A], camera_polar[T]); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); // 不受灯光影响 glMatrixMode(GL_PROJECTION); // 选择投影矩阵 glPushMatrix(); // 保存原矩阵 glLoadIdentity(); // 装入单位矩阵 glOrtho(-window[W] / 2, window[W] / 2, -window[H] / 2, window[H] / 2, -1, 1); // 设置裁减区域 glMatrixMode(GL_MODELVIEW); // 选择Modelview矩阵 glPushMatrix(); // 保存原矩阵 glLoadIdentity(); // 装入单位矩阵 glPushAttrib(GL_LIGHTING_BIT); glRasterPos2f(20 - window[W] / 2, window[H] / 2 - 20); for (c = fpstext; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c); } glRasterPos2f(window[W] / 2 - 240, window[H] / 2 - 20); for (c = cameraPositionMessage; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c); } glRasterPos2f(window[W] / 2 - 240, window[H] / 2 - 55); for (c = targetPositionMessage; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c); } glRasterPos2f(window[W] / 2 - 240, window[H] / 2 - 90); for (c = cameraPolarPositonMessage; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c); } glRasterPos2f(20 - window[W] / 2, 20 - window[H] / 2); for (c = message; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c); } glPopAttrib(); glMatrixMode(GL_PROJECTION); // 选择投影矩阵 glPopMatrix(); // 重置为原保存矩阵 glMatrixMode(GL_MODELVIEW); // 选择Modelview矩阵 glPopMatrix(); // 重置为原保存矩阵 glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); } void initVBO() { plane = new VBOPlane(50.0f, 50.0f, 1, 1); teapot = new VBOTeapot(14, glm::mat4(1.0f)); torus = new VBOTorus(0.7f * 2, 0.3f * 2, 50, 50); } void setShader() { GLuint shaderProgram = shader.getProgram(); pass1Index = glGetSubroutineIndex(shaderProgram, GL_FRAGMENT_SHADER, "pass1"); pass2Index = glGetSubroutineIndex(shaderProgram, GL_FRAGMENT_SHADER, "pass2"); shader.setUniform("Width", window[W]); shader.setUniform("Height", window[H]); shader.setUniform("Light.Intensity", vec3(1.0f, 1.0f, 1.0f)); updateShaderMVP(); } void updateMVPZero() { view = glm::lookAt(vec3(camera[X], camera[Y], camera[Z]), vec3(target[X], target[Y], target[Z]), vec3(0.0f, 1.0f, 0.0f)); projection = glm::perspective(45.0f, 1.7778f, 0.1f, 30000.0f); shader.setUniform("Light.Position", view * vec4(0.0f, 0.0f, 10.0f, 1.0f)); shader.setUniform("EdgeThreshold", edgeThreshold); } void updateMVPOne() { model = mat4(1.0f); model = glm::translate(model, vec3(-2.0f, -1.5f, 0.0f)); model = glm::rotate(model, glm::radians(angle), vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(-90.0f), vec3(1.0f, 0.0f, 0.0f)); shader.setUniform("Material.Kd", 0.9f, 0.9f, 0.9f); shader.setUniform("Material.Ks", 0.95f, 0.95f, 0.95f); shader.setUniform("Material.Ka", 0.1f, 0.1f, 0.1f); shader.setUniform("Material.Shininess", 100.0f); updateShaderMVP(); } void updateMVPTwo() { model = mat4(1.0f); model = glm::translate(model, vec3(0.0f, -2.0f, 0.0f)); shader.setUniform("Material.Kd", 0.4f, 0.4f, 0.4f); shader.setUniform("Material.Ks", 0.0f, 0.0f, 0.0f); shader.setUniform("Material.Ka", 0.1f, 0.1f, 0.1f); shader.setUniform("Material.Shininess", 1.0f); updateShaderMVP(); } void updateMVPThree() { model = mat4(1.0f); model = glm::translate(model, vec3(2.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(angle), vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(90.0f), vec3(1.0f, 0.0f, 0.0f)); shader.setUniform("Material.Kd", 0.9f, 0.5f, 0.2f); shader.setUniform("Material.Ks", 0.95f, 0.95f, 0.95f); shader.setUniform("Material.Ka", 0.1f, 0.1f, 0.1f); shader.setUniform("Material.Shininess", 100.0f); updateShaderMVP(); } void updateShaderMVP() { mat4 mv = view * model; shader.setUniform("ModelViewMatrix", mv); shader.setUniform("NormalMatrix", mat3(vec3(mv[0]), vec3(mv[1]), vec3(mv[2]))); shader.setUniform("MVP", projection * mv); } void setupFBO() { // Generate and bind the framebuffer glGenFramebuffers(1, &fboHandle); glBindFramebuffer(GL_FRAMEBUFFER, fboHandle); // Create the texture object glGenTextures(1, &renderTex); glBindTexture(GL_TEXTURE_2D, renderTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1280, 720, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); // Bind the texture to the FBO glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTex, 0); // Create the depth buffer GLuint depthBuf; glGenRenderbuffers(1, &depthBuf); glBindRenderbuffer(GL_RENDERBUFFER, depthBuf); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1280, 720); // Bind the depth buffer to the FBO glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuf); // Set the targets for the fragment output variables GLenum drawBuffers[] = {GL_COLOR_ATTACHMENT0, GL_NONE}; glDrawBuffers(1, drawBuffers); GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (result == GL_FRAMEBUFFER_COMPLETE) { cout << "Framebuffer is complete" << endl; } else { cout << "Framebuffer error: " << result << endl; } // Unbind the framebuffer, and revert to default framebuffer glBindFramebuffer(GL_FRAMEBUFFER, 0); } void setupVAO() { // Array for full-screen quad GLfloat verts[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f }; GLfloat tc[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; // Set up the buffers unsigned int handle[2]; glGenBuffers(2, handle); glBindBuffer(GL_ARRAY_BUFFER, handle[0]); glBufferData(GL_ARRAY_BUFFER, 6 * 3 * sizeof(float), verts, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, handle[1]); glBufferData(GL_ARRAY_BUFFER, 6 * 2 * sizeof(float), tc, GL_STATIC_DRAW); // Set up the vertex array object glGenVertexArrays(1, &fsQuad); glBindVertexArray(fsQuad); glBindBuffer(GL_ARRAY_BUFFER, handle[0]); glVertexAttribPointer((GLuint) 0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); // Vertex position glBindBuffer(GL_ARRAY_BUFFER, handle[1]); glVertexAttribPointer((GLuint) 2, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); // Texture coordinates glBindVertexArray(0); } void initShader() { try { shader.compileShader("edge.vert"); shader.compileShader("edge.frag"); shader.link(); shader.use(); } catch (GLSLProgramException &e) { cerr << e.what() << endl; exit(EXIT_FAILURE); } }
39.359677
131
0.533787
YunzheZJU
978d4b0d959ed6727d5d1d7bc48fe5a5359b0ce0
1,543
cc
C++
facebody/src/model/GenerateHumanSketchStyleRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
facebody/src/model/GenerateHumanSketchStyleRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
facebody/src/model/GenerateHumanSketchStyleRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/facebody/model/GenerateHumanSketchStyleRequest.h> using AlibabaCloud::Facebody::Model::GenerateHumanSketchStyleRequest; GenerateHumanSketchStyleRequest::GenerateHumanSketchStyleRequest() : RpcServiceRequest("facebody", "2019-12-30", "GenerateHumanSketchStyle") { setMethod(HttpRequest::Method::Post); } GenerateHumanSketchStyleRequest::~GenerateHumanSketchStyleRequest() {} std::string GenerateHumanSketchStyleRequest::getReturnType()const { return returnType_; } void GenerateHumanSketchStyleRequest::setReturnType(const std::string& returnType) { returnType_ = returnType; setBodyParameter("ReturnType", returnType); } std::string GenerateHumanSketchStyleRequest::getImageURL()const { return imageURL_; } void GenerateHumanSketchStyleRequest::setImageURL(const std::string& imageURL) { imageURL_ = imageURL; setBodyParameter("ImageURL", imageURL); }
29.673077
83
0.771225
aliyun
9791022486471675cd10515f685393c43850bd56
134
cpp
C++
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
#include "hello.h" double calculate_paycheck(double num1, double num2) { auto payrate = num1 / num2; return payrate; }
13.4
51
0.664179
acc-cosc-1337-summer-2020-classroom
97965f72395d2a44fbf70895ef4836a59b19f5e2
28,101
cpp
C++
src/Pegasus/Common/tests/OperationContext/TestOperationContext.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Common/tests/OperationContext/TestOperationContext.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Common/tests/OperationContext/TestOperationContext.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN // ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED // "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //============================================================================== // // Author: Chip Vincent (cvincent@us.ibm.com) // // Modified By: // Carol Ann Krug Graves, Hewlett-Packard Company(carolann_graves@hp.com) // Yi Zhou, Hewlett-Packard Company (yi_zhou@hp.com) // //%///////////////////////////////////////////////////////////////////////////// #include <Pegasus/Common/Config.h> #include <Pegasus/Common/Constants.h> #include <Pegasus/Common/CIMDateTime.h> #include <Pegasus/Common/CIMName.h> #include <Pegasus/Common/OperationContext.h> #include <Pegasus/Common/OperationContextInternal.h> #include <iostream> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; static char * verbose = 0; CIMInstance _createFilterInstance1(void) { CIMInstance filterInstance(PEGASUS_CLASSNAME_INDFILTER); // add properties filterInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); filterInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); filterInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString())); filterInstance.addProperty(CIMProperty("Name", String("Filter1"))); filterInstance.addProperty(CIMProperty("Query", String("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"))); filterInstance.addProperty(CIMProperty("QueryLanguage", String("WQL1"))); filterInstance.addProperty(CIMProperty("SourceNamespace", String("root/PG_InterOp"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName", "CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Filter1", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = filterInstance.getPath(); objectPath.setKeyBindings(keys); filterInstance.setPath(objectPath); return(filterInstance); } CIMInstance _createHandlerInstance1(void) { CIMInstance handlerInstance(PEGASUS_CLASSNAME_INDHANDLER_CIMXML); // add properties handlerInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); handlerInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); handlerInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString())); handlerInstance.addProperty(CIMProperty("Name", String("Handler1"))); handlerInstance.addProperty(CIMProperty("Destination", String("localhost:5988/test1"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName", "CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Handler1", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = handlerInstance.getPath(); objectPath.setKeyBindings(keys); handlerInstance.setPath(objectPath); return(handlerInstance); } CIMInstance _createFilterInstance2(void) { CIMInstance filterInstance(PEGASUS_CLASSNAME_INDFILTER); // add properties filterInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); filterInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); filterInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString())); filterInstance.addProperty(CIMProperty("Name", String("Filter2"))); filterInstance.addProperty(CIMProperty("Query", String("SELECT * FROM CIM_AlertIndication WHERE AlertType = 8"))); filterInstance.addProperty(CIMProperty("QueryLanguage", String("WQL1"))); filterInstance.addProperty(CIMProperty("SourceNamespace", String("root/PG_InterOp"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName", "CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Filter2", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = filterInstance.getPath(); objectPath.setKeyBindings(keys); filterInstance.setPath(objectPath); return(filterInstance); } CIMInstance _createHandlerInstance2(void) { CIMInstance handlerInstance(PEGASUS_CLASSNAME_INDHANDLER_CIMXML); // add properties handlerInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); handlerInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); handlerInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString())); handlerInstance.addProperty(CIMProperty("Name", String("Handler2"))); handlerInstance.addProperty(CIMProperty("Destination", String("localhost:5988/test2"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName","CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Handler2", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = handlerInstance.getPath(); objectPath.setKeyBindings(keys); handlerInstance.setPath(objectPath); return(handlerInstance); } CIMInstance _createSubscriptionInstance1(void) { CIMInstance filterInstance1 = _createFilterInstance1(); CIMInstance handlerInstance1 = _createHandlerInstance1(); CIMInstance subscriptionInstance(PEGASUS_CLASSNAME_INDSUBSCRIPTION); // add properties subscriptionInstance.addProperty(CIMProperty("Filter", filterInstance1.getPath(), 0, PEGASUS_CLASSNAME_INDFILTER)); subscriptionInstance.addProperty(CIMProperty("Handler", handlerInstance1.getPath(), 0, PEGASUS_CLASSNAME_INDHANDLER_CIMXML)); subscriptionInstance.addProperty(CIMProperty("OnFatalErrorPolicy", Uint16(4))); subscriptionInstance.addProperty(CIMProperty("FailureTriggerTimeInterval", Uint64(60))); subscriptionInstance.addProperty(CIMProperty("SubscriptionState", Uint16(2))); subscriptionInstance.addProperty(CIMProperty("TimeOfLastStateChange", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionDuration", Uint64(86400))); subscriptionInstance.addProperty(CIMProperty("SubscriptionStartTime", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionTimeRemaining", Uint64(86400))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationPolicy", Uint16(1))); subscriptionInstance.addProperty(CIMProperty("OtherRepeatNotificationPolicy", String("AnotherPolicy"))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationInterval", Uint64(60))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationGap", Uint64(15))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationCount", Uint16(3))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("Filter", filterInstance1.getPath().toString(), CIMKeyBinding::REFERENCE)); keys.append(CIMKeyBinding("Handler", handlerInstance1.getPath().toString(), CIMKeyBinding::REFERENCE)); // update object path CIMObjectPath objectPath = subscriptionInstance.getPath(); objectPath.setKeyBindings(keys); subscriptionInstance.setPath(objectPath); return(subscriptionInstance); } CIMInstance _createSubscriptionInstance2(void) { CIMInstance filterInstance2 = _createFilterInstance2(); CIMInstance handlerInstance2 = _createHandlerInstance2(); CIMInstance subscriptionInstance(PEGASUS_CLASSNAME_INDSUBSCRIPTION); // add properties subscriptionInstance.addProperty(CIMProperty("Filter", filterInstance2.getPath(), 0, PEGASUS_CLASSNAME_INDFILTER)); subscriptionInstance.addProperty(CIMProperty("Handler", handlerInstance2.getPath(), 0, PEGASUS_CLASSNAME_INDHANDLER_CIMXML)); subscriptionInstance.addProperty(CIMProperty("OnFatalErrorPolicy", Uint16(2))); subscriptionInstance.addProperty(CIMProperty("FailureTriggerTimeInterval", Uint64(120))); subscriptionInstance.addProperty(CIMProperty("SubscriptionState", Uint16(2))); subscriptionInstance.addProperty(CIMProperty("TimeOfLastStateChange", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionDuration", Uint64(172800))); subscriptionInstance.addProperty(CIMProperty("SubscriptionStartTime", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionTimeRemaining", Uint64(172800))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationPolicy", Uint16(1))); subscriptionInstance.addProperty(CIMProperty("OtherRepeatNotificationPolicy", String("AnotherPolicy2"))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationInterval", Uint64(120))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationGap", Uint64(30))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationCount", Uint16(6))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("Filter", filterInstance2.getPath().toString(), CIMKeyBinding::REFERENCE)); keys.append(CIMKeyBinding("Handler", handlerInstance2.getPath().toString(), CIMKeyBinding::REFERENCE)); // update object path CIMObjectPath objectPath = subscriptionInstance.getPath(); objectPath.setKeyBindings(keys); subscriptionInstance.setPath(objectPath); return(subscriptionInstance); } // // IdentityContainer // void Test1(void) { if(verbose) { cout << "Test1()" << endl; } OperationContext context; { String userName("Yoda"); context.insert(IdentityContainer(userName)); IdentityContainer container = context.get(IdentityContainer::NAME); if(userName != container.getUserName()) { cout << "----- Identity Container failed" << endl; throw 0; } } context.clear(); { String userName("Yoda"); context.insert(IdentityContainer(userName)); // // This test exercises the IdentityContainer copy constructor // IdentityContainer container = context.get(IdentityContainer::NAME); if(userName != container.getUserName()) { cout << "----- Identity Container copy constructor failed" << endl; throw 0; } } context.clear(); { String userName("Yoda"); context.insert(IdentityContainer(userName)); // // This test exercises the IdentityContainer assignment operator // IdentityContainer container = IdentityContainer(" "); container = context.get(IdentityContainer::NAME); if(userName != container.getUserName()) { cout << "----- Identity Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionInstanceContainer // void Test2(void) { if(verbose) { cout << "Test2()" << endl; } OperationContext context; CIMInstance subscriptionInstance = _createSubscriptionInstance1(); { context.insert(SubscriptionInstanceContainer(subscriptionInstance)); SubscriptionInstanceContainer container = context.get(SubscriptionInstanceContainer::NAME); if(!subscriptionInstance.identical(container.getInstance())) { cout << "----- Subscription Instance Container failed" << endl; throw 0; } } context.clear(); { context.insert(SubscriptionInstanceContainer(subscriptionInstance)); // // This test exercises the SubscriptionInstanceContainer copy // constructor // SubscriptionInstanceContainer container = context.get(SubscriptionInstanceContainer::NAME); if(!subscriptionInstance.identical(container.getInstance())) { cout << "----- Subscription Instance Container copy constructor failed" << endl; throw 0; } } context.clear(); { context.insert(SubscriptionInstanceContainer(subscriptionInstance)); // // This test exercises the SubscriptionInstanceContainer assignment // operator // SubscriptionInstanceContainer container = SubscriptionInstanceContainer(CIMInstance()); container = context.get(SubscriptionInstanceContainer::NAME); if(!subscriptionInstance.identical(container.getInstance())) { cout << "----- Subscription Instance Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionFilterConditionContainer // void Test3(void) { if(verbose) { cout << "Test3()" << endl; } OperationContext context; { String filterCondition("AlertType = 5"); String queryLanguage("WQL1"); context.insert(SubscriptionFilterConditionContainer(filterCondition, queryLanguage)); SubscriptionFilterConditionContainer container = context.get(SubscriptionFilterConditionContainer::NAME); if((filterCondition != container.getFilterCondition()) || (queryLanguage != container.getQueryLanguage())) { cout << "----- Subscription Filter Condition Container failed" << endl; throw 0; } } context.clear(); { String filterCondition("AlertType = 5"); String queryLanguage("WQL1"); context.insert( SubscriptionFilterConditionContainer(filterCondition, queryLanguage)); // // This test exercises the SubscriptionFilterConditionContainer copy // constructor // SubscriptionFilterConditionContainer container = context.get(SubscriptionFilterConditionContainer::NAME); if((filterCondition != container.getFilterCondition()) || (queryLanguage != container.getQueryLanguage())) { cout << "----- SubscriptionFilterCondition Container copy constructor failed" << endl; throw 0; } } context.clear(); { String filterCondition("AlertType = 5"); String queryLanguage("WQL1"); context.insert( SubscriptionFilterConditionContainer(filterCondition, queryLanguage)); // // This test exercises the SubscriptionFilterConditionContainer // assignment operator // SubscriptionFilterConditionContainer container = SubscriptionFilterConditionContainer(" ", " "); container = context.get(SubscriptionFilterConditionContainer::NAME); if((filterCondition != container.getFilterCondition()) || (queryLanguage != container.getQueryLanguage())) { cout << "----- SubscriptionFilterCondition Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionFilterQueryContainer // void Test4(void) { if(verbose) { cout << "Test4()" << endl; } OperationContext context; { String filterQuery("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"); String queryLanguage("WQL1"); CIMNamespaceName sourceNamespace("root/sampleprovider"); context.insert( SubscriptionFilterQueryContainer(filterQuery, queryLanguage, sourceNamespace)); SubscriptionFilterQueryContainer container = context.get(SubscriptionFilterQueryContainer::NAME); if((filterQuery != container.getFilterQuery()) || (queryLanguage != container.getQueryLanguage()) || (!(sourceNamespace == container.getSourceNameSpace()))) { cout << "----- Subscription Filter Query Container failed" << endl; throw 0; } } context.clear(); { String filterQuery("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"); String queryLanguage("WQL1"); CIMNamespaceName sourceNamespace("root/sampleprovider"); context.insert( SubscriptionFilterQueryContainer(filterQuery, queryLanguage, sourceNamespace)); // // This test exercises the SubscriptionFilterQueryContainer copy // constructor // SubscriptionFilterQueryContainer container = (SubscriptionFilterQueryContainer)context.get (SubscriptionFilterQueryContainer::NAME); if((filterQuery != container.getFilterQuery()) || (queryLanguage != container.getQueryLanguage()) || (!(sourceNamespace == container.getSourceNameSpace()))) { cout << "----- SubscriptionFilterQuery Container copy constructor failed" << endl; throw 0; } } context.clear(); { String filterQuery("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"); String queryLanguage("WQL1"); CIMNamespaceName sourceNamespace("root/sampleprovider"); CIMNamespaceName junkNamespace("root/junk"); context.insert( SubscriptionFilterQueryContainer(filterQuery, queryLanguage, sourceNamespace)); // // This test exercises the SubscriptionFilterQueryContainer // assignment operator // SubscriptionFilterQueryContainer container = SubscriptionFilterQueryContainer(" ", " ", junkNamespace); container = context.get(SubscriptionFilterQueryContainer::NAME); if((filterQuery != container.getFilterQuery()) || (queryLanguage != container.getQueryLanguage()) || (!(sourceNamespace == container.getSourceNameSpace()))) { cout << "----- SubscriptionFilterQuery Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionInstanceNamesContainer // void Test5(void) { if(verbose) { cout << "Test5()" << endl; } OperationContext context; CIMInstance subscriptionInstance1 = _createSubscriptionInstance1(); CIMInstance subscriptionInstance2 = _createSubscriptionInstance2(); Array<CIMObjectPath> subscriptionInstanceNames; subscriptionInstanceNames.append(subscriptionInstance1.getPath()); subscriptionInstanceNames.append(subscriptionInstance2.getPath()); { context.insert( SubscriptionInstanceNamesContainer(subscriptionInstanceNames)); SubscriptionInstanceNamesContainer container = context.get(SubscriptionInstanceNamesContainer::NAME); Array<CIMObjectPath> returnedInstanceNames = container.getInstanceNames(); for(Uint8 i = 0, n = subscriptionInstanceNames.size(); i < n; i++) { if(!subscriptionInstanceNames[i].identical(returnedInstanceNames[i])) { cout << "----- Subscription Instance Names Container failed" << endl; throw 0; } } } context.clear(); { context.insert( SubscriptionInstanceNamesContainer(subscriptionInstanceNames)); // // This test exercises the SubscriptionInstanceNamesContainer copy // constructor // SubscriptionInstanceNamesContainer container = context.get(SubscriptionInstanceNamesContainer::NAME); Array<CIMObjectPath> returnedInstanceNames = container.getInstanceNames(); for(Uint8 i = 0, n = subscriptionInstanceNames.size(); i < n; i++) { if(!subscriptionInstanceNames[i].identical(returnedInstanceNames[i])) { cout << "----- Subscription Instance Names Container copy constructor failed" << endl; throw 0; } } } context.clear(); { context.insert( SubscriptionInstanceNamesContainer(subscriptionInstanceNames)); // // This test exercises the SubscriptionInstanceNamesContainer // assignment operator // Array<CIMObjectPath> returnedInstanceNames; SubscriptionInstanceNamesContainer container = SubscriptionInstanceNamesContainer(returnedInstanceNames); container = context.get(SubscriptionInstanceNamesContainer::NAME); returnedInstanceNames = container.getInstanceNames(); for(Uint8 i = 0, n = subscriptionInstanceNames.size(); i < n; i++) { if(!subscriptionInstanceNames[i].identical(returnedInstanceNames[i])) { cout << "----- Subscription Instance Names Container assignment operator failed" << endl; throw 0; } } } } void Test6(void) { if(verbose) { cout << "Test6()" << endl; } OperationContext context; String languageId("en-US"); context.insert(LocaleContainer(languageId)); LocaleContainer container = context.get(LocaleContainer::NAME); if(languageId != container.getLanguageId()) { cout << "----- Locale Container failed" << endl; throw 0; } } void Test7(void) { if(verbose) { cout << "Test7()" << endl; } OperationContext context; CIMInstance module("PG_ProviderModule"); CIMInstance provider("PG_Provider"); Boolean isRemoteNameSpace = true; String remoteInfo("remote_info"); context.insert(ProviderIdContainer(module, provider, isRemoteNameSpace, remoteInfo)); ProviderIdContainer container = context.get(ProviderIdContainer::NAME); if(!module.identical(container.getModule()) || !provider.identical(container.getProvider()) || (isRemoteNameSpace != container.isRemoteNameSpace()) || (remoteInfo != container.getRemoteInfo())) { cout << "----- Provider Id Container failed" << endl; throw 0; } } void Test8(void) { if(verbose) { cout << "Test8()" << endl; } OperationContext context; try { OperationContext scopeContext; scopeContext = context; scopeContext.remove(IdentityContainer::NAME); scopeContext.remove(SubscriptionInstanceContainer::NAME); scopeContext.remove(SubscriptionFilterConditionContainer::NAME); scopeContext.remove(SubscriptionFilterQueryContainer::NAME); scopeContext.remove(LocaleContainer::NAME); scopeContext.remove(ProviderIdContainer::NAME); } catch(...) { } } // // SnmpTrapOidContainer // void Test9(void) { if(verbose) { cout << "Test9()" << endl; } OperationContext context; { String snmpTrapOid ("1.3.6.1.4.1.992.2.3.9210.8400"); context.insert(SnmpTrapOidContainer(snmpTrapOid)); SnmpTrapOidContainer container = context.get(SnmpTrapOidContainer::NAME); if(snmpTrapOid != container.getSnmpTrapOid()) { cout << "----- Snmp Trap Oid Container failed" << endl; throw 0; } } context.clear(); { String snmpTrapOid ("1.3.6.1.4.1.992.2.3.9210.8400"); context.insert(SnmpTrapOidContainer(snmpTrapOid)); // // This test exercises the SnmpTrapOidContainer copy // constructor // SnmpTrapOidContainer container = context.get(SnmpTrapOidContainer::NAME); if(snmpTrapOid != container.getSnmpTrapOid()) { cout << "----- SnmpTrapOid Container copy constructor failed" << endl; throw 0; } } context.clear(); { String snmpTrapOid ("1.3.6.1.4.1.992.2.3.9210.8400"); context.insert(SnmpTrapOidContainer(snmpTrapOid)); // // This test exercises the SnmpTrapOidContainer // assignment operator // SnmpTrapOidContainer container = SnmpTrapOidContainer(" "); container = context.get(SnmpTrapOidContainer::NAME); if(snmpTrapOid != container.getSnmpTrapOid()) { cout << "----- SnmpTrapOid Container assignment operator failed" << endl; throw 0; } } } void Test10(void) { if(verbose) { cout << "Test10()" << endl; } OperationContext context; CIMClass cimClass("CachedClass"); context.insert(CachedClassDefinitionContainer(cimClass)); CachedClassDefinitionContainer container = context.get(CachedClassDefinitionContainer::NAME); if(cimClass.getClassName().getString() != container.getClass().getClassName().getString()) { cout << "----- CachedClassDefinitionContainer failed" << endl; throw 0; } } int main(int argc, char** argv) { verbose = getenv("PEGASUS_TEST_VERBOSE"); try { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); Test8(); Test9(); Test10(); cout << argv[0] << " +++++ passed all tests" << endl; } catch(CIMException & e) { cout << argv[0] << " ----- failed with CIMException(" << e.getCode() << "):" << e.getMessage() << endl; } catch(Exception & e) { cout << argv[0] << " ----- failed with Exception:" << e.getMessage() << endl; } catch(...) { cout << argv[0] << " ----- failed with unknown exception" << endl; } return(0); }
32.078767
129
0.673891
ncultra
979b9cab028edacd7d197e7a162952c35400c372
2,100
hpp
C++
android_app/app/src/main/cpp/include/zdl/DlSystem/ITensorItrImpl.hpp
csarron/MobileAccelerator
5e1b40cb2332073da6cd8a52bbba2712ae30f7bd
[ "MIT" ]
2
2021-07-25T01:10:03.000Z
2021-10-29T22:49:09.000Z
android_app/app/src/main/cpp/include/zdl/DlSystem/ITensorItrImpl.hpp
csarron/MobileAccelerator
5e1b40cb2332073da6cd8a52bbba2712ae30f7bd
[ "MIT" ]
null
null
null
android_app/app/src/main/cpp/include/zdl/DlSystem/ITensorItrImpl.hpp
csarron/MobileAccelerator
5e1b40cb2332073da6cd8a52bbba2712ae30f7bd
[ "MIT" ]
null
null
null
//============================================================================= // @@-COPYRIGHT-START-@@ // // Copyright 2015 Qualcomm Technologies, Inc. All rights reserved. // Confidential & Proprietary - Qualcomm Technologies, Inc. ("QTI") // // The party receiving this software directly from QTI (the "Recipient") // may use this software as reasonably necessary solely for the purposes // set forth in the agreement between the Recipient and QTI (the // "Agreement"). The software may be used in source code form solely by // the Recipient's employees (if any) authorized by the Agreement. Unless // expressly authorized in the Agreement, the Recipient may not sublicense, // assign, transfer or otherwise provide the source code to any third // party. Qualcomm Technologies, Inc. retains all ownership rights in and // to the software // // This notice supersedes any other QTI notices contained within the software // except copyright notices indicating different years of publication for // different portions of the software. This notice does not supersede the // application of any third party copyright notice to that third party's // code. // // @@-COPYRIGHT-END-@@ //============================================================================= #ifndef _ITENSOR_ITR_IMPL_HPP_ #define _ITENSOR_ITR_IMPL_HPP_ #include "ZdlExportDefine.hpp" #include <memory> #include <iterator> #include <vector> namespace DlSystem { class ITensorItrImpl; } class ZDL_EXPORT DlSystem::ITensorItrImpl { public: ITensorItrImpl() {} virtual ~ITensorItrImpl() {} virtual float getValue() const = 0; virtual float& getReference() = 0; virtual float& getReferenceAt(size_t idx) = 0; virtual float* dataPointer() const = 0; virtual void increment(int incVal = 1) = 0; virtual void decrement(int decVal = 1) = 0; virtual size_t getPosition() = 0; virtual std::unique_ptr<DlSystem::ITensorItrImpl> clone() = 0; private: ITensorItrImpl& operator=(const ITensorItrImpl& other) = delete; ITensorItrImpl(const ITensorItrImpl& other) = delete; }; #endif
34.42623
79
0.681905
csarron
979c6b30191b3c796513d66d784490eb5eafde41
15,492
cpp
C++
src/jc_handlers/jc_class.cpp
gavz/choupi
fb49537e9646d4797f63ca2191f3b0ddb4c6760a
[ "MIT" ]
2
2021-05-22T03:24:31.000Z
2022-01-20T14:25:25.000Z
src/jc_handlers/jc_class.cpp
gavz/choupi
fb49537e9646d4797f63ca2191f3b0ddb4c6760a
[ "MIT" ]
null
null
null
src/jc_handlers/jc_class.cpp
gavz/choupi
fb49537e9646d4797f63ca2191f3b0ddb4c6760a
[ "MIT" ]
3
2021-05-06T14:24:58.000Z
2022-01-06T07:52:27.000Z
/* ** The MIT License (MIT) ** ** Copyright (c) 2020, National Cybersecurity Agency of France (ANSSI) ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ** THE SOFTWARE. ** ** Author: ** - Guillaume Bouffard <guillaume.bouffard@ssi.gouv.fr> */ #include "jc_class.hpp" #include "jc_cp.hpp" namespace jcvm { /* * The checkcast function check if a type in is compatible with the * type_out. The rule is the following one: * * - If S is a class type, then: * + If T is a class type, then S must be the same class as T, or * S must be a subclass of T; * + If T is an interface type, then S must implement interface T. * - If S is an interface type[13], then: * + If T is a class type, then T must be Object (§2.2.1.4 * Unsupported Classes); * + If T is an interface type, T must be the same interface as S * or a superinterface of S. * - If S is an array type, namely the type SC[], that is, an array of * components of type SC, then: * + If T is a class type, then T must be Object. * + If T is an array type, namely the type TC[], an array of * components of type TC, then one of the following must be true: * * TC and SC are the same primitive type (§3.1 Data Types and * Values). * * TC and SC are reference types[14] (§3.1 Data Types and Values) * with type SC assignable to TC, by these rules. * + If T is an interface type, T must be one of the interfaces * implemented by arrays. * * 13: When both S and T are arrays of reference types, this algorithm is * applied recursively using the types of the arrays, namely SC and TC. In * the recursive call, S, which was SC in the original call, may be an * interface type. This rule can only be reached in this manner. * Similarly, in the recursive call, T, which was TC in the original call, * may be an interface type. * * @param[jtype_in] the input type * @param[jtype_out] the out type * * @return TRUE if the types are compatible, else FALSE */ jbool_t Class_Handler::docheckcast(const std::pair<Package, const uint8_t *> jtype_in, const std::pair<Package, const uint8_t *> jtype_out) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { // case 1: type_in is a class type if (IS_CLASS(jtype_in.second)) { auto jclass_in = std::make_pair( jtype_in.first, reinterpret_cast<const jc_cap_class_info *>(jtype_in.second)); // case 1.1: type_out is a class type if (IS_CLASS(jtype_out.second)) { auto jclass_out = reinterpret_cast<const jc_cap_class_info *>(jtype_out.second); // then S must be the same class as T, or S must be a subclass of T if (jclass_out->isObjectClass()) { return TRUE; } while (!jclass_in.second->isObjectClass()) { if (jclass_in.second == jclass_out) { return TRUE; } jclass_in = ConstantPool_Handler(jclass_in.first) .classref2class(jclass_in.second->super_class_ref); } return FALSE; } // case 1.2: type_out is an interface type else { if (jclass_in.second->interface_count == 0) { return FALSE; } for (uint8_t i = 0; i < jclass_in.second->interface_count; ++i) { auto implemented_interface = jclass_in.second->interfaces(i); ConstantPool_Handler cp(jclass_in.first); if (Class_Handler::checkInterfaceCast( cp.resolveClassref(implemented_interface.interface), jtype_out) == TRUE) { return TRUE; } } } } // case 2: type_in is an interface type else { // jtype_out must be Object if (IS_CLASS(jtype_out.second)) { const auto jclass_out = std::make_pair( jtype_out.first, reinterpret_cast<const jc_cap_class_info *>(jtype_out.second)); return (jclass_out.second->isObjectClass() ? TRUE : FALSE); } return Class_Handler::checkInterfaceCast(jtype_in, jtype_out); } return FALSE; } /* * Check if two interfaces (interface_in and interface_out) have a hierarchy * link together. This function returns TRUE when interface_in is the * daughter of interface_out. * * @param[interface_in] * @param[interface_out] * * @return returns TRUE when interface_in is the daughter of interface_out */ jbool_t Class_Handler::checkInterfaceCast( const std::pair<Package, const uint8_t *> interface_in, const std::pair<Package, const uint8_t *> interface_out) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (!IS_INTERFACE(interface_in.second) || !IS_INTERFACE(interface_out.second)) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ auto superinterfaces = reinterpret_cast<const jc_cap_interface_info *>(interface_in.second) ->super_interfaces(); for (uint8_t j = 0; j < superinterfaces.size(); ++j) { const jc_cap_class_ref super_interface_in = superinterfaces.at(j); auto super_interface_ptr = ConstantPool_Handler(interface_in.first) .resolveClassref(super_interface_in); #ifdef JCVM_DYNAMIC_CHECKS_CAP if (!IS_INTERFACE(super_interface_ptr.second)) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ if ((super_interface_ptr.first == interface_out.first) && (super_interface_ptr.second == interface_out.second)) { return TRUE; } } return FALSE; } /* * Get the reference to the Object class from a classref. * * @param[classref] a classref to find this ultimate class. * @return the reference to the Object class. */ std::pair<Package, const jc_cap_class_info *> Class_Handler::getObjectClassFromAnObjectRef(const jc_cap_class_ref classref) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { ConstantPool_Handler cp_handler(this->package); auto token = cp_handler.classref2class(classref); while (!(token.second->isObjectClass())) { cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } return token; } /** * Get a class public method offset from a class' public method token. * * @param[public_method_token] public method token to resolve. * * @return the public virtual method offset in the Method component. */ std::pair<Package, const uint16_t> Class_Handler::getPublicMethodOffset( const jc_cap_virtual_method_ref_info virtual_method_ref_info) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (virtual_method_ref_info.isPublicMethod()) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ ConstantPool_Handler cp_handler(this->package); uint8_t method_offset = virtual_method_ref_info.token; auto token = cp_handler.classref2class(virtual_method_ref_info.class_ref); // Where is the method offset located? while (!(token.second->isObjectClass()) && (method_offset < token.second->public_method_table_base)) { // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } #ifdef JCVM_DYNAMIC_CHECKS_CAP if (token.second->isObjectClass() && (method_offset < token.second->public_method_table_base)) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ return this->doGetPublicMethodOffset(token.first, token.second, method_offset); } /** * Do get a class public method offset from a class' public method token. * * @param[package] where is located the method to resolve * @param[claz] a pointer to the class where is located the method to resolve * @param[public_method_token] public method token to resolve. * * @return the public virtual method offset in the Method component. */ std::pair<Package, const uint16_t> Class_Handler::doGetPublicMethodOffset(Package &package, const jc_cap_class_info *claz, uint8_t public_method_offset) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { ConstantPool_Handler cp_handler(this->package); uint16_t method_offset = 0xFFFF; const JCVMArray<const uint16_t> public_virtual_method_table = claz->public_virtual_method_table(); auto token = std::make_pair(package, claz); do { uint16_t offset = public_method_offset - claz->public_method_table_base; method_offset = public_virtual_method_table.at(offset); if (method_offset == (uint16_t)0xFFFF) { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (claz->isObjectClass()) { // Behaviour not expected throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } } while (method_offset == (uint16_t)0xFFFF); return std::make_pair(token.first, method_offset); } /** * Get a class package method offset from a class' package method token. * * @param[package_method_token] package method token to resolve. * * @return the package virtual method offset in the Method component. The Cap * field is updated to executed the method to call. */ std::pair<Package, const uint16_t> Class_Handler::getPackageMethodOffset( const jc_cap_virtual_method_ref_info virtual_method_ref_info) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (!virtual_method_ref_info.isPublicMethod()) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ ConstantPool_Handler cp_handler(this->package); uint8_t method_offset_class = virtual_method_ref_info.token; auto token = cp_handler.classref2class(virtual_method_ref_info.class_ref); // Where is the method offset located? while (!(token.second->isObjectClass()) && (method_offset_class < token.second->package_method_table_base)) { // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } uint16_t method_offset = 0xFFFF; const jc_cap_class_info *claz = token.second; const JCVMArray<const uint16_t> package_virtual_method_table = claz->package_virtual_method_table(); do { uint16_t offset = method_offset_class - claz->package_method_table_base; method_offset = package_virtual_method_table.at(offset); if (method_offset == (uint16_t)0xFFFF) { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (claz->isObjectClass()) { // Behavior not expected throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } } while (method_offset == (uint16_t)0xFFFF); return std::make_pair(token.first, method_offset); } /** * Get a class public or package method offset from a class' method token. * * @param[method_token] method token to resolve. * * @return the public or package virtual method offset in the Method component. */ std::pair<Package, const uint16_t> Class_Handler::getMethodOffset( const jc_cap_virtual_method_ref_info virtual_method_ref_info) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { if (virtual_method_ref_info.isPublicMethod()) { return this->getPublicMethodOffset(virtual_method_ref_info); } else { // it's a package method return this->getPackageMethodOffset(virtual_method_ref_info); } } /* * Get a class' implemented interface method offset from a class' package method * token. * * @param[class] class where the method will be resolved. * @param[interface] implemented interface. * @param[implemented_interface_method_number] implemented interface method * number. * @return the implemented interface method offset in the method component. */ std::pair<Package, const uint16_t> Class_Handler::getImplementedInterfaceMethodOffset( const jc_cap_class_ref class_ref, const jc_cap_class_ref interface, const uint8_t implemented_interface_method_number, const bool isArray) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { ConstantPool_Handler cp_handler(this->package); auto claz = (isArray ? this->getObjectClassFromAnObjectRef(class_ref) : cp_handler.classref2class(class_ref)); for (uint16_t index = 0; index < claz.second->interface_count; ++index) { const auto &interfaces = claz.second->interfaces(index); if (HTONS(interfaces.interface.internal_classref) == interface.internal_classref) { uint8_t public_method_offset = interfaces.indexes().at(implemented_interface_method_number); if (isArray) { return this->doGetPublicMethodOffset(claz.first, claz.second, public_method_offset); } else { const jc_cap_virtual_method_ref_info method_ref = { .class_ref = class_ref, .token = public_method_offset, }; return this->getPublicMethodOffset(method_ref); } } } throw Exceptions::SecurityException; } /* * Get the instance field size for an instantiated class. * * @param[claz_index] class index used to compute the instance field size */ const uint16_t Class_Handler::getInstanceFieldsSize(const jclass_index_t claz_index) const #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { auto package = this->package; auto claz = ConstantPool_Handler(package).getClassFromClassIndex(claz_index); uint16_t instance_size = 0; do { ConstantPool_Handler cp_handler(package); instance_size += (claz->declared_instance_size & 0x00FF); auto pair = cp_handler.classref2class(claz->super_class_ref); package = pair.first; claz = pair.second; } while (!(claz->isObjectClass())); return instance_size; } } // namespace jcvm
33.173448
80
0.706106
gavz
97a2bce42566f20ad356ce2a39e84587bb5959a0
4,287
cc
C++
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
2
2019-03-13T14:47:16.000Z
2019-07-22T09:17:43.000Z
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
null
null
null
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
1
2019-07-22T09:17:44.000Z
2019-07-22T09:17:44.000Z
/// /// @file webpage.cc /// @author mistydew(mistydew@qq.com) /// @date 2017-12-02 15:36:06 /// #include "webpage.h" #include "configuration.h" #include "wordsegmentation.h" #include <queue> #include <sstream> namespace md { WebPage::WebPage(const std::string & doc) { std::cout << "WebPage(const std::string &)" << std::endl; _topWords.reserve(TOPK); processDoc(doc); } WebPage::~WebPage() { std::cout << "~WebPage()" << std::endl; } std::string WebPage::getDocTitle() { return _docTitle; } std::string WebPage::getDocUrl() { return _docUrl; } std::string WebPage::summary(const std::vector<std::string> & queryWords) { std::vector<std::string> summaryVec; std::istringstream iss(_docContent); std::string line; while (iss >> line) { for (auto & word : queryWords) { if (line.find(word) != std::string::npos) { summaryVec.push_back(line); break; } } if (summaryVec.size() > 6) break; } std::string summary; for (auto & line : summaryVec) { summary.append(line).append("\n"); } return summary; } void WebPage::processDoc(const std::string & doc) { std::cout << "process document..." << std::endl; std::string begId = "<docid>"; std::string endId = "</docid>"; std::string begUrl = "<url>"; std::string endUrl = "</url>"; std::string begTitle = "<title>"; std::string endTitle = "</title>"; std::string begContent = "<content>"; std::string endContent = "</content>"; std::string::size_type bpos = doc.find(begId); std::string::size_type epos = doc.find(endId); std::string docId = doc.substr(bpos + begId.size(), epos - bpos - begId.size()); _docId = str2uint(docId); bpos = doc.find(begUrl); epos = doc.find(endUrl); _docUrl = doc.substr(bpos + begUrl.size(), epos - bpos - begUrl.size()); bpos = doc.find(begTitle); epos = doc.find(endTitle); _docTitle = doc.substr(bpos + begTitle.size(), epos - bpos - begTitle.size()); bpos = doc.find(begContent); epos = doc.find(endContent); _docContent = doc.substr(bpos + begContent.size(), epos - bpos - begContent.size()); #if 0 std::cout << _docId << std::endl; std::cout << _docUrl << std::endl; std::cout << _docTitle << std::endl; std::cout << _docContent << std::endl; #endif statistic(); calcTopK(); std::cout << "process completed" << std::endl; } void WebPage::statistic() { std::vector<std::string> words; WordSegmentation::getInstance()->cut(_docContent, words); std::size_t nBytes; for (auto & word : words) { if(0 == Configuration::getInstance()->getStopWord().count(word)) { nBytes = nBytesUTF8Code(word[0]); if (0 == nBytes) { word = processWords(word); if ("" == word) continue; } ++_wordsMap[word]; } } #if 0 for (auto & map : _wordsMap) { std::cout << map.first << " " << map.second << std::endl; } #endif } std::string WebPage::processWords(const std::string & word) { std::string temp; for (std::string::size_type idx = 0; idx != word.size(); ++idx) { if (isalpha(word[idx])) { if (isupper(word[idx])) temp += word[idx] + 32; else temp += word[idx]; } } return temp; } void WebPage::calcTopK() { std::priority_queue<std::pair<std::string, std::size_t>, std::vector<std::pair<std::string, std::size_t> >, WordFreqCompare> wordFreqQue(_wordsMap.begin(), _wordsMap.end()); while (!wordFreqQue.empty()) { _topWords.push_back(wordFreqQue.top().first); if (_topWords.size() >= TOPK) break; wordFreqQue.pop(); } #if 0 std::cout << "top words:" << std::endl; for (auto & top : _topWords) { std::cout << top << std::endl; } #endif } std::ostream & operator<<(std::ostream & os, const WebPage & rhs) { os << rhs._docId << std::endl << rhs._docTitle << std::endl << rhs._docUrl << std::endl << rhs._docContent; return os; } } // end of namespace md
24.637931
128
0.559132
mistydew
97a453e833e798b0117112d4759e7c3e46460faf
606
cpp
C++
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#include "test.hpp" #include "test/numbers.hpp" #include "jln/mp/smp/algorithm/suffix.hpp" TEST_SUITE_BEGIN() TEST() { using namespace jln::mp; using namespace ut::ints; test_pack2<suffix, int>(); ut::same<list<>, emp::suffix<list<>, int>>(); ut::same<list<_0, int>, emp::suffix<seq_0, int>>(); test_context<suffix<int>, smp::suffix<int>>() .test<list<>>() .test<list<_0, int>, _0>() .test<list<_0, int, _1, int>, _0, _1>() .test<list<_0, int, _1, int, _2, int>, _0, _1, _2>() ; ut::not_invocable<smp::suffix<void, bad_function>, _1, _1, _1>(); } TEST_SUITE_END()
20.896552
67
0.612211
jonathanpoelen
97aa1b3005b136dd27e3bffc6af997679b487c9f
4,727
cpp
C++
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
// program for basic operations in AVL Tree #include <iostream> #include <cstdlib> using namespace std; struct Node{ int data; struct Node *left; struct Node *right; int height; }*root; struct Node *createNewNode(int x){ struct Node *newptr = new Node; newptr->data = x; newptr->left = NULL; newptr->right = NULL; newptr->height = 1; return newptr; } void inorder(struct Node *root){ if(root == NULL) return; else{ inorder(root->left); cout << root->data << " "; inorder(root->right); } cout << "\n"; } int max(int a, int b){ if(a >= b) return a; else return b; } int height(struct Node *root){ if(root == NULL) return 0; else return root->height; } int getBalance(struct Node *root){ if(root == NULL) return 0; else return height(root->left) - height(root->right); } struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // perform rotation x->right = y; y->left = T2; // update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // return new root return x; } struct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // perform rotation y->left = x; x->right = T2; // update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // return new root return y; } struct Node *insertAVL(struct Node *root, int data){ int balance; // perform normal BST insertion if(root == NULL) return createNewNode(data); if(data <= root->data) root->left = insertAVL(root->left, data); else if(data > root->data) root->right = insertAVL(root->right, data); // update the height of ancestor node root->height = 1 + max(height(root->left),height(root->right)); // get the balance factor of this ancestor node balance = getBalance(root); // if this node is unbalanced, then 4 cases are possible // left left case if(balance > 1 && data < root->left->data) return leftRotate(root); // right right case if(balance > 1 && data > root->right->data) return rightRotate(root); // left right case if(balance > 1 && data > root->left->data){ root->left = leftRotate(root->left); return rightRotate(root); } // right left case if(balance < -1 && data < root->right->data){ root->right = rightRotate(root->right); return leftRotate(root); } // return the unchanged pointers return root; } struct Node *minValueNode(struct Node *root){ struct Node *curr = root; // loop down to find smallest node while(curr->left != NULL) curr = curr->left; return curr; } struct Node *deleteAVL(struct Node *root, int data){ int balance; // perform standard BST delete if(root == NULL) return root; // if the key is in left subtree if(data < root->data) root->left = deleteAVL(root->left, data); // if the key is in right subtree if(data > root->data) root->right = deleteAVL(root->right, data); // if this is the node to be deleted else{ // node with only one child or no child if(root->left == NULL){ struct Node *temp = root->right; free(root); return temp; } else if(root->right == NULL){ struct Node *temp = root->left; free(root); return temp; } // node with two children struct Node *temp = minValueNode(root->right); // copy the inorder successor's content to this node root->data = temp->data; // delete the inorder successor root->right = deleteAVL(root->right,temp->data); } // return root; // update the height of current node root->height = 1 + max(height(root->left), height(root->right)); // get the balanced factor from this node (bottomm up manner) balance = getBalance(root); // if this node is unbalanced, there are 4 possible cases // left left case if(balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // right right case if(balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // left right case if(balance > 1 && getBalance(root->left) < 0){ root->left = leftRotate(root->left); return rightRotate(root); } // right left case if(balance < -1 && getBalance(root->right) > 0){ root->right = rightRotate(root->right); return leftRotate(root); } return root; } int main(){ root = NULL; int size, i; cout << "Enter the size of array\n"; cin >> size; int A[size]; cout << "Enter the elements of array\n"; for(i = 0; i < size; i++){ cin >> A[i]; if(A[i] > 0) root = insertAVL(root, A[i]); else if(A[i] < 0){ A[i] = -1*A[i]; root = deleteAVL(root, A[i]); } } cout << "The inorder traversal of tree is\n"; inorder(root); return 0; }
19.861345
65
0.642268
Raghav1806
97ab322573a6865d8a85ff34c4ad426f4104757c
1,381
cpp
C++
IOCP4Http/IOCP/PerSocketContext.cpp
Joyce-Qu/IOCPServer-Client-
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
42
2019-11-13T06:39:31.000Z
2021-12-28T18:55:27.000Z
IOCP4Http/IOCP/PerSocketContext.cpp
124327288/IOCPServer
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
null
null
null
IOCP4Http/IOCP/PerSocketContext.cpp
124327288/IOCPServer
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
31
2019-11-14T09:58:15.000Z
2022-03-25T08:30:41.000Z
#include <ws2tcpip.h> #include <assert.h> #include "Network.h" #include "PerIoContext.h" #include "PerSocketContext.h" #include <iostream> using namespace std; ListenContext::ListenContext(short port, const std::string& ip) { SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); m_addr.sin_family = AF_INET; inet_pton(AF_INET, ip.c_str(), &m_addr.sin_addr); //m_addr.sin_addr.s_addr = inet_addr(ip.c_str()); m_addr.sin_port = htons(port); m_socket = Network::socket(); assert(SOCKET_ERROR != m_socket); } ClientContext::ClientContext(const SOCKET& socket) : m_socket(socket), m_recvIoCtx(new RecvIoContext()) , m_sendIoCtx(new IoContext(PostType::SEND)) , m_nPendingIoCnt(0) { SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); InitializeCriticalSection(&m_csLock); } ClientContext::~ClientContext() { delete m_recvIoCtx; delete m_sendIoCtx; m_recvIoCtx = nullptr; m_sendIoCtx = nullptr; LeaveCriticalSection(&m_csLock); } void ClientContext::reset() { assert(0 == m_nPendingIoCnt); assert(m_outBufQueue.empty()); SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); m_nLastHeartbeatTime = GetTickCount(); } void ClientContext::appendToBuffer(PBYTE pInBuf, size_t len) { m_inBuf.write((PBYTE)pInBuf, len); } void ClientContext::appendToBuffer(const std::string& inBuf) { m_inBuf.write(inBuf); }
24.660714
63
0.717596
Joyce-Qu
97ad3e092974dd1d58c4f30432cd174a86fdc87e
2,333
cpp
C++
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
3
2018-12-08T16:32:05.000Z
2020-06-02T11:07:15.000Z
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
null
null
null
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
1
2019-09-12T00:26:05.000Z
2019-09-12T00:26:05.000Z
#include "GfxHeader.h" CGfxCamera::CGfxCamera(void) { } CGfxCamera::~CGfxCamera(void) { } void CGfxCamera::SetScissor(float x, float y, float width, float height) { m_camera.setScissor(x, y, width, height); } void CGfxCamera::SetViewport(float x, float y, float width, float height) { m_camera.setViewport(x, y, width, height); } void CGfxCamera::SetPerspective(float fovy, float aspect, float zNear, float zFar) { m_camera.setPerspective(fovy, aspect, zNear, zFar); } void CGfxCamera::SetOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { m_camera.setOrtho(left, right, bottom, top, zNear, zFar); } void CGfxCamera::SetLookat(float eyex, float eyey, float eyez, float centerx, float centery, float centerz, float upx, float upy, float upz) { m_camera.setLookat(glm::vec3(eyex, eyey, eyez), glm::vec3(centerx, centery, centerz), glm::vec3(upx, upy, upz)); } const glm::camera& CGfxCamera::GetCamera(void) const { return m_camera; } const glm::vec4& CGfxCamera::GetScissor(void) const { return m_camera.scissor; } const glm::vec4& CGfxCamera::GetViewport(void) const { return m_camera.viewport; } const glm::vec3& CGfxCamera::GetPosition(void) const { return m_camera.position; } const glm::vec3& CGfxCamera::GetForwardDirection(void) const { return m_camera.forward; } const glm::vec3& CGfxCamera::GetUpDirection(void) const { return m_camera.up; } const glm::mat4& CGfxCamera::GetProjectionMatrix(void) const { return m_camera.projectionMatrix; } const glm::mat4& CGfxCamera::GetViewMatrix(void) const { return m_camera.viewMatrix; } const glm::mat4& CGfxCamera::GetViewInverseMatrix(void) const { return m_camera.viewInverseMatrix; } const glm::mat4& CGfxCamera::GetViewInverseTransposeMatrix(void) const { return m_camera.viewInverseTransposeMatrix; } glm::vec3 CGfxCamera::WorldToScreen(const glm::vec3& world) const { return m_camera.worldToScreen(world); } glm::vec3 CGfxCamera::ScreenToWorld(const glm::vec3& screen) const { return m_camera.screenToWorld(screen); } bool CGfxCamera::IsVisible(const glm::vec3& vertex) const { return m_camera.visible(vertex); } bool CGfxCamera::IsVisible(const glm::aabb& aabb) const { return m_camera.visible(aabb); } bool CGfxCamera::IsVisible(const glm::sphere& sphere) const { return m_camera.visible(sphere); }
20.646018
140
0.753536
LiangYue1981816
97adcb71b727d993f3f48ec0c431b358a65b8a0a
1,349
hpp
C++
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
#pragma once //! \defgroup Basis Basis for a spin-1/2 system #include "BasisJz.hpp" #include "BasisFull.hpp" #include <iterator> #include <type_traits> #include <tbb/concurrent_vector.h> #include <tbb/parallel_for_each.h> #include <tbb/parallel_sort.h> /** * Enable if Iterable is not random access iterable */ template<class BasisType> tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis, std::forward_iterator_tag) { tbb::concurrent_vector<uint32_t> res; tbb::parallel_for_each(basis.begin(), basis.end(), [&](uint32_t elt) { res.emplace_back(elt); }); tbb::parallel_sort(res.begin(), res.end()); return res; } template<class BasisType> tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis, std::random_access_iterator_tag) { tbb::concurrent_vector<uint32_t> res(basis.size(), 0u); tbb::parallel_for(std::size_t(0u), basis.size(), [&](std::size_t idx) { res[idx] = basis[idx]; }); return res; } template<class BasisType> inline tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis) { using DecayedBasisType = typename std::decay<BasisType>::type; using IteratorType = typename std::result_of<decltype(&DecayedBasisType::begin)(BasisType)>::type; return parallelConstructBasis(basis, typename std::iterator_traits<IteratorType>::iterator_category()); }
28.702128
107
0.75315
cecri
97af8f553fd0ca2d14f6905218236556ec82f11a
5,132
tcc
C++
include/lvr2/util/ClusterBiMap.tcc
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
38
2019-06-19T15:10:35.000Z
2022-02-16T03:08:24.000Z
include/lvr2/util/ClusterBiMap.tcc
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
9
2019-06-19T16:19:51.000Z
2021-09-17T08:31:25.000Z
include/lvr2/util/ClusterBiMap.tcc
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
13
2019-04-16T11:50:32.000Z
2020-11-26T07:47:44.000Z
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ClusterBiMap.tcc * * @date 17.06.2017 * @author Johan M. von Behren <johan@vonbehren.eu> */ #include <algorithm> using std::remove; namespace lvr2 { template <typename HandleT> Cluster<HandleT>& ClusterBiMap<HandleT>::getC(ClusterHandle clusterHandle) { return m_cluster[clusterHandle]; } template <typename HandleT> const Cluster<HandleT>& ClusterBiMap<HandleT>::getCluster(ClusterHandle clusterHandle) const { return m_cluster[clusterHandle]; } template <typename HandleT> const Cluster<HandleT>& ClusterBiMap<HandleT>::operator[](ClusterHandle clusterHandle) const { return m_cluster[clusterHandle]; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::createCluster() { ClusterHandle newHandle(m_cluster.size()); m_cluster.push(Cluster<HandleT>()); return newHandle; } template <typename HandleT> void ClusterBiMap<HandleT>::removeCluster(ClusterHandle clusterHandle) { auto cluster = getC(clusterHandle); // Substract number of handles in removed cluster from number of all handles in set m_numHandles -= cluster.handles.size(); // Remove handles in cluster from cluster map for (auto handle: cluster.handles) { m_clusterMap.erase(handle); } // Remove cluster m_cluster.erase(clusterHandle); } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::addToCluster(ClusterHandle clusterHandle, HandleT handle) { getC(clusterHandle).handles.push_back(handle); m_clusterMap.insert(handle, clusterHandle); ++m_numHandles; return clusterHandle; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::removeFromCluster(ClusterHandle clusterHandle, HandleT handle) { auto& handles = getC(clusterHandle).handles; handles.erase(remove(handles.begin(), handles.end(), handle), handles.end()); m_clusterMap.erase(handle); --m_numHandles; return clusterHandle; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::getClusterH(HandleT handle) const { return m_clusterMap[handle]; } template <typename HandleT> OptionalClusterHandle ClusterBiMap<HandleT>::getClusterOf(HandleT handle) const { auto maybe = m_clusterMap.get(handle); if (maybe) { return *maybe; } return OptionalClusterHandle(); } template <typename HandleT> size_t ClusterBiMap<HandleT>::numCluster() const { return m_cluster.numUsed(); } template <typename HandleT> size_t ClusterBiMap<HandleT>::numHandles() const { return m_numHandles; } template <typename HandleT> void ClusterBiMap<HandleT>::reserve(size_t newCap) { m_cluster.reserve(newCap); m_clusterMap.reserve(newCap); } template<typename HandleT> ClusterBiMapIterator<HandleT>& ClusterBiMapIterator<HandleT>::operator++() { ++m_iterator; return *this; } template<typename HandleT> bool ClusterBiMapIterator<HandleT>::operator==(const ClusterBiMapIterator& other) const { return m_iterator == other.m_iterator; } template<typename HandleT> bool ClusterBiMapIterator<HandleT>::operator!=(const ClusterBiMapIterator& other) const { return m_iterator != other.m_iterator; } template<typename HandleT> ClusterHandle ClusterBiMapIterator<HandleT>::operator*() const { return *m_iterator; } template <typename HandleT> ClusterBiMapIterator<HandleT> ClusterBiMap<HandleT>::begin() const { return m_cluster.begin(); } template <typename HandleT> ClusterBiMapIterator<HandleT> ClusterBiMap<HandleT>::end() const { return m_cluster.end(); } } // namespace lvr2
27.891304
99
0.75039
uos
97b5ad3f88874a5ef67632c787ae9b65005b5053
1,021
cpp
C++
Lab8/Date.cpp
RustyRaptor/CS271
3d6787a5bf6bdd69176a685124ffcfee44de2d59
[ "MIT" ]
null
null
null
Lab8/Date.cpp
RustyRaptor/CS271
3d6787a5bf6bdd69176a685124ffcfee44de2d59
[ "MIT" ]
null
null
null
Lab8/Date.cpp
RustyRaptor/CS271
3d6787a5bf6bdd69176a685124ffcfee44de2d59
[ "MIT" ]
null
null
null
// CS271 - Lab Assignment: #8 // Program name: C++ Classes // Purpose of program: Some classes in C++ // written by: Ziad Arafat // Date Written: 2020-04-12 #include "Date.h" using namespace std; unsigned int month; unsigned int day; unsigned int year; Date::Date( ) { month = 1; day = 1; year = 1980; } Date::Date( int m, int d, int y ) { month = m; day = d; year = y; } void Date::setMonth( int m ) { if (m >= 1 && m <= 12){ month = m; } } void Date::setDay( int d ) { if (d >= 1 && d <= 31){ day = d; } } void Date::setYear( int y ) { if (y >= 1980 && y <= 2100){ year = y; } } int Date::getMonth( ) { return month; } int Date::getDay( ) { return day; } int Date::getYear( ) { return year; } void Date::print( ) { cout << setfill( '0' ) << setw( 2 ) << getMonth( ) << "/" << setfill( '0' ) << setw( 2 ) << getDay( ) << "/" << setfill( '0' ) << setw( 4 ) << getYear( ) << endl; }
16.206349
63
0.481881
RustyRaptor
97b76d7ee77235cf4e0ebff11a4e2b84d1427b18
14,364
cpp
C++
admin/wmi/wbem/providers/win32provider/sessionandconnections/dll/connectiontosession.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/providers/win32provider/sessionandconnections/dll/connectiontosession.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/providers/win32provider/sessionandconnections/dll/connectiontosession.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/****************************************************************** ConnectionToSession.CPP -- C provider class implementation Copyright (c) 2000-2001 Microsoft Corporation, All Rights Reserved Description: Association between Connection To Session ******************************************************************/ #include "precomp.h" #include "ConnectionToSession.h" CConnectionToSession MyCConnectionToSession ( PROVIDER_NAME_CONNECTIONTOSESSION , Namespace ) ; /***************************************************************************** * * FUNCTION : CConnectionToSession::CConnectionToSession * * DESCRIPTION : Constructor * *****************************************************************************/ CConnectionToSession :: CConnectionToSession ( LPCWSTR lpwszName, LPCWSTR lpwszNameSpace ) : Provider ( lpwszName , lpwszNameSpace ) { } /***************************************************************************** * * FUNCTION : CConnectionToSession::~CConnectionToSession * * DESCRIPTION : Destructor * *****************************************************************************/ CConnectionToSession :: ~CConnectionToSession () { } /***************************************************************************** * * FUNCTION : CConnectionToSession::EnumerateInstances * * DESCRIPTION : Returns all the instances of this class. * *****************************************************************************/ HRESULT CConnectionToSession :: EnumerateInstances ( MethodContext *pMethodContext, long lFlags ) { HRESULT hRes = WBEM_S_NO_ERROR ; DWORD dwPropertiesReq = CONNECTIONSTOSESSION_ALL_PROPS; hRes = EnumConnectionInfo ( L"", L"", pMethodContext, dwPropertiesReq ); return hRes ; } /***************************************************************************** * * FUNCTION : CConnectionToSession::GetObject * * DESCRIPTION : Find a single instance based on the key properties for the * class. * *****************************************************************************/ HRESULT CConnectionToSession :: GetObject ( CInstance *pInstance, long lFlags , CFrameworkQuery &Query ) { HRESULT hRes = WBEM_S_NO_ERROR; CHString t_Connection ; CHString t_Session; if ( pInstance->GetCHString ( IDS_Connection , t_Connection ) == FALSE ) { hRes = WBEM_E_INVALID_PARAMETER ; } if ( SUCCEEDED ( hRes ) ) { if ( pInstance->GetCHString ( IDS_Session , t_Session ) == FALSE ) { hRes = WBEM_E_INVALID_PARAMETER ; } } if ( SUCCEEDED ( hRes ) ) { CHString t_ConnComputerName; CHString t_ConnShareName; CHString t_ConnUserName; hRes = GetConnectionsKeyVal ( t_Connection, t_ConnComputerName, t_ConnShareName, t_ConnUserName ); if ( SUCCEEDED ( hRes ) ) { CHString t_SessComputerName; CHString t_SessUserName; hRes = GetSessionKeyVal ( t_Session, t_SessComputerName, t_SessUserName ); if ( SUCCEEDED ( hRes ) ) { // now check the shares in t_Connection and t_Session should match hRes = _wcsicmp ( t_ConnComputerName, t_SessComputerName ) == 0 ? hRes : WBEM_E_NOT_FOUND; if ( SUCCEEDED ( hRes ) ) { hRes = _wcsicmp ( t_ConnUserName, t_SessUserName ) == 0 ? hRes : WBEM_E_NOT_FOUND; if ( SUCCEEDED ( hRes ) ) { #ifdef NTONLY hRes = FindAndSetNTConnection ( t_ConnShareName.GetBuffer(0), t_ConnComputerName, t_ConnUserName, 0, pInstance, NoOp ); #endif #if 0 #ifdef WIN9XONLY hRes = FindAndSet9XConnection ( t_ConnShareName, t_ConnComputerName, t_ConnUserName, 0, pInstance, NoOp ); #endif #endif } } } } } return hRes ; } #ifdef NTONLY /***************************************************************************** * * FUNCTION : CConnectionToSession::EnumNTConnectionsFromComputerToShare * * DESCRIPTION : Enumerating all the connections made from a computer to * a given share * *****************************************************************************/ HRESULT CConnectionToSession :: EnumNTConnectionsFromComputerToShare ( LPWSTR a_ComputerName, LPWSTR a_ShareName, MethodContext *pMethodContext, DWORD dwPropertiesReq ) { HRESULT hRes = WBEM_S_NO_ERROR; NET_API_STATUS t_Status = NERR_Success; DWORD dwNoOfEntriesRead = 0; DWORD dwTotalConnections = 0; DWORD dwResumeHandle = 0; CONNECTION_INFO *pBuf = NULL; CONNECTION_INFO *pTmpBuf = NULL; LPWSTR t_ComputerName = NULL; if ( a_ComputerName && a_ComputerName[0] != L'\0' ) { //let's skip the \\ chars t_ComputerName = a_ComputerName + 2; } // ShareName and Computer Name both cannot be null at the same time while ( TRUE ) { if ( a_ShareName[0] != L'\0' ) { t_Status = NetConnectionEnum( NULL, a_ShareName, 1, (LPBYTE *) &pBuf, -1, &dwNoOfEntriesRead, &dwTotalConnections, &dwResumeHandle ); } else if ( a_ComputerName[0] != L'\0' ) { t_Status = NetConnectionEnum( NULL, a_ComputerName, 1, (LPBYTE *) &pBuf, -1, &dwNoOfEntriesRead, &dwTotalConnections, &dwResumeHandle ); } if ( t_Status == NERR_Success ) { if ( dwNoOfEntriesRead == 0 ) { break; } else if ( dwNoOfEntriesRead > 0 ) { try { pTmpBuf = pBuf; for ( int i = 0; i < dwNoOfEntriesRead; i++, pTmpBuf++ ) { if (pTmpBuf->coni1_netname && pBuf->coni1_username) { CInstancePtr pInstance ( CreateNewInstance ( pMethodContext ), FALSE ); hRes = LoadInstance ( pInstance, a_ShareName, t_ComputerName ? t_ComputerName : a_ComputerName, pTmpBuf, dwPropertiesReq ); if ( SUCCEEDED ( hRes ) ) { hRes = pInstance->Commit(); if ( FAILED ( hRes ) ) { break; } } else { break; } } } } catch ( ... ) { NetApiBufferFree ( pBuf ); pBuf = NULL; throw; } NetApiBufferFree ( pBuf ); pBuf = NULL; } } else { if ( t_Status != ERROR_MORE_DATA ) { if ( t_Status == ERROR_ACCESS_DENIED ) { hRes = WBEM_E_ACCESS_DENIED; } else { if ( t_Status == ERROR_NOT_ENOUGH_MEMORY ) { hRes = WBEM_E_OUT_OF_MEMORY; } else { hRes = WBEM_E_FAILED; } } break; } } } return hRes; } #endif #if 0 #ifdef WIN9XONLY /***************************************************************************** * * FUNCTION : CConnectionToSession::Enum9XConnectionsFromComputerToShare * * DESCRIPTION : Enumerating all the connections made from a computer to * a given share * *****************************************************************************/ HRESULT CConnectionToSession :: Enum9XConnectionsFromComputerToShare ( LPWSTR a_ComputerName, LPWSTR a_ShareName, MethodContext *pMethodContext, DWORD dwPropertiesReq ) { HRESULT hRes = WBEM_S_NO_ERROR; NET_API_STATUS t_Status = NERR_Success; DWORD dwNoOfEntriesRead = 0; DWORD dwTotalConnections = 0; BOOL bFound = FALSE; CONNECTION_INFO * pBuf = NULL; CONNECTION_INFO * pTmpBuf = NULL; DWORD dwBufferSize = MAX_ENTRIES * sizeof( CONNECTION_INFO ); pBuf = ( CONNECTION_INFO *) malloc(dwBufferSize); if ( pBuf != NULL ) { try { t_Status = NetConnectionEnum( NULL, (char FAR *) ( a_ShareName ), // ShareName 1, (char *) pBuf, ( unsigned short )dwBufferSize, ( unsigned short *) &dwNoOfEntriesRead, ( unsigned short *) &dwTotalConnections ); } catch ( ... ) { free ( pBuf ); pBuf = NULL; throw; } // otherwise we are not to frr the buffer, we have use it and then free the buffer. if ( ( dwNoOfEntriesRead < dwTotalConnections ) && ( t_Status == ERROR_MORE_DATA ) ) { free ( pBuf ); pBuf = NULL; pBuf = ( CONNECTION_INFO *) malloc( dwTotalConnections ); if ( pBuf != NULL ) { try { t_Status = NetConnectionEnum( NULL, (char FAR *) ( a_ShareName ), // ShareName 1, (char *) pBuf, ( unsigned short )dwBufferSize, ( unsigned short *) &dwNoOfEntriesRead, ( unsigned short *) &dwTotalConnections ); } catch ( ... ) { free ( pBuf ); pBuf = NULL; throw; } // We need to use the buffer before we free it } else { throw CHeap_Exception ( CHeap_Exception :: E_ALLOCATION_ERROR ) ; } } // The buffer is yet to be used if ( ( t_Status == NERR_Success ) && ( dwNoOfEntriesRead == dwTotalConnections ) ) { // use the buffer first and then free if ( pBuf != NULL ) { try { pTmpBuf = pBuf; for ( int i = 0; i < dwNoOfEntriesRead; i++, pTmpBuf ++) { CInstancePtr pInstance ( CreateNewInstance ( pMethodContext ), FALSE ); hRes = LoadInstance ( pInstance, a_ShareName, a_ComputerName, pTmpBuf, dwPropertiesReq ); if ( SUCCEEDED ( hRes ) ) { hRes = pInstance->Commit(); if ( FAILED ( hRes ) ) { break; } } } } catch ( ... ) { free ( pBuf ); pBuf = NULL; throw; } // finally free the buffer free (pBuf ); pBuf = NULL; } else { throw CHeap_Exception ( CHeap_Exception :: E_ALLOCATION_ERROR ) ; } } else { hRes = WBEM_E_FAILED; } } else { throw CHeap_Exception ( CHeap_Exception :: E_ALLOCATION_ERROR ) ; } return hRes; } #endif #endif /***************************************************************************** * * FUNCTION : CConnectionToSession:: LoadInstance * * DESCRIPTION : Loading an instance with the connection to Session info * *****************************************************************************/ HRESULT CConnectionToSession :: LoadInstance ( CInstance *pInstance, LPCWSTR a_Share, LPCWSTR a_Computer, CONNECTION_INFO *pBuf, DWORD dwPropertiesReq ) { HRESULT hRes = WBEM_S_NO_ERROR; LPWSTR ObjPath = NULL; LPWSTR SessObjPath = NULL; try { CHString t_NetName ( pBuf->coni1_netname ); if ( a_Share[0] != L'\0' ) { hRes = MakeObjectPath ( ObjPath, PROVIDER_NAME_CONNECTION, IDS_ComputerName, t_NetName ); if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( ObjPath, IDS_ShareName, a_Share ); } if ( SUCCEEDED ( hRes ) ) { hRes = MakeObjectPath ( SessObjPath, PROVIDER_NAME_SESSION, IDS_ComputerName, t_NetName ); } } else { hRes = MakeObjectPath ( ObjPath, PROVIDER_NAME_CONNECTION, IDS_ComputerName, a_Computer ); if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( ObjPath, IDS_ShareName, t_NetName ); } if ( SUCCEEDED ( hRes ) ) { MakeObjectPath ( SessObjPath, PROVIDER_NAME_SESSION, IDS_ComputerName, a_Computer); } } CHString t_UserName ( pBuf->coni1_username ); if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( ObjPath, IDS_UserName, t_UserName ); } if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( SessObjPath, IDS_UserName, t_UserName ); } if ( SUCCEEDED ( hRes ) ) { if ( pInstance->SetCHString ( IDS_Connection, ObjPath ) == FALSE ) { hRes = WBEM_E_PROVIDER_FAILURE ; } } if ( SUCCEEDED ( hRes ) ) { if ( pInstance->SetCHString ( IDS_Session, SessObjPath ) == FALSE ) { hRes = WBEM_E_PROVIDER_FAILURE ; } } } catch (...) { if (SessObjPath) { delete [] SessObjPath; SessObjPath = NULL; } if (ObjPath) { delete [] ObjPath; ObjPath = NULL; } throw; } if (SessObjPath) { delete [] SessObjPath; SessObjPath = NULL; } if (ObjPath) { delete [] ObjPath; ObjPath = NULL; } return hRes; } /***************************************************************************** * * FUNCTION : CConnectionToSession::GetSessionKeyVal * * DESCRIPTION : Parsing the key to get Connection Key Value * *****************************************************************************/ HRESULT CConnectionToSession::GetSessionKeyVal ( LPCWSTR a_Key, CHString &a_ComputerName, CHString &a_UserName ) { HRESULT hRes = WBEM_S_NO_ERROR; ParsedObjectPath *t_ObjPath; CObjectPathParser t_PathParser; DWORD dwAllKeys = 0; if ( t_PathParser.Parse( a_Key, &t_ObjPath ) == t_PathParser.NoError ) { try { hRes = t_ObjPath->m_dwNumKeys != 2 ? WBEM_E_INVALID_PARAMETER : hRes; if ( SUCCEEDED ( hRes ) ) { hRes = _wcsicmp ( t_ObjPath->m_pClass, PROVIDER_NAME_SESSION ) != 0 ? WBEM_E_INVALID_PARAMETER : hRes; if ( SUCCEEDED ( hRes ) ) { for ( int i = 0; i < 2; i++ ) { if (V_VT(&t_ObjPath->m_paKeys[i]->m_vValue) == VT_BSTR) { if ( _wcsicmp ( t_ObjPath->m_paKeys[i]->m_pName, IDS_ComputerName ) == 0 ) { a_ComputerName = t_ObjPath->m_paKeys[i]->m_vValue.bstrVal; dwAllKeys |= 1; } else if ( _wcsicmp ( t_ObjPath->m_paKeys[i]->m_pName, IDS_UserName ) == 0 ) { a_UserName = t_ObjPath->m_paKeys[i]->m_vValue.bstrVal; dwAllKeys |= 2; } } } if ( dwAllKeys != 3 ) { hRes = WBEM_E_INVALID_PARAMETER; } } else { hRes = WBEM_E_INVALID_PARAMETER; } } } catch ( ... ) { delete t_ObjPath; throw; } delete t_ObjPath; } else { hRes = WBEM_E_INVALID_PARAMETER; } return hRes; }
22.8
131
0.525968
npocmaka
b632914d2592fde88b55410d451e1a343d27e425
8,097
cpp
C++
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
// VisualBoyAdvance - Nintendo Gameboy/GameboyAdvance (TM) emulator. // Copyright (C) 1999-2003 Forgotten // Copyright (C) 2004 Forgotten and the VBA development team // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2, or(at your option) // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // AccelEditor.cpp : implementation file // #include "stdafx.h" #include "vba.h" #include "AccelEditor.h" #include "CmdAccelOb.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // AccelEditor dialog AccelEditor::AccelEditor(CWnd* pParent /*=NULL*/) : ResizeDlg(AccelEditor::IDD, pParent) { //{{AFX_DATA_INIT(AccelEditor) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT mgr = theApp.winAccelMgr; } void AccelEditor::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AccelEditor) DDX_Control(pDX, IDC_CURRENTS, m_currents); DDX_Control(pDX, IDC_ALREADY_AFFECTED, m_alreadyAffected); DDX_Control(pDX, IDC_COMMANDS, m_commands); DDX_Control(pDX, IDC_EDIT_KEY, m_key); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AccelEditor, CDialog) //{{AFX_MSG_MAP(AccelEditor) ON_BN_CLICKED(ID_OK, OnOk) ON_LBN_SELCHANGE(IDC_COMMANDS, OnSelchangeCommands) ON_BN_CLICKED(IDC_RESET, OnReset) ON_BN_CLICKED(IDC_ASSIGN, OnAssign) ON_BN_CLICKED(ID_CANCEL, OnCancel) ON_BN_CLICKED(IDC_REMOVE, OnRemove) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AccelEditor message handlers BOOL AccelEditor::OnInitDialog() { CDialog::OnInitDialog(); DIALOG_SIZER_START( sz ) DIALOG_SIZER_ENTRY( IDC_STATIC1, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_STATIC2, DS_MoveY) DIALOG_SIZER_ENTRY( IDC_STATIC3, DS_MoveX | DS_MoveY) DIALOG_SIZER_ENTRY( IDC_ALREADY_AFFECTED, DS_MoveY) DIALOG_SIZER_ENTRY( ID_OK, DS_MoveX) DIALOG_SIZER_ENTRY( ID_CANCEL, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_ASSIGN, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_REMOVE, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_RESET, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_CLOSE, DS_MoveY) DIALOG_SIZER_ENTRY( IDC_COMMANDS, DS_SizeX | DS_SizeY) DIALOG_SIZER_ENTRY( IDC_CURRENTS, DS_MoveX | DS_SizeY) DIALOG_SIZER_ENTRY( IDC_EDIT_KEY, DS_MoveX | DS_MoveY) DIALOG_SIZER_END() SetData(sz, TRUE, HKEY_CURRENT_USER, "Software\\Emulators\\VisualBoyAdvance\\Viewer\\AccelEditor", NULL); InitCommands(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void AccelEditor::InitCommands() { m_commands.ResetContent(); m_alreadyAffected.SetWindowText(""); POSITION pos = mgr.m_mapAccelString.GetStartPosition(); while(pos != NULL) { CString command; WORD wID; mgr.m_mapAccelString.GetNextAssoc(pos, command, wID); int index = m_commands.AddString(command); m_commands.SetItemData(index, wID); } // Update the currents accels associated with the selected command if (m_commands.SetCurSel(0) != LB_ERR) OnSelchangeCommands(); } void AccelEditor::OnCancel() { EndDialog(FALSE); } void AccelEditor::OnOk() { EndDialog(TRUE); } void AccelEditor::OnSelchangeCommands() { // Check if some commands exist. int index = m_commands.GetCurSel(); if (index == LB_ERR) return; WORD wIDCommand = LOWORD(m_commands.GetItemData(index)); m_currents.ResetContent(); CCmdAccelOb* pCmdAccel; if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel)) { CAccelsOb* pAccel; CString szBuffer; POSITION pos = pCmdAccel->m_Accels.GetHeadPosition(); // Add the keys to the 'currents keys' listbox. while (pos != NULL) { pAccel = pCmdAccel->m_Accels.GetNext(pos); pAccel->GetString(szBuffer); index = m_currents.AddString(szBuffer); // and a pointer to the accel object. m_currents.SetItemData(index, (DWORD_PTR)pAccel); } } // Init the key editor // m_pKey->ResetKey(); } void AccelEditor::OnReset() { mgr.Default(); InitCommands(); // update the listboxes. } void AccelEditor::OnAssign() { // Control if it's not already affected CCmdAccelOb* pCmdAccel; CAccelsOb* pAccel; WORD wIDCommand; POSITION pos; WORD wKey; bool bCtrl, bAlt, bShift; if (!m_key.GetAccelKey(wKey, bCtrl, bAlt, bShift)) return; // no valid key, abort int count = m_commands.GetCount(); int index; for (index = 0; index < count; index++) { wIDCommand = LOWORD(m_commands.GetItemData(index)); mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel); pos = pCmdAccel->m_Accels.GetHeadPosition(); while (pos != NULL) { pAccel = pCmdAccel->m_Accels.GetNext(pos); if (pAccel->IsEqual(wKey, bCtrl, bAlt, bShift)) { // the key is already affected (in the same or other command) m_alreadyAffected.SetWindowText(pCmdAccel->m_szCommand); m_key.SetSel(0, -1); return; // abort } } } // OK, we can add the accel key in the currently selected group index = m_commands.GetCurSel(); if (index == LB_ERR) return; // Get the object who manage the accels list, associated to the command. wIDCommand = LOWORD(m_commands.GetItemData(index)); if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel) != TRUE) return; BYTE cVirt = 0; if (bCtrl) cVirt |= FCONTROL; if (bAlt) cVirt |= FALT; if (bShift) cVirt |= FSHIFT; cVirt |= FVIRTKEY; // Create the new key... pAccel = new CAccelsOb(cVirt, wKey, false); ASSERT(pAccel != NULL); // ...and add in the list. pCmdAccel->m_Accels.AddTail(pAccel); // Update the listbox. CString szBuffer; pAccel->GetString(szBuffer); index = m_currents.AddString(szBuffer); m_currents.SetItemData(index, (DWORD_PTR)pAccel); // Reset the key editor. m_key.ResetKey(); } void AccelEditor::OnRemove() { // Some controls int indexCurrent = m_currents.GetCurSel(); if (indexCurrent == LB_ERR) return; // 2nd part. int indexCmd = m_commands.GetCurSel(); if (indexCmd == LB_ERR) return; // Ref to the ID command WORD wIDCommand = LOWORD(m_commands.GetItemData(indexCmd)); // Run through the accels,and control if it can be deleted. CCmdAccelOb* pCmdAccel; if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel) == TRUE) { CAccelsOb* pAccel; CAccelsOb* pAccelCurrent = (CAccelsOb*)(m_currents.GetItemData(indexCurrent)); CString szBuffer; POSITION pos = pCmdAccel->m_Accels.GetHeadPosition(); POSITION PrevPos; while (pos != NULL) { PrevPos = pos; pAccel = pCmdAccel->m_Accels.GetNext(pos); if (pAccel == pAccelCurrent) { if (!pAccel->m_bLocked) { // not locked, so we delete the key pCmdAccel->m_Accels.RemoveAt(PrevPos); delete pAccel; // and update the listboxes/key editor/static text m_currents.DeleteString(indexCurrent); m_key.ResetKey(); m_alreadyAffected.SetWindowText(""); return; } else { systemMessage(0,"Unable to remove this\naccelerator (Locked)"); return; } } } systemMessage(0,"internal error (CAccelDlgHelper::Remove : pAccel unavailable)"); return; } systemMessage(0,"internal error (CAccelDlgHelper::Remove : Lookup failed)"); }
27.824742
85
0.681116
pdpdds
b63479c43fe8c989fc03537f6a2975891c2d8806
124
hpp
C++
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
1
2021-04-03T00:18:45.000Z
2021-04-03T00:18:45.000Z
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
null
null
null
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
null
null
null
#pragma once namespace litmus { enum class verbosity_t { NONE = 0, COMPACT = 1, NORMAL = 2, DETAILED = 3 }; }
10.333333
23
0.596774
JessyDL
b63514f9432f7c5ca3f8514c9e50581e878cb984
1,005
hpp
C++
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
// // Created by Javier Peralta on 5/31/18. // #ifndef SVM_DIFFERENTIALEVOLUTION_HPP #define SVM_DIFFERENTIALEVOLUTION_HPP #include "../Data.hpp" #include "../OptimizationProblem.hpp" class DifferentialEvolution { public: friend class Individual; class Individual; private: unsigned max_evals; unsigned num_vars; double __cr, __F; OptimizationProblem *__problem; bool minimize; std::vector<Individual> population; std::vector<int> get_parent_idx(); public: DifferentialEvolution(std::vector<Individual> &pop, unsigned max_evals, double cr, double F, OptimizationProblem *problem, ProblemType type = ProblemType::MINIMIZE); Individual getBest(); bool iterate(); }; class DifferentialEvolution::Individual{ friend class DifferentialEvolution; protected: vect data; double value; public: vect get_data(); double get_value(); void set_value(double val); explicit Individual(vect &dat); Individual(vect &dat, double val); }; #endif //SVM_DIFFERENTIALEVOLUTION_HPP
22.840909
167
0.759204
nottu
b637fe4d30b266db56418882aa4a463fc1d8b7cc
1,704
hpp
C++
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
#ifndef ACTAN_TOOLS_SENSORS_HPP #define ACTAN_TOOLS_SENSORS_HPP #if defined(__float128) #define depth_level __float128 #elif defined(_Float128) #define depth_level _Float128 #else #define depth_level long double #endif #include <hmath/core.hpp> namespace actan { namespace sensor { class Sensor { private: hmath::DualQuaternion<depth_level> mounting_position = { 1,0,0,0,1,0,0,0 }; public: Sensor(); ~Sensor(); void setMountingPosition(hmath::DualQuaternion<depth_level>); void setMountingPosition(hmath::Vector3<depth_level>, hmath::Quaternion<depth_level>); void setMountingPosition(hmath::Quaternion<depth_level>, hmath::Vector3<depth_level>); }; class InertialSensor : public Sensor { private: hmath::Vector3<depth_level> angular_rates_limit, raw_acc_limits; hmath::Vector3<depth_level> latest_angular_rates, latest_raw_acceleration; public: InertialSensor(); ~InertialSensor(); }; class PinholeCamera : public Sensor { private: depth_level focal_length, aperture; public: PinholeCamera(); ~PinholeCamera(); }; } class AHRS : public sensor::InertialSensor { private: hmath::Quaternion<depth_level> orientation; hmath::Vector3<depth_level> free_acceleration; public: AHRS(); ~AHRS(); template<typename T> void setOrientation(hmath::Vector3<T>); template<typename T> void setFreeAcceleration(hmath::Vector3<T>); }; } #endif
24.342857
98
0.619131
oliver-peoples
b63d21667567b563bbfa8923303d0ee361244700
2,794
hpp
C++
src/shape/Bunker.hpp
newnone/Non-Gravitar
9d21cf7ab5ef49f6976fcaf25fa01cacbb209740
[ "MIT" ]
null
null
null
src/shape/Bunker.hpp
newnone/Non-Gravitar
9d21cf7ab5ef49f6976fcaf25fa01cacbb209740
[ "MIT" ]
null
null
null
src/shape/Bunker.hpp
newnone/Non-Gravitar
9d21cf7ab5ef49f6976fcaf25fa01cacbb209740
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2018 Oscar B. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef NON_GRAVITAR_BUNKER_HPP #define NON_GRAVITAR_BUNKER_HPP #include <vector> #include "ClosedShape.hpp" #include "Rectangle.hpp" #include "RoundMissile.hpp" #include "ShapeVisitor.hpp" template<typename T> using vector = std::vector<T>; namespace gvt { class Bunker: public ClosedShape { private: double mDelay{0}; vector<double> mDirections; unsigned mCurr{0}; static unsigned const constexpr WIDTH = 66; static unsigned const constexpr HEIGHT = 45; BoundingPolygon polygonFactory() const; public: Bunker(Vectord position, size_t directions); inline double width() const override; inline double height() const override; /** * Sets the missile delay, i.e. the time to wait before the next * missile is shot. */ inline void missileDelay (double delay); /** * Getter method of @c missileDelay(double). */ inline double missileDelay () const; /** * @return a @c RoundMissile instance shot by the calling @c Bunker * object, with a random velocity vector of unitary norm. */ shared_ptr<RoundMissile> shoot(double speed, long lifespan, double radius); inline unsigned directions() const; void accept (ShapeVisitor &visitor) override; bool operator==(Shape const &o) const override; }; } namespace gvt { void Bunker::missileDelay (double delay) { mDelay = delay; } double Bunker::missileDelay () const { return mDelay; } // Implementation of inline Bunker functions double Bunker::width() const { return WIDTH; } double Bunker::height() const { return HEIGHT; } unsigned Bunker::directions() const { return mDirections.size(); } } #endif
28.222222
81
0.725125
newnone
b64307fb369aa01cc588abc7842c0b68c5383a69
61,868
cpp
C++
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
26
2019-09-04T17:48:41.000Z
2022-02-23T17:04:24.000Z
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
57
2019-09-06T21:37:34.000Z
2022-03-09T02:13:46.000Z
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
24
2019-09-04T23:12:07.000Z
2022-03-30T02:06:22.000Z
#include <rppi_filter_operations.h> #include <rppdefs.h> #include "rppi_validate.hpp" #ifdef HIP_COMPILE #include <hip/rpp_hip_common.hpp> #include "hip/hip_declarations.hpp" #elif defined(OCL_COMPILE) #include <cl/rpp_cl_common.hpp> #include "cl/cl_declarations.hpp" #endif //backend #include <stdio.h> #include <iostream> #include <fstream> #include <chrono> using namespace std::chrono; #include "cpu/host_filter_operations.hpp" /******************** box_filter ********************/ RppStatus rppi_box_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** sobel_filter ********************/ RppStatus rppi_sobel_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** median_filter ********************/ RppStatus rppi_median_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** custom_convolution ********************/ /******************** non_max_suppression ********************/ RppStatus rppi_non_max_suppression_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** gaussian_filter ********************/ RppStatus rppi_gaussian_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** nonlinear_filter ********************/ RppStatus rppi_nonlinear_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } // ********************************** custom convolution *************************************** RppStatus rppi_custom_convolution_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; }
37.816626
101
0.457749
shobana-mcw
b6440496a92b62f842701964c833da19c16803e3
906
cpp
C++
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
#include "guinsoodb/parser/statement/transaction_statement.hpp" #include "guinsoodb/parser/transformer.hpp" namespace guinsoodb { unique_ptr<TransactionStatement> Transformer::TransformTransaction(guinsoodb_libpgquery::PGNode *node) { auto stmt = reinterpret_cast<guinsoodb_libpgquery::PGTransactionStmt *>(node); D_ASSERT(stmt); switch (stmt->kind) { case guinsoodb_libpgquery::PG_TRANS_STMT_BEGIN: case guinsoodb_libpgquery::PG_TRANS_STMT_START: return make_unique<TransactionStatement>(TransactionType::BEGIN_TRANSACTION); case guinsoodb_libpgquery::PG_TRANS_STMT_COMMIT: return make_unique<TransactionStatement>(TransactionType::COMMIT); case guinsoodb_libpgquery::PG_TRANS_STMT_ROLLBACK: return make_unique<TransactionStatement>(TransactionType::ROLLBACK); default: throw NotImplementedException("Transaction type %d not implemented yet", stmt->kind); } } } // namespace guinsoodb
39.391304
104
0.825607
GuinsooLab
b6474bdf4746d833e16134adc8dfd774567d6580
4,735
cpp
C++
tools/extras/irstlm/src/doc.cpp
scscscscscsc/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
4
2016-06-05T14:19:32.000Z
2016-06-07T09:21:10.000Z
tools/extras/irstlm/src/doc.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
tools/extras/irstlm/src/doc.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** IrstLM: IRST Language Model Toolkit, compile LM Copyright (C) 2006 Marcello Federico, ITC-irst Trento, Italy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include <math.h> #include <assert.h> #include "util.h" #include "mfstream.h" #include "mempool.h" #include "htable.h" #include "dictionary.h" #include "n_gram.h" #include "doc.h" using namespace std; doc::doc(dictionary* d,char* docfname) { dict=d; n=0; m=0; V=new int[dict->size()]; N=new int[dict->size()]; T=new int[dict->size()]; cd=-1; dfname=docfname; df=NULL; binary=false; }; doc::~doc() { delete [] V; delete [] N; delete [] T; } int doc::open() { df=new mfstream(dfname,ios::in); char header[100]; df->getline(header,100); if (sscanf(header,"DoC %d",&n) && n>0) binary=true; else if (sscanf(header,"%d",&n) && n>0) binary=false; else { exit_error(IRSTLM_ERROR_DATA, "doc::open() error: wrong header\n"); } cerr << "opening: " << n << (binary?" bin-":" txt-") << "docs\n"; cd=-1; return 1; } int doc::reset() { cd=-1; m=0; df->close(); delete df; open(); return 1; } int doc::read() { if (cd >=(n-1)) return 0; m=0; for (int i=0; i<dict->size(); i++) N[i]=0; if (binary) { df->read((char *)&m,sizeof(int)); df->read((char *)V,m * sizeof(int)); df->read((char *)T,m * sizeof(int)); for (int i=0; i<m; i++) { N[V[i]]=T[i]; } } else { int eod=dict->encode(dict->EoD()); int bod=dict->encode(dict->BoD()); ngram ng(dict); while((*df) >> ng) { if (ng.size>0) { if (*ng.wordp(1)==bod) { ng.size=0; continue; } if (*ng.wordp(1)==eod) { ng.size=0; break; } N[*ng.wordp(1)]++; if (N[*ng.wordp(1)]==1)V[m++]=*ng.wordp(1); } } } cd++; return 1; } int doc::savernd(char* fname,int num) { assert((df!=NULL) && (cd==-1)); srand(100); mfstream out(fname,ios::out); out << "DoC\n"; out.write((const char*) &n,sizeof(int)); cerr << "n=" << n << "\n"; //first select num random docs char taken[n]; int r; for (int i=0; i<n; i++) taken[i]=0; for (int d=0; d<num; d++) { while((r=(rand() % n)) && taken[r]) {}; cerr << "random document found " << r << "\n"; taken[r]++; reset(); for (int i=0; i<=r; i++) read(); out.write((const char *)&m,sizeof(int)); out.write((const char*) V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*) &N[V[i]],sizeof(int)); } //write the rest of files reset(); for (int d=0; d<n; d++) { read(); if (!taken[d]) { out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } else { cerr << "do not save doc " << d << "\n"; } } //out.close(); reset(); return 1; } int doc::save(char* fname) { assert((df!=NULL) && (cd==-1)); mfstream out(fname,ios::out); out << "DoC "<< n << "\n"; for (int d=0; d<n; d++) { read(); out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } //out.close(); reset(); return 1; } int doc::save(char* fname, int bsz) { assert((df!=NULL) && (cd==-1)); char name[100]; int i=0; while (cd < (n-1)) { // at least one document sprintf(name,"%s.%d",fname,++i); mfstream out(name,ios::out); int csz=(cd+bsz)<n?bsz:(n-cd-1); out << "DoC "<< csz << "\n"; for (int d=0; d<csz; d++) { read(); out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } out.close(); } reset(); return 1; }
19.729167
79
0.530729
scscscscscsc
b64993be7464496ca9e61403286e83785c0c32b5
8,796
cpp
C++
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
2
2021-08-06T19:40:34.000Z
2021-09-06T23:07:47.000Z
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
// // Variant.cpp // Relation-Based Simulator (RBS) // // Created by Ali Jenabidehkordi on 19.08.18. // Copyright © 2018 Ali Jenabidehkordi. All rights reserved. // #include "Variant.h" namespace rbs::variables { Variant::Variant() : p_id{ TypeID::None } , p_value{} { } Variant::Variant(const Variant &other) = default; Variant::Variant(Variant &&other) { p_id = std::move(other.p_id); p_value = std::move(other.p_value); } bool Variant::hasValue() const { return p_id != TypeID::None; } bool Variant::isEmpty() const { return p_id == TypeID::None; } void Variant::clear() { p_id = TypeID::None; } bool Variant::operator==(const Variant &other) const { if( p_id == other.p_id ) { switch (p_id) { case TypeID::None: return true; case TypeID::Vector1D: return std::get<space::Vector<1> >(p_value) == std::get<space::Vector<1> >(other.p_value); case TypeID::Vector2D: return std::get<space::Vector<2> >(p_value) == std::get<space::Vector<2> >(other.p_value); case TypeID::Vector3D: return std::get<space::Vector<3> >(p_value) == std::get<space::Vector<3> >(other.p_value); case TypeID::Point1D: return std::get<space::Point<1> >(p_value) == std::get<space::Point<1> >(other.p_value); case TypeID::Point2D: return std::get<space::Point<2> >(p_value) == std::get<space::Point<2> >(other.p_value); case TypeID::Point3D: return std::get<space::Point<3> >(p_value) == std::get<space::Point<3> >(other.p_value); case TypeID::Index1D: return std::get<space::Index<1> >(p_value) == std::get<space::Index<1> >(other.p_value); case TypeID::Index2D: return std::get<space::Index<2> >(p_value) == std::get<space::Index<2> >(other.p_value); case TypeID::Index3D: return std::get<space::Index<3> >(p_value) == std::get<space::Index<3> >(other.p_value); case TypeID::LongDouble: return std::get<long double>(p_value) == std::get<double>(other.p_value); case TypeID::Double: return std::get<double>(p_value) == std::get<double>(other.p_value); case TypeID::Float: return std::get<float>(p_value) == std::get<float>(other.p_value); case TypeID::UnsignedLongLong: return std::get<unsigned long long>(p_value) == std::get<unsigned long long>(other.p_value); case TypeID::UnsignedLong: return std::get<unsigned long>(p_value) == std::get<unsigned long>(other.p_value); case TypeID::UnsignedInt: return std::get<unsigned int>(p_value) == std::get<unsigned int>(other.p_value); case TypeID::UnsignedShort: return std::get<unsigned short>(p_value) == std::get<unsigned short>(other.p_value); case TypeID::UnsignedChar: return std::get<unsigned char>(p_value) == std::get<unsigned char>(other.p_value); case TypeID::LongLong: return std::get<long long>(p_value) == std::get<long long>(other.p_value); case TypeID::Long: return std::get<long>(p_value) == std::get<long>(other.p_value); case TypeID::Int: return std::get<int>(p_value) == std::get<int>(other.p_value); case TypeID::Short: return std::get<short>(p_value) == std::get<short>(other.p_value); case TypeID::Char: return std::get<char>(p_value) == std::get<char>(other.p_value); case TypeID::Bool: return std::get<bool>(p_value) == std::get<bool>(other.p_value); case TypeID::String: return std::get<std::string>(p_value) == std::get<std::string>(other.p_value); default: throw std::out_of_range("The type of the Variant is not recognized."); } } return false; } bool Variant::operator!=(const Variant &other) const { return !operator==(other); } variables::Variant::operator std::string() const { std::string ans = "Variant:{"; if(isEmpty()) { ans = ans + "empty"; } else { ans = ans + "type: " + type_to_string() + ", value: " + value_to_string(); } return ans + "}"; } std::string Variant::value_to_string() const { switch (p_id) { case TypeID::None: return "uninitialized"; case TypeID::Vector1D: return std::string(std::get<space::Vector<1> >(p_value)); case TypeID::Vector2D: return std::string(std::get<space::Vector<2> >(p_value)); case TypeID::Vector3D: return std::string(std::get<space::Vector<3> >(p_value)); case TypeID::Point1D: return std::string(std::get<space::Point<1> >(p_value)); case TypeID::Point2D: return std::string(std::get<space::Point<2> >(p_value)); case TypeID::Point3D: return std::string(std::get<space::Point<3> >(p_value)); case TypeID::Index1D: return std::string(std::get<space::Index<1> >(p_value)); case TypeID::Index2D: return std::string(std::get<space::Index<2> >(p_value)); case TypeID::Index3D: return std::string(std::get<space::Index<3> >(p_value)); case TypeID::LongDouble: return std::to_string(std::get<long double>(p_value)); case TypeID::Double: return std::to_string(std::get<double>(p_value)); case TypeID::Float: return std::to_string(std::get<float>(p_value)); case TypeID::UnsignedLongLong: return std::to_string(std::get<unsigned long long>(p_value)); case TypeID::UnsignedLong: return std::to_string(std::get<unsigned long>(p_value)); case TypeID::UnsignedInt: return std::to_string(std::get<unsigned int>(p_value)); case TypeID::UnsignedShort: return std::to_string(std::get<unsigned short>(p_value)); case TypeID::UnsignedChar: return std::to_string(std::get<unsigned char>(p_value)); case TypeID::LongLong: return std::to_string(std::get<long long>(p_value)); case TypeID::Long: return std::to_string(std::get<long>(p_value)); case TypeID::Int: return std::to_string(std::get<int>(p_value)); case TypeID::Short: return std::to_string(std::get<short>(p_value)); case TypeID::Char: return std::to_string(std::get<char>(p_value)); case TypeID::Bool: return std::to_string(std::get<bool>(p_value)); case TypeID::String: return std::get<std::string>(p_value); default: throw std::out_of_range("The type of the Variant is not recognized."); } } std::string Variant::type_to_string() const { switch (p_id) { case TypeID::None: return "none"; case TypeID::Vector1D: return "space::Vector<1>"; case TypeID::Vector2D: return "space::Vector<2>"; case TypeID::Vector3D: return "space::Vector<3>"; case TypeID::Point1D: return "space::Point<1>"; case TypeID::Point2D: return "space::Point<2>"; case TypeID::Point3D: return "space::Point<3>"; case TypeID::Index1D: return "space::Index<1>"; case TypeID::Index2D: return "space::Index<2>"; case TypeID::Index3D: return "space::Index<3>"; case TypeID::LongDouble: return "long double"; case TypeID::Double: return "double"; case TypeID::Float: return "float"; case TypeID::UnsignedLongLong: return "unsigned long long"; case TypeID::UnsignedLong: return "unsigned long"; case TypeID::UnsignedInt: return "unsigned int"; case TypeID::UnsignedShort: return "unsigned short"; case TypeID::UnsignedChar: return "unsigned char"; case TypeID::LongLong: return "long long"; case TypeID::Long: return "long"; case TypeID::Int: return "int"; case TypeID::Short: return "short"; case TypeID::Char: return "char"; case TypeID::Bool: return "bool"; case TypeID::String: return "std::string"; default: throw std::out_of_range("The type of the Variant is not recognized."); } } std::size_t Variant::index() const { return static_cast<std::size_t>(p_id) - 1; } void Variant::swap(Variant &other) { std::swap(p_id, other.p_id); std::swap(p_value, other.p_value); } Variant &Variant::operator =(Variant other) { swap(other); return *this; } std::ostream &operator <<(std::ostream &out, const Variant &variant) { return out << std::string(variant); } } // namespace rbs::variant
52.357143
135
0.593565
alijenabi
b649f164b0f698ac856b600e19c2c775a25ace8b
2,575
cpp
C++
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
null
null
null
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
1
2019-05-23T18:36:57.000Z
2019-05-23T18:58:32.000Z
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
6
2018-11-22T18:10:58.000Z
2020-06-26T16:55:35.000Z
//*************************************************************************** // Copyright 2017 OceanScan - Marine Systems & Technology, Lda. * //*************************************************************************** // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * //*************************************************************************** // Author: Ricardo Martins * //*************************************************************************** // IMC headers. #include <IMC/Base/InlineMessage.hpp> #include <IMC/Spec/EulerAngles.hpp> // Catch headers. #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("opsOnNull") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE_THROWS_AS(imsg.get(), std::runtime_error); REQUIRE(imsg.getSerializationSize() == 2); } TEST_CASE("serializeNull") { uint8_t bfr[128]; IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE(imsg.serialize(bfr) == 2); } TEST_CASE("equalOperatorBothNull") { IMC::InlineMessage<IMC::EulerAngles> a; IMC::InlineMessage<IMC::EulerAngles> b; REQUIRE(a == b); } TEST_CASE("equalOperatorOneNull") { IMC::EulerAngles msg; IMC::InlineMessage<IMC::EulerAngles> a; a.set(msg); IMC::InlineMessage<IMC::EulerAngles> b; REQUIRE(a != b); } TEST_CASE("getNull") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE_THROWS(imsg.get()); } TEST_CASE("getId") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE(imsg.getId() == IMC::Message::nullId()); IMC::EulerAngles msg; imsg.set(msg); REQUIRE(imsg.getId() == msg.getId()); } TEST_CASE("setByPointerCompareDereference") { IMC::InlineMessage<IMC::EulerAngles> imsg; IMC::EulerAngles msg; imsg.set(&msg); REQUIRE(*imsg == msg); }
32.1875
77
0.528155
paulosousadias
b64a0ca2541b8c7a1eb67199fe1d100f536c2f4d
10,723
cpp
C++
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPReportColumns.cpp : implementation of the CXTPReportColumns class. // // This file is a part of the XTREME REPORTCONTROL MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Common/XTPPropExchange.h" #include "XTPReportControl.h" #include "XTPReportHeader.h" #include "XTPReportColumn.h" #include "XTPReportColumns.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CXTPReportColumns CXTPReportColumns::CXTPReportColumns(CXTPReportControl* pControl) : m_pControl(pControl) { m_pGroupsOrder = new CXTPReportColumnOrder(this); m_pSortOrder = new CXTPReportColumnOrder(this); m_pTreeColumn = NULL; } CXTPReportColumns::~CXTPReportColumns() { Clear(); if (m_pGroupsOrder) m_pGroupsOrder->InternalRelease(); if (m_pSortOrder) m_pSortOrder->InternalRelease(); } void CXTPReportColumns::Clear() { // array cleanup for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { CXTPReportColumn* pColumn = m_arrColumns.GetAt(nColumn); if (pColumn) pColumn->InternalRelease(); } m_arrColumns.RemoveAll(); m_pSortOrder->Clear(); m_pGroupsOrder->Clear(); // clear variables which could be references to those values if (m_pControl && (m_pControl->GetColumns() == this)) m_pControl->SetFocusedColumn(NULL); } int CXTPReportColumnOrder::GetCount() const { return (int) m_arrColumns.GetSize(); } void CXTPReportColumns::Add(CXTPReportColumn* pColumn) { pColumn->m_pColumns = this; m_arrColumns.Add(pColumn); GetReportHeader()->OnColumnsChanged(xtpReportColumnOrderChanged | xtpReportColumnAdded, pColumn); } CXTPReportHeader* CXTPReportColumns::GetReportHeader() const { return m_pControl->GetReportHeader(); } void CXTPReportColumns::Remove(CXTPReportColumn* pColumn) { m_pGroupsOrder->Remove(pColumn); m_pSortOrder->Remove(pColumn); int nIndex = IndexOf(pColumn); if (nIndex != -1) { m_arrColumns.RemoveAt(nIndex); pColumn->InternalRelease(); GetReportHeader()->OnColumnsChanged(xtpReportColumnOrderChanged | xtpReportColumnRemoved, pColumn); } } int CXTPReportColumns::IndexOf(const CXTPReportColumn* pColumn) const { // array cleanup for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { if (m_arrColumns.GetAt(nColumn) == pColumn) return nColumn; } return -1; } void CXTPReportColumns::ResetSortOrder() { m_pSortOrder->Clear(); } void CXTPReportColumns::SetSortColumn(CXTPReportColumn* pColumn, BOOL bIncreasing) { ResetSortOrder(); m_pSortOrder->Add(pColumn, bIncreasing); } int CXTPReportColumns::ChangeColumnOrder(int nNewOrder, int nItemIndex) { if (nNewOrder < 0 || nItemIndex < 0) return -1; CXTPReportColumn* pColumn = GetAt(nItemIndex); if (pColumn) { if (nNewOrder == nItemIndex) return nNewOrder; if (nNewOrder > nItemIndex) nNewOrder--; m_arrColumns.RemoveAt(nItemIndex); m_arrColumns.InsertAt(nNewOrder, pColumn); } return nNewOrder; } int CXTPReportColumns::GetVisibleColumnsCount() const { int nVisibleCount = 0; int nCount = GetCount(); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn && pColumn->IsVisible()) nVisibleCount++; } return nVisibleCount; } void CXTPReportColumns::GetVisibleColumns(CXTPReportColumns& arrColumns) const { int nCount = GetCount(); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn && pColumn->IsVisible()) { arrColumns.m_arrColumns.Add(pColumn); pColumn->InternalAddRef(); } } } CXTPReportColumn* CXTPReportColumns::Find(int nItemIndex) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->GetItemIndex() == nItemIndex) return pColumn; } return NULL; } CXTPReportColumn* CXTPReportColumns::Find(const CString& strInternalName) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->GetInternalName() == strInternalName) return pColumn; } return NULL; } void CXTPReportColumns::InsertSortColumn(CXTPReportColumn* pColumn) { if (m_pSortOrder->IndexOf(pColumn) == -1) m_pSortOrder->Add(pColumn); } CXTPReportColumn* CXTPReportColumns::GetVisibleAt(int nIndex) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (!pColumn->IsVisible()) continue; if (nIndex == 0) return pColumn; nIndex--; } return NULL; } CXTPReportColumn* CXTPReportColumns::GetFirstVisibleColumn() const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->IsVisible()) return pColumn; } return NULL; } CXTPReportColumn* CXTPReportColumns::GetLastVisibleColumn() const { for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->IsVisible()) return pColumn; } return NULL; } void CXTPReportColumns::DoPropExchange(CXTPPropExchange* pPX) { int nItemIndex; CString strInternalName; if (pPX->IsStoring()) { int nCount = GetCount(); CXTPPropExchangeEnumeratorPtr pEnumerator(pPX->GetEnumerator(_T("Column"))); POSITION pos = pEnumerator->GetPosition(nCount, FALSE); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); CXTPPropExchangeSection secColumn(pEnumerator->GetNext(pos)); nItemIndex = pColumn->GetItemIndex(); strInternalName = pColumn->GetInternalName(); PX_Int(&secColumn, _T("ItemIndex"), nItemIndex); PX_String(&secColumn, _T("InternalName"), strInternalName); pColumn->DoPropExchange(&secColumn); } } else { CXTPPropExchangeEnumeratorPtr pEnumerator(pPX->GetEnumerator(_T("Column"))); POSITION pos = pEnumerator->GetPosition(0, FALSE); CXTPReportColumn tmpColumn(0, _T(""), 0); int i = 0; while (pos) { CXTPPropExchangeSection secColumn(pEnumerator->GetNext(pos)); CXTPReportColumn* pColumn = NULL; PX_Int(&secColumn, _T("ItemIndex"), nItemIndex, -1); if (pPX->GetSchema() > _XTP_SCHEMA_110) { PX_String(&secColumn, _T("InternalName"), strInternalName); if (!strInternalName.IsEmpty()) { pColumn = Find(strInternalName); // column data is exists but column is not in the collection. if (!pColumn) { // just read data to skeep (to be safe for array serialization) tmpColumn.DoPropExchange(&secColumn); continue; } } } if (!pColumn) pColumn = Find(nItemIndex); if (!pColumn) AfxThrowArchiveException(CArchiveException::badIndex); pColumn->DoPropExchange(&secColumn); ChangeColumnOrder(i, IndexOf(pColumn)); i++; } } CXTPPropExchangeSection secGroupsOrder(pPX->GetSection(_T("GroupsOrder"))); m_pGroupsOrder->DoPropExchange(&secGroupsOrder); CXTPPropExchangeSection secSortOrder(pPX->GetSection(_T("SortOrder"))); m_pSortOrder->DoPropExchange(&secSortOrder); } ///////////////////////////////////////////////////////////////////////////// // CXTPReportColumnOrder CXTPReportColumnOrder::CXTPReportColumnOrder(CXTPReportColumns* pColumns) : m_pColumns(pColumns) { } CXTPReportColumn* CXTPReportColumnOrder::GetAt(int nIndex) { if (nIndex >= 0 && nIndex < GetCount()) return m_arrColumns.GetAt(nIndex); else return NULL; } int CXTPReportColumnOrder::InsertAt(int nIndex, CXTPReportColumn* pColumn) { if (nIndex < 0) return -1; if (nIndex >= GetCount()) nIndex = GetCount(); int nPrevIndex = IndexOf(pColumn); if (nPrevIndex != -1) { if (nPrevIndex == nIndex) return nIndex; if (nIndex > nPrevIndex) nIndex--; if (nIndex == nPrevIndex) return nIndex; // change order m_arrColumns.RemoveAt(nPrevIndex); } m_arrColumns.InsertAt(nIndex, pColumn); return nIndex; } int CXTPReportColumnOrder::Add(CXTPReportColumn* pColumn, BOOL bSortIncreasing) { pColumn->m_bSortIncreasing = bSortIncreasing; return (int) m_arrColumns.Add(pColumn); } int CXTPReportColumnOrder::Add(CXTPReportColumn* pColumn) { return (int) m_arrColumns.Add(pColumn); } void CXTPReportColumnOrder::Clear() { m_arrColumns.RemoveAll(); } int CXTPReportColumnOrder::IndexOf(const CXTPReportColumn* pColumn) { int nCount = GetCount(); for (int i = 0; i < nCount; i++) { if (GetAt(i) == pColumn) return i; } return -1; } void CXTPReportColumnOrder::RemoveAt(int nIndex) { if (nIndex >= 0 && nIndex < GetCount()) m_arrColumns.RemoveAt(nIndex); } void CXTPReportColumnOrder::Remove(CXTPReportColumn* pColumn) { int nCount = GetCount(); for (int i = 0; i < nCount; i++) { if (GetAt(i) == pColumn) { m_arrColumns.RemoveAt(i); break; } } } void CXTPReportColumnOrder::DoPropExchange(CXTPPropExchange* pPX) { if (pPX->IsStoring()) { int nCount = GetCount(); PX_Int(pPX, _T("Count"), nCount, 0); for (int i = 0; i < nCount; i++) { CXTPReportColumn* pColumn = GetAt(i); if (pColumn) { int nItemIndex = pColumn->GetItemIndex(); CString strInternalName = pColumn->GetInternalName(); CString strParamName; strParamName.Format(_T("Column%i"), i); PX_Int(pPX, strParamName, nItemIndex, 0); strParamName.Format(_T("InternalName%i"), i); PX_String(pPX, strParamName, strInternalName); } } } else { Clear(); int nCount = 0; PX_Int(pPX, _T("Count"), nCount, 0); for (int i = 0; i < nCount; i++) { int nItemIndex = 0; CString strParamName; strParamName.Format(_T("Column%i"), i); PX_Int(pPX, strParamName, nItemIndex, 0); CXTPReportColumn* pColumn = NULL; if (pPX->GetSchema() > _XTP_SCHEMA_110) { strParamName.Format(_T("InternalName%i"), i); CString strInternalName; PX_String(pPX, strParamName, strInternalName); if (!strInternalName.IsEmpty()) pColumn = m_pColumns->Find(strInternalName); } if (!pColumn) pColumn = m_pColumns->Find(nItemIndex); if (pColumn) Add(pColumn); } } }
22.246888
101
0.69654
11Zero
b64aa8d9436b0552bbce48e8c47f37dbf5e429c0
1,248
cpp
C++
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 366_find_leaves_of_bianry_tree.cpp // leetcode_dfs // // Created by Hadley on 26.08.20. // Copyright © 2020 Hadley. All rights reserved. // #include <iostream> #include <fstream> #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> #include <map> #include <filesystem> #include <dirent.h> using namespace std; //Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: int dfs(TreeNode* root){ if(!root)return 0; int l=dfs(root->left)+1; int r=dfs(root->right)+1; int index=max(l,r)-1; if(index>=res.size())res.push_back({}); res[index].push_back(root->val); return max(l,r); } vector<vector<int>> findLeaves(TreeNode* root) { dfs(root); return res; } private: vector<vector<int>>res; };
22.285714
91
0.634615
Hadleyhzy
b64be8ad8172ca61b4bd07a4e0923083f1e615f6
601
cpp
C++
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
#include "Collisions.h" #include "Entity.h" Entity::Entity(EntityType type, fPoint position, bool flip, Player* parent) { this->type = type; this->position = position; this->flip = flip; this->parent = parent; toDelete = false; toRemove = false; flip = false; } Entity::~Entity() { } bool Entity::Update(float dt) { return true; } void Entity::Collision(Collider* c1, Collider* c2) { } void Entity::UIEvent(Element* element, ElementData&) { } fPoint Entity::GetDrawPosition(iPoint size) { fPoint output = position; output.x -= size.x / 2; output.y -= size.y / 2; return output; }
14.309524
75
0.678869
Paideieitor
b64e3db9d1c2e542b4b9ceda3ed50c6d1649a382
2,361
cpp
C++
app/src/main/cpp/XTexture.cpp
sk95120/Connrot
d19c878d99ae85eca3663c11897fc4de1772fbff
[ "Apache-2.0" ]
1
2021-11-30T04:52:16.000Z
2021-11-30T04:52:16.000Z
app/src/main/cpp/XTexture.cpp
ShiKe-And-His-Friends/Connrot
d19c878d99ae85eca3663c11897fc4de1772fbff
[ "Apache-2.0" ]
1
2019-08-27T01:34:46.000Z
2019-08-27T01:34:46.000Z
app/src/main/cpp/XTexture.cpp
sk95120/Connrot
d19c878d99ae85eca3663c11897fc4de1772fbff
[ "Apache-2.0" ]
1
2021-11-30T04:52:17.000Z
2021-11-30T04:52:17.000Z
// // Created by shike on 2/4/2020. // #include "XTexture.h" #include "XLog.h" #include "XEGL.h" #include "XShader.h" class CXTexture:public XTexture{ public: bool ifFirst; //FILE *fp; XShader sh; XTextureType type; std::mutex mux; virtual void Drop(){ if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Drop methods."); } mux.lock(); XEGL::Get()->Close(); sh.Close(); mux.unlock(); delete this; } virtual bool Init(void *win , XTextureType type){ if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Init methods. Type is %d" ,type); } mux.lock(); XEGL::Get()->Close(); sh.Close(); this->type = type; if (!win) { mux.unlock(); XLOGE("XTexture Init Failed win is null."); return false; } if (!XEGL::Get()->Init(win)) { mux.unlock(); XLOGE("XTexture Init Failed win init Fail."); return false; } sh.Init((XShaderType)type); mux.unlock(); if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Init success."); } return true; } virtual void Draw(unsigned char *data[] , int width , int height){ if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Draw methods. Data width is %d ,height is %d ,type is %d",width ,height ,type); } mux.lock(); sh.GetTexture(0 ,width ,height ,data[0]); // Y if (type == XTEXTURETYPE_YUV420P) { sh.GetTexture(1,width/2,height/2,data[1]); // U sh.GetTexture(2,width/2,height/2,data[2]); // V } else { sh.GetTexture(1 , width/2 , height/2 , data[1] , true); //UV } /*if (!ifFirst) { fp = fopen("/storage/emulated/0/1080test.yuv","wb+"); ifFirst = true; } fwrite(data[0],1,width * height,fp); fwrite(data[1],1,width * height / 4,fp); fwrite(data[2],1,width * height / 4,fp); fflush(fp); */ sh.Draw(); XEGL::Get()->Draw(); mux.unlock(); if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Draw success."); } } }; XTexture *XTexture::Create () { XLOGD("CXTexture Create."); return new CXTexture(); }
26.829545
108
0.505718
sk95120
b6551c3c68b0bc35a21af4fd16c77fa72cfc1c35
1,413
hpp
C++
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
22
2018-08-27T15:28:10.000Z
2022-02-13T08:18:00.000Z
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
3
2018-08-27T01:44:51.000Z
2020-06-28T20:07:42.000Z
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
2
2018-08-26T18:55:47.000Z
2018-09-29T01:04:36.000Z
#ifndef SNABL_BSET_HPP #define SNABL_BSET_HPP #include "snabl/cmp.hpp" #include "snabl/std.hpp" #include "snabl/types.hpp" namespace snabl { template <typename KeyT, typename ValT> struct BSet { using Vals = vector<ValT>; Vals vals; KeyT ValT::*key_ptr; BSet(KeyT ValT::*key_ptr): key_ptr(key_ptr) { } BSet(KeyT ValT::*key_ptr, const Vals &source): vals(source), key_ptr(key_ptr) { } I64 find(const KeyT &key, I64 min, ValT **found=nullptr) const { I64 max = vals.size(); while (min < max) { const I64 i = (max+min) / 2; const ValT &v(vals[i]); const KeyT &k = v.*key_ptr; switch (cmp(key, k)) { case Cmp::LT: max = i; break; case Cmp::EQ: if (found) { *found = const_cast<ValT *>(&v); } return i; case Cmp::GT: min = i+1; break; } } return min; } ValT *find(const KeyT &key) const { ValT *found(nullptr); find(key, 0, &found); return found; } template <typename...ArgsT> ValT *emplace(const KeyT &key, ArgsT &&...args) { ValT *found(nullptr); const I64 i(find(key, 0, &found)); if (found) { return nullptr; } return &*vals.emplace(vals.begin()+i, forward<ArgsT>(args)...); } void clear() { vals.clear(); } }; } #endif
22.428571
69
0.530078
codr4life
b65aed50316ad423ff5b0889dbc0247d96bbee14
865
cpp
C++
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
28
2019-09-09T08:13:25.000Z
2022-02-09T06:20:31.000Z
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
2
2020-05-26T02:06:42.000Z
2021-04-08T08:16:03.000Z
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
1
2020-06-09T23:40:04.000Z
2020-06-09T23:40:04.000Z
// // Created by Pedro Tacla Yamada on 14/7/20. // #include "DefaultStatsProvider.h" namespace filesaver::server { static const double MILLISECONDS_IN_SECOND = 1000.; DefaultStatsProvider::DefaultStatsProvider (services::stats::ThroughputTracker* throughputTracker, services::FileSizeService* fileSizeService) : m_throughputTracker (throughputTracker), m_fileSizeService (fileSizeService) { } Stats DefaultStatsProvider::getStats () { auto totalFiles = m_fileSizeService->getTotalFiles (); auto millisecondsElapsed = m_throughputTracker->getElapsedMilliseconds (); double filesPerSecond = MILLISECONDS_IN_SECOND * (static_cast<double> (totalFiles) / static_cast<double> (millisecondsElapsed)); return {filesPerSecond, millisecondsElapsed, totalFiles}; } } // namespace filesaver::server
30.892857
112
0.738728
yamadapc
b65b8a8657c4a8f38124f9ad71297f1732e7f9ad
396
cpp
C++
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
148
2018-10-11T16:51:37.000Z
2022-03-26T13:55:08.000Z
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
30
2019-11-30T11:43:07.000Z
2022-01-25T21:09:47.000Z
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
8
2020-04-17T13:18:30.000Z
2021-11-20T06:24:44.000Z
/* See LICENSE file in root folder */ #include "ShaderAST/Expr/ExprModulo.hpp" #include "ShaderAST/Expr/ExprVisitor.hpp" namespace ast::expr { Modulo::Modulo( type::TypePtr type , ExprPtr lhs , ExprPtr rhs ) : Binary{ std::move( type ) , std::move( lhs ) , std::move( rhs ) , Kind::eModulo } { } void Modulo::accept( VisitorPtr vis ) { vis->visitModuloExpr( this ); } }
15.84
41
0.643939
Praetonus
b65c5929e2e4a41de1bc85f2e30e137110bcc2d8
1,487
cpp
C++
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
2
2016-06-16T14:00:40.000Z
2020-04-26T12:11:34.000Z
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
null
null
null
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
null
null
null
#include "stdafx.h" App app; App::App() { } void App::Draw() { const IVec2 scrSize = systemMisc.GetScreenSize(); constexpr float f = 1000; constexpr float n = 1; const float aspect = (float)scrSize.x / scrSize.y; Mat proj = perspectiveLH(45.0f * (float)M_PI / 180.0f, aspect, n, f); matrixMan.Set(MatrixMan::PROJ, proj); rt.BeginRenderToThis(); triangle.Draw(); skyMan.Draw(); rsPostProcess.Apply(); deviceMan.SetRenderTarget(); afBindTextureToBindingPoint(rt.GetTexture(), 0); afDraw(PT_TRIANGLESTRIP, 4); fontMan.Render(); } void App::Init() { GoMyDir(); triangle.Create(); // skyMan.Create("yangjae_row.dds", "sky_photosphere"); skyMan.Create("yangjae.dds", "sky_photosphere"); // skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\Lobby\\LobbyCube.dds", "sky_cubemap"); fontMan.Init(); const IVec2 scrSize = systemMisc.GetScreenSize(); rt.Init(scrSize, AFF_R8G8B8A8_UNORM, AFF_D32_FLOAT_S8_UINT); SamplerType sampler = AFST_POINT_CLAMP; rsPostProcess.Create("vivid", 0, nullptr, BM_NONE, DSM_DISABLE, CM_DISABLE, 1, &sampler); } void App::Destroy() { deviceMan.Flush(); triangle.Destroy(); skyMan.Destroy(); fontMan.Destroy(); rsPostProcess.Destroy(); rt.Destroy(); } void App::Update() { matrixMan.Set(MatrixMan::VIEW, devCamera.CalcViewMatrix()); fps.Update(); fontMan.DrawString(Vec2(20, 40), 20, SPrintf("FPS: %f", fps.Get())); }
23.234375
135
0.677875
yorung
b65ddc6dec39b505392574d96c345095e856a9ef
6,408
cpp
C++
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "physics/operators/nonlinear_solid_operators.hpp" #include "infrastructure/logger.hpp" #include "numerics/expr_template_ops.hpp" namespace serac { NonlinearSolidQuasiStaticOperator::NonlinearSolidQuasiStaticOperator(std::unique_ptr<mfem::ParNonlinearForm> H_form, const BoundaryConditionManager& bcs) : mfem::Operator(H_form->FESpace()->GetTrueVSize()), H_form_(std::move(H_form)), bcs_(bcs) { } // compute: y = H(x,p) void NonlinearSolidQuasiStaticOperator::Mult(const mfem::Vector& k, mfem::Vector& y) const { // Apply the nonlinear form H_form_->Mult(k, y); H_form_->Mult(k, y); y.SetSubVector(bcs_.allEssentialDofs(), 0.0); } // Compute the Jacobian from the nonlinear form mfem::Operator& NonlinearSolidQuasiStaticOperator::GetGradient(const mfem::Vector& x) const { auto& grad = dynamic_cast<mfem::HypreParMatrix&>(H_form_->GetGradient(x)); bcs_.eliminateAllEssentialDofsFromMatrix(grad); return grad; } // destructor NonlinearSolidQuasiStaticOperator::~NonlinearSolidQuasiStaticOperator() {} NonlinearSolidDynamicOperator::NonlinearSolidDynamicOperator(std::unique_ptr<mfem::ParNonlinearForm> H_form, std::unique_ptr<mfem::ParBilinearForm> S_form, std::unique_ptr<mfem::ParBilinearForm> M_form, const BoundaryConditionManager& bcs, EquationSolver& newton_solver, const serac::LinearSolverParameters& lin_params) : mfem::TimeDependentOperator(M_form->ParFESpace()->TrueVSize() * 2), M_form_(std::move(M_form)), S_form_(std::move(S_form)), H_form_(std::move(H_form)), newton_solver_(newton_solver), bcs_(bcs), lin_params_(lin_params), z_(height / 2) { // Assemble the mass matrix and eliminate the fixed DOFs M_mat_.reset(M_form_->ParallelAssemble()); bcs_.eliminateAllEssentialDofsFromMatrix(*M_mat_); M_inv_ = EquationSolver(H_form_->ParFESpace()->GetComm(), lin_params); auto M_prec = std::make_unique<mfem::HypreSmoother>(); M_inv_.linearSolver().iterative_mode = false; M_prec->SetType(mfem::HypreSmoother::Jacobi); M_inv_.SetPreconditioner(std::move(M_prec)); M_inv_.SetOperator(*M_mat_); // Construct the reduced system operator and initialize the newton solver with // it reduced_oper_ = std::make_unique<NonlinearSolidReducedSystemOperator>(*H_form_, *S_form_, *M_form_, bcs); newton_solver_.SetOperator(*reduced_oper_); } void NonlinearSolidDynamicOperator::Mult(const mfem::Vector& vx, mfem::Vector& dvx_dt) const { // Create views to the sub-vectors v, x of vx, and dv_dt, dx_dt of dvx_dt int sc = height / 2; mfem::Vector v(vx.GetData() + 0, sc); mfem::Vector x(vx.GetData() + sc, sc); mfem::Vector dv_dt(dvx_dt.GetData() + 0, sc); mfem::Vector dx_dt(dvx_dt.GetData() + sc, sc); z_ = *H_form_ * x; S_form_->TrueAddMult(v, z_); z_.SetSubVector(bcs_.allEssentialDofs(), 0.0); dv_dt = M_inv_ * -z_; dx_dt = v; } void NonlinearSolidDynamicOperator::ImplicitSolve(const double dt, const mfem::Vector& vx, mfem::Vector& dvx_dt) { int sc = height / 2; mfem::Vector v(vx.GetData() + 0, sc); mfem::Vector x(vx.GetData() + sc, sc); mfem::Vector dv_dt(dvx_dt.GetData() + 0, sc); mfem::Vector dx_dt(dvx_dt.GetData() + sc, sc); // By eliminating kx from the coupled system: // kv = -M^{-1}*[H(x + dt*kx) + S*(v + dt*kv)] // kx = v + dt*kv // we reduce it to a nonlinear equation for kv, represented by the // m_reduced_oper. This equation is solved with the m_newton_solver // object (using m_J_solver and m_J_prec internally). reduced_oper_->SetParameters(dt, &v, &x); mfem::Vector zero; // empty vector is interpreted as zero r.h.s. by NewtonSolver dv_dt = newton_solver_ * zero; SLIC_WARNING_IF(!newton_solver_.nonlinearSolver().GetConverged(), "Newton solver did not converge."); dx_dt = v + (dt * dv_dt); } // destructor NonlinearSolidDynamicOperator::~NonlinearSolidDynamicOperator() {} NonlinearSolidReducedSystemOperator::NonlinearSolidReducedSystemOperator(const mfem::ParNonlinearForm& H_form, const mfem::ParBilinearForm& S_form, mfem::ParBilinearForm& M_form, const BoundaryConditionManager& bcs) : mfem::Operator(M_form.ParFESpace()->TrueVSize()), M_form_(M_form), S_form_(S_form), H_form_(H_form), dt_(0.0), v_(nullptr), x_(nullptr), w_(height), z_(height), bcs_(bcs) { } void NonlinearSolidReducedSystemOperator::SetParameters(double dt, const mfem::Vector* v, const mfem::Vector* x) { dt_ = dt; v_ = v; x_ = x; } void NonlinearSolidReducedSystemOperator::Mult(const mfem::Vector& k, mfem::Vector& y) const { // compute: y = H(x + dt*(v + dt*k)) + M*k + S*(v + dt*k) w_ = *v_ + (dt_ * k); z_ = *x_ + (dt_ * w_); y = H_form_ * z_; M_form_.TrueAddMult(k, y); S_form_.TrueAddMult(w_, y); y.SetSubVector(bcs_.allEssentialDofs(), 0.0); } mfem::Operator& NonlinearSolidReducedSystemOperator::GetGradient(const mfem::Vector& k) const { // Form the gradient of the complete nonlinear operator auto localJ = std::unique_ptr<mfem::SparseMatrix>(Add(1.0, M_form_.SpMat(), dt_, S_form_.SpMat())); w_ = *v_ + (dt_ * k); z_ = *x_ + (dt_ * w_); // No boundary conditions imposed here localJ->Add(dt_ * dt_, H_form_.GetLocalGradient(z_)); jacobian_.reset(M_form_.ParallelAssemble(localJ.get())); // Eliminate the fixed boundary DOFs bcs_.eliminateAllEssentialDofsFromMatrix(*jacobian_); return *jacobian_; } NonlinearSolidReducedSystemOperator::~NonlinearSolidReducedSystemOperator() {} } // namespace serac
38.142857
116
0.637953
joshessman-llnl
b662f049c445959516d9d4dbcce5744975b15c84
2,387
cpp
C++
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
2
2022-02-11T11:59:44.000Z
2022-02-16T20:33:25.000Z
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
#include "all.h" #include "ectrl_i.h" void DrawLineColumn(int x, int y); //---------------------------- C_window::C_window(): scroll_x(0), scroll_y(0), overwrite(false), hwnd(NULL), redraw(true) { undo[0].Add(C_undo_element::MARK); } //---------------------------- void C_window::Activate(){ SetFocus(hwnd); } //---------------------------- bool C_window::Save(){ if(doc.unnamed){ //prompt for name char buf[257]; strcpy(buf, doc.title); OPENFILENAME of; memset(&of, 0, sizeof(of)); of.lStructSize = sizeof(of); //of.hwndOwner = hwnd_main; of.hInstance = ec->hi; of.lpstrFile = buf; of.nMaxFile = sizeof(buf)-1; of.lpstrFileTitle = buf; of.nMaxFileTitle = sizeof(buf)-1; of.lpstrInitialDir = NULL; of.Flags = OFN_OVERWRITEPROMPT; if(!GetSaveFileName(&of)) return false; doc.SetTitle(buf); doc.modified = true; doc.unnamed = false; } if(!doc.Write()) return false; //parse undo buffer and change all FILEMODIFY elements to NOP { for(int i=UNDO_BUFFER_ELEMENTS; i--; ){ if(undo[0].elements[i] && undo[0].elements[i]->id==C_undo_element::FILEMODIFY){ undo[0].elements[i]->id = C_undo_element::NOP; } } } SetWindowText(ec->hwnd, doc.title); return true; } //---------------------------- bool C_window::SetScrollPos(int x, int y, int undo_buff){ if(scroll_x!=x || scroll_y!=y){ //add position into undo buffer undo[undo_buff].Add(C_undo_element::SCROLL, scroll_x, scroll_y); scroll_x = x; scroll_y = y; doc.redraw = true; cursor.redraw = true; //setup scroll-bar SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_RANGE | SIF_POS; si.nMin = 0; si.nMax = doc.linenum; si.nPos = scroll_y; SetScrollInfo(hwnd, SB_VERT, &si, true); return true; } return false; } //---------------------------- /* C_str C_window::ExtractFilename() const{ dword i = doc.title.Size(); while(i && doc.title[i-1]!='\\') --i; if(ec->read_only) return C_fstr("%s [read-only]", (const char*)doc.title + i); return &doc.title[i]; } */ //----------------------------
22.308411
91
0.51571
mice777