Search Results

Search found 1486 results on 60 pages for 'unsigned'.

Page 16/60 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Derived template override return type of member function C++

    - by Ruud v A
    I am writing matrix classes. Take a look at this definition: template <typename T, unsigned int dimension_x, unsigned int dimension_y> class generic_matrix { ... generic_matrix<T, dimension_x - 1, dimension_y - 1> minor(unsigned int x, unsigned int y) const { ... } ... } template <typename T, unsigned int dimension> class generic_square_matrix : public generic_matrix<T, dimension, dimension> { ... generic_square_matrix(const generic_matrix<T, dimension, dimension>& other) { ... } ... void foo(); } The generic_square_matrix class provides additional functions like matrix multiplication. Doing this is no problem: generic_square_matrix<T, 4> m = generic_matrix<T, 4, 4>(); It is possible to assign any square matrix to M, even though the type is not generic_square_matrix, due to the constructor. This is possible because the data does not change across children, only the supported functions. This is also possible: generic_square_matrix<T, 4> m = generic_square_matrix<T, 5>().minor(1,1); Same conversion applies here. But now comes the problem: generic_square_matrix<T, 4>().minor(1,1).foo(); //problem, foo is not in generic_matrix<T, 3, 3> To solve this I would like generic_square_matrix::minor to return a generic_square_matrix instead of a generic_matrix. The only possible way to do this, I think is to use template specialisation. But since a specialisation is basically treated like a separate class, I have to redefine all functions. I cannot call the function of the non-specialised class as you would do with a derived class, so I have to copy the entire function. This is not a very nice generic-programming solution, and a lot of work. C++ almost has a solution for my problem: a virtual function of a derived class, can return a pointer or reference to a different class than the base class returns, if this class is derived from the class that the base class returns. generic_square_matrix is derived from generic_matrix, but the function does not return a pointer nor reference, so this doesn't apply here. Is there a solution to this problem (possibly involving an entirely other structure; my only requirements are that the dimensions are a template parameter and that square matrices can have additional functionality). Thanks in advance, Ruud

    Read the article

  • PHP & MySQL Undefined variable problem

    - by comma
    I keep getting the following error Undefined variable: id on line 91 can some one help me correct this problem? The error is on this line. $query2 = "INSERT INTO users_skills (skill_id, user_id, date_created) VALUES ('$id', '$user_id', NOW())"; MySQL database tables. CREATE TABLE tags ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, skill VARCHAR(255) NOT NULL, experience VARCHAR(255) NOT NULL, years VARCHAR(255) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE users_skills ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, skill_id INT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL, date_created DATETIME UNSIGNED NOT NULL, PRIMARY KEY (id) ); Here is the PHP & MySQL code. if (isset($_POST['info_submitted'])) { $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"SELECT learned_skills.*, users_skills.* FROM learned_skills INNER JOIN users_skills ON learned_skills.id = users_skills.skill_id WHERE user_id='$user_id'"); if (!$dbc) { print mysqli_error($mysqli); return; } $user_id = '5'; $skill = $_POST['skill']; $experience = $_POST['experience']; $years = $_POST['years']; $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"SELECT learned_skills.*, users_skills.* FROM learned_skills INNER JOIN users_skills ON users_skills.skill_id = learned_skills.id WHERE users_skills.user_id='$user_id'"); if (mysqli_num_rows($dbc) == 0) { if (isset($_POST['skill']) && trim($_POST['skill'])!=='') { $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $query1 = mysqli_query($mysqli,"INSERT INTO learned_skills (skill, experience, years) VALUES ('" . $skill . "', '" . $experience . "', '" . $years . "')"); if (mysqli_query($mysqli, $query1)) { print mysqli_error($mysqli); return; } $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"SELECT id FROM learned_skills WHERE id='" . $skill . "' AND experience='" . $experience . "' AND years='" . $years . "'"); if (!$dbc) { print mysqli_error($mysqli); } else { while($row = mysqli_fetch_array($dbc)){ $id = $row["id"]; } } $query2 = "INSERT INTO users_skills (skill_id, user_id, date_created) VALUES ('$id', '$user_id', NOW())"; } }

    Read the article

  • stxxl Assertion `it != root_node_.end()' failed

    - by Fabrizio Silvestri
    I am receiving this assertion failed error when trying to insert an element in a stxxl map. The entire assertion error is the following: resCache: /usr/include/stxxl/bits/containers/btree/btree.h:470: std::pair , bool stxxl::btree::btree::insert(const value_type&) [with KeyType = e_my_key, DataType = unsigned int, CompareType = comp_type, unsigned int RawNodeSize = 16384u, unsigned int RawLeafSize = 131072u, PDAllocStrategy = stxxl::SR, stxxl::btree::btree::value_type = std::pair]: Assertion `it != root_node_.end()' failed. Aborted Any idea? Edit: Here's the code fragment void request_handler::handle_request(my_key& query, reply& rep) { c_++; strip(query.content); std::cout << "Received query " << query.content << " by thread " << boost::this_thread::get_id() << ". It is number " << c_ << "\n"; strcpy(element.first.content, query.content); element.second = c_; testcache_.insert(element); STXXL_MSG("Records in map: " << testcache_.size()); } Edit2 here's more details (I omit constants, e.g. MAX_QUERY_LEN) struct comp_type : std::binary_function<my_key, my_key, bool> { bool operator () (const my_key & a, const my_key & b) const { return strncmp(a.content, b.content, MAX_QUERY_LEN) < 0; } static my_key max_value() { return max_key; } static my_key min_value() { return min_key; } }; typedef stxxl::map<my_key, my_data, comp_type> cacheType; cacheType testcache_; request_handler::request_handler() :testcache_(NODE_CACHE_SIZE, LEAF_CACHE_SIZE) { c_ = 0; memset(max_key.content, (std::numeric_limits<unsigned char>::max)(), MAX_QUERY_LEN); memset(min_key.content, (std::numeric_limits<unsigned char>::min)(), MAX_QUERY_LEN); testcache_.enable_prefetching(); STXXL_MSG("Records in map: " << testcache_.size()); }

    Read the article

  • Count seconds and minutes with MCU timer/interrupt?

    - by arynhard
    I am trying to figure out how to create a timer for my C8051F020 MCU. The following code uses the value passed to init_Timer2() with the following formula: 65535-(0.1 / (12/2000000)=48868. I set up the timer to count every time it executes and for every 10 counts, count one second. This is based on the above formula. 48868 when passed to init_Timer2 will produce a 0.1 second delay. It would take ten of them per second. However, when I test the timer it is a little fast. At ten seconds the timer reports 11 seconds, at 20 seconds the timer reports 22 seconds. I would like to get as close to a perfect second as I can. Here is my code: #include <compiler_defs.h> #include <C8051F020_defs.h> void init_Clock(void); void init_Watchdog(void); void init_Ports(void); void init_Timer2(unsigned int counts); void start_Timer2(void); void timer2_ISR(void); unsigned int timer2_Count; unsigned int seconds; unsigned int minutes; int main(void) { init_Clock(); init_Watchdog(); init_Ports(); start_Timer2(); P5 &= 0xFF; while (1); } //============================================================= //Functions //============================================================= void init_Clock(void) { OSCICN = 0x04; //2Mhz //OSCICN = 0x07; //16Mhz } void init_Watchdog(void) { //Disable watchdog timer WDTCN = 0xDE; WDTCN = 0xAD; } void init_Ports(void) { XBR0 = 0x00; XBR1 = 0x00; XBR2 = 0x40; P0 = 0x00; P0MDOUT = 0x00; P5 = 0x00; //Set P5 to 1111 P74OUT = 0x08; //Set P5 4 - 7 (LEDs) to push pull (Output) } void init_Timer2(unsigned int counts) { CKCON = 0x00; //Set all timers to system clock divided by 12 T2CON = 0x00; //Set timer 2 to timer mode RCAP2 = counts; T2 = 0xFFFF; //655535 IE |= 0x20; //Enable timer 2 T2CON |= 0x04; //Start timer 2 } void start_Timer2(void) { EA = 0; init_Timer2(48868); EA = 1; } void timer2_ISR(void) interrupt 5 { T2CON &= ~(0x80); P5 ^= 0xF0; timer2_Count++; if(timer2_Count % 10 == 0) { seconds++; } if(seconds % 60 == 0 && seconds != 0) { minutes++; } }

    Read the article

  • Need MYSQL query for finding lowest score per game player

    - by Chris Barnhill
    I have a game on Facebook called Rails Across Europe. I have a Best Scores page where I show the players with the best 20 scores, which in game terms refers to the lowest winning turn. The problem is that there are a small number of players who play frequently, and their scores dominate the page. I'd like to make the scores page open to more players. So I thought that I could display the single lowest winning turn for each player instead of displaying all of the lowest winning turns for all players. The problem is that the query for this eludes me. So I hope that one of you brilliant StackOverflow folks can help me with this. I have included the relevant MYSQL table schemas below. Here are the the table relationships: player_stats contains statistics for either a game in progress or a completed game. If a game is in progress, winning_turn is zero (which means that games with a winning_turn of zero should not be included in the query). player_stats has a game_player table id reference. game_player contains data describing games currently in progress. game_player has a player table id reference. player contains data describing a person who plays the game. Here's the query I'm currently using: 'SELECT p.fb_user_id, ps.winning_turn, gp.difficulty_level, c.name as city_name, g.name as goods_name, d.cost FROM game_player as gp, player as p, player_stats as ps, demand as d, city as c, goods as g WHERE p.status = "ACTIVE" AND gp.player_id = p.id AND ps.game_player_id = gp.id AND d.id = ps.highest_demand_id AND c.id = d.city_id AND g.id = d.goods_id AND ps.winning_turn > 0 ORDER BY ps.winning_turn ASC, d.cost DESC LIMIT '.$limit.';'; Here are the relevant table schemas: -- -- Table structure for table `player_stats` -- CREATE TABLE IF NOT EXISTS `player_stats` ( `id` int(11) NOT NULL auto_increment, `game_player_id` int(11) NOT NULL, `winning_turn` int(11) NOT NULL, `highest_demand_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `game_player_id` (`game_player_id`,`highest_demand_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3814 ; -- -- Table structure for table `game_player` -- CREATE TABLE IF NOT EXISTS `game_player` ( `id` int(10) unsigned NOT NULL auto_increment, `game_id` int(10) unsigned NOT NULL, `player_id` int(10) unsigned NOT NULL, `player_number` int(11) NOT NULL, `funds` int(10) unsigned NOT NULL, `turn` int(10) unsigned NOT NULL, `difficulty_level` enum('STANDARD','ADVANCED','MASTER','ULTIMATE') NOT NULL, `date_last_used` datetime NOT NULL, PRIMARY KEY (`id`), KEY `game_id` (`game_id`,`player_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3814 ; -- -- Table structure for table `player` -- CREATE TABLE IF NOT EXISTS `player` ( `id` int(11) NOT NULL auto_increment, `fb_user_id` char(255) NOT NULL, `fb_proxied_email` text NOT NULL, `first_name` char(255) NOT NULL, `last_name` char(255) NOT NULL, `birthdate` date NOT NULL, `date_registered` datetime NOT NULL, `date_last_logged_in` datetime NOT NULL, `status` enum('ACTIVE','SUSPENDED','CLOSED') NOT NULL, PRIMARY KEY (`id`), KEY `fb_user_id` (`fb_user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1646 ;

    Read the article

  • Updated Security Baseline (7u45) impacts Java 7u40 and before with High Security settings

    - by costlow
    The Java Security Baseline has been increased from 7u25 to 7u45.  For versions of Java below 7u45, this means unsigned Java applets or Java applets that depend on Javascript LiveConnect calls will be blocked when using the High Security setting in the Java Control Panel. This issue only affects Applets and Web Start applications. It does not affect other types of Java applications. The Short Answer Users upgrading to Java 7 update 45 will automatically fix this and is strongly recommended. The More Detailed Answer There are two items involved as described on the deployment flowchart: The Security Baseline – a dynamically updated attribute that checks to see which Java version contains the most recent security patches. The Security Slider – the user-controlled setting of when to prompt/run/block applets. The Security Baseline Java clients periodically check in to understand what version contains the most recent security patches. Versions are released in-between that contain bug fixes. For example: 7u25 (July 2013) was the previous secure baseline. 7u40 contained bug fixes. Because this did not contain security patches, users were not required to upgrade and were welcome to remain on 7u25. When 7u45 was released (October, 2013), this critical patch update contained security patches and raised the secure baseline. Users are required to upgrade from earlier versions. For users that are not regularly connected to the internet, there is a built in Expiration Date. Because of the pre-established quarterly critical patch updates, we are able to determine an approximate date of the next version. A critical patch released in July will have its successor released, at latest, in July + 3 months: October. The Security Slider The security slider is located within the Java control panel and determines which Applets & Web Start applications will prompt, which will run, and which will be blocked. One of the questions used to determine prompt/run/block is, “At or Above the Security Baseline.” The Combination JavaScript calls made from LiveConnect do not reside within signed JAR files, so they are considered to be unsigned code. This is correct within networked systems even if the domain uses HTTPS because signed JAR files represent signed "data at rest" whereas TLS (often called SSL) literally stands for "Transport Level Security" and secures the communication channel, not the contents/code within the channel. The resulting flow of users who click "update later" is: Is the browser plug-in registered and allowed to run? Yes. Does a rule exist for this RIA? No rules apply. Does the RIA have a valid signature? Yes and not revoked. Which security prompt is needed? JRE is below the baseline. This is because 7u45 is the baseline and the user, clicked "upgrade later." Under the default High setting, Unsigned code is set to "Don’t Run" so users see: Additional Notes End Users can control their own security slider within the control panel. System Administrators can customize the security slider during automated installations. As a reminder, in the future, Java 7u51 (January 2014) will block unsigned and self-signed Applets & Web Start applications by default.

    Read the article

  • OpenGL 3.x Assimp trouble implementing phong shading (normals?)

    - by Defcronyke
    I'm having trouble getting phong shading to look right. I'm pretty sure there's something wrong with either my OpenGL calls, or the way I'm loading my normals, but I guess it could be something else since 3D graphics and Assimp are both still very new to me. When trying to load .obj/.mtl files, the problems I'm seeing are: The models seem to be lit too intensely (less phong-style and more completely washed out, too bright). Faces that are lit seem to be lit equally all over (with the exception of a specular highlight showing only when the light source position is moved to be practically right on top of the model) Because of problems 1 and 2, spheres look very wrong: picture of sphere And things with larger faces look (less-noticeably) wrong too: picture of cube I could be wrong, but to me this doesn't look like proper phong shading. Here's the code that I think might be relevant (I can post more if necessary): file: assimpRenderer.cpp #include "assimpRenderer.hpp" namespace def { assimpRenderer::assimpRenderer(std::string modelFilename, float modelScale) { initSFML(); initOpenGL(); if (assImport(modelFilename)) // if modelFile loaded successfully { initScene(); mainLoop(modelScale); shutdownScene(); } shutdownOpenGL(); shutdownSFML(); } assimpRenderer::~assimpRenderer() { } void assimpRenderer::initSFML() { windowWidth = 800; windowHeight = 600; settings.majorVersion = 3; settings.minorVersion = 3; app = NULL; shader = NULL; app = new sf::Window(sf::VideoMode(windowWidth,windowHeight,32), "OpenGL 3.x Window", sf::Style::Default, settings); app->setFramerateLimit(240); app->setActive(); return; } void assimpRenderer::shutdownSFML() { delete app; return; } void assimpRenderer::initOpenGL() { GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ std::cerr << "Error: " << glewGetErrorString(err) << std::endl; } // check the OpenGL context version that's currently in use int glVersion[2] = {-1, -1}; glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // get the OpenGL Major version glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // get the OpenGL Minor version std::cout << "Using OpenGL Version: " << glVersion[0] << "." << glVersion[1] << std::endl; return; } void assimpRenderer::shutdownOpenGL() { return; } void assimpRenderer::initScene() { // allocate heap space for VAOs, VBOs, and IBOs vaoID = new GLuint[scene->mNumMeshes]; vboID = new GLuint[scene->mNumMeshes*2]; iboID = new GLuint[scene->mNumMeshes]; glClearColor(0.4f, 0.6f, 0.9f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); shader = new Shader("shader.vert", "shader.frag"); projectionMatrix = glm::perspective(60.0f, (float)windowWidth / (float)windowHeight, 0.1f, 100.0f); rot = 0.0f; rotSpeed = 50.0f; faceIndex = 0; colorArrayA = NULL; colorArrayD = NULL; colorArrayS = NULL; normalArray = NULL; genVAOs(); return; } void assimpRenderer::shutdownScene() { delete [] iboID; delete [] vboID; delete [] vaoID; delete shader; } void assimpRenderer::renderScene(float modelScale) { sf::Time elapsedTime = clock.getElapsedTime(); clock.restart(); if (rot > 360.0f) rot = 0.0f; rot += rotSpeed * elapsedTime.asSeconds(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); viewMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, -3.0f, -10.0f)); // move back a bit modelMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(modelScale)); // scale model modelMatrix = glm::rotate(modelMatrix, rot, glm::vec3(0, 1, 0)); //modelMatrix = glm::rotate(modelMatrix, 25.0f, glm::vec3(0, 1, 0)); glm::vec3 lightPosition( 0.0f, -100.0f, 0.0f ); float lightPositionArray[3]; lightPositionArray[0] = lightPosition[0]; lightPositionArray[1] = lightPosition[1]; lightPositionArray[2] = lightPosition[2]; shader->bind(); int projectionMatrixLocation = glGetUniformLocation(shader->id(), "projectionMatrix"); int viewMatrixLocation = glGetUniformLocation(shader->id(), "viewMatrix"); int modelMatrixLocation = glGetUniformLocation(shader->id(), "modelMatrix"); int ambientLocation = glGetUniformLocation(shader->id(), "ambientColor"); int diffuseLocation = glGetUniformLocation(shader->id(), "diffuseColor"); int specularLocation = glGetUniformLocation(shader->id(), "specularColor"); int lightPositionLocation = glGetUniformLocation(shader->id(), "lightPosition"); int normalMatrixLocation = glGetUniformLocation(shader->id(), "normalMatrix"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]); glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, &modelMatrix[0][0]); glUniform3fv(lightPositionLocation, 1, lightPositionArray); for (unsigned int i = 0; i < scene->mNumMeshes; i++) { colorArrayA = new float[3]; colorArrayD = new float[3]; colorArrayS = new float[3]; material = scene->mMaterials[scene->mNumMaterials-1]; normalArray = new float[scene->mMeshes[i]->mNumVertices * 3]; unsigned int normalIndex = 0; for (unsigned int j = 0; j < scene->mMeshes[i]->mNumVertices * 3; j+=3, normalIndex++) { normalArray[j] = scene->mMeshes[i]->mNormals[normalIndex].x; // x normalArray[j+1] = scene->mMeshes[i]->mNormals[normalIndex].y; // y normalArray[j+2] = scene->mMeshes[i]->mNormals[normalIndex].z; // z } normalIndex = 0; glUniformMatrix3fv(normalMatrixLocation, 1, GL_FALSE, normalArray); aiColor3D ambient(0.0f, 0.0f, 0.0f); material->Get(AI_MATKEY_COLOR_AMBIENT, ambient); aiColor3D diffuse(0.0f, 0.0f, 0.0f); material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse); aiColor3D specular(0.0f, 0.0f, 0.0f); material->Get(AI_MATKEY_COLOR_SPECULAR, specular); colorArrayA[0] = ambient.r; colorArrayA[1] = ambient.g; colorArrayA[2] = ambient.b; colorArrayD[0] = diffuse.r; colorArrayD[1] = diffuse.g; colorArrayD[2] = diffuse.b; colorArrayS[0] = specular.r; colorArrayS[1] = specular.g; colorArrayS[2] = specular.b; // bind color for each mesh glUniform3fv(ambientLocation, 1, colorArrayA); glUniform3fv(diffuseLocation, 1, colorArrayD); glUniform3fv(specularLocation, 1, colorArrayS); // render all meshes glBindVertexArray(vaoID[i]); // bind our VAO glDrawElements(GL_TRIANGLES, scene->mMeshes[i]->mNumFaces*3, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // unbind our VAO delete [] normalArray; delete [] colorArrayA; delete [] colorArrayD; delete [] colorArrayS; } shader->unbind(); app->display(); return; } void assimpRenderer::handleEvents() { sf::Event event; while (app->pollEvent(event)) { if (event.type == sf::Event::Closed) { app->close(); } if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)) { app->close(); } if (event.type == sf::Event::Resized) { glViewport(0, 0, event.size.width, event.size.height); } } return; } void assimpRenderer::mainLoop(float modelScale) { while (app->isOpen()) { renderScene(modelScale); handleEvents(); } } bool assimpRenderer::assImport(const std::string& pFile) { // read the file with some example postprocessing scene = importer.ReadFile(pFile, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); // if the import failed, report it if (!scene) { std::cerr << "Error: " << importer.GetErrorString() << std::endl; return false; } return true; } void assimpRenderer::genVAOs() { int vboIndex = 0; for (unsigned int i = 0; i < scene->mNumMeshes; i++, vboIndex+=2) { mesh = scene->mMeshes[i]; indexArray = new unsigned int[mesh->mNumFaces * sizeof(unsigned int) * 3]; // convert assimp faces format to array faceIndex = 0; for (unsigned int t = 0; t < mesh->mNumFaces; ++t) { const struct aiFace* face = &mesh->mFaces[t]; std::memcpy(&indexArray[faceIndex], face->mIndices, sizeof(float) * 3); faceIndex += 3; } // generate VAO glGenVertexArrays(1, &vaoID[i]); glBindVertexArray(vaoID[i]); // generate IBO for faces glGenBuffers(1, &iboID[i]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboID[i]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * mesh->mNumFaces * 3, indexArray, GL_STATIC_DRAW); // generate VBO for vertices if (mesh->HasPositions()) { glGenBuffers(1, &vboID[vboIndex]); glBindBuffer(GL_ARRAY_BUFFER, vboID[vboIndex]); glBufferData(GL_ARRAY_BUFFER, mesh->mNumVertices * sizeof(GLfloat) * 3, mesh->mVertices, GL_STATIC_DRAW); glEnableVertexAttribArray((GLuint)0); glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0); } // generate VBO for normals if (mesh->HasNormals()) { normalArray = new float[scene->mMeshes[i]->mNumVertices * 3]; unsigned int normalIndex = 0; for (unsigned int j = 0; j < scene->mMeshes[i]->mNumVertices * 3; j+=3, normalIndex++) { normalArray[j] = scene->mMeshes[i]->mNormals[normalIndex].x; // x normalArray[j+1] = scene->mMeshes[i]->mNormals[normalIndex].y; // y normalArray[j+2] = scene->mMeshes[i]->mNormals[normalIndex].z; // z } normalIndex = 0; glGenBuffers(1, &vboID[vboIndex+1]); glBindBuffer(GL_ARRAY_BUFFER, vboID[vboIndex+1]); glBufferData(GL_ARRAY_BUFFER, mesh->mNumVertices * sizeof(GLfloat) * 3, normalArray, GL_STATIC_DRAW); glEnableVertexAttribArray((GLuint)1); glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0); delete [] normalArray; } // tex coord stuff goes here // unbind buffers glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); delete [] indexArray; } vboIndex = 0; return; } } file: shader.vert #version 150 core in vec3 in_Position; in vec3 in_Normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; uniform vec3 lightPosition; uniform mat3 normalMatrix; smooth out vec3 vVaryingNormal; smooth out vec3 vVaryingLightDir; void main() { // derive MVP and MV matrices mat4 modelViewProjectionMatrix = projectionMatrix * viewMatrix * modelMatrix; mat4 modelViewMatrix = viewMatrix * modelMatrix; // get surface normal in eye coordinates vVaryingNormal = normalMatrix * in_Normal; // get vertex position in eye coordinates vec4 vPosition4 = modelViewMatrix * vec4(in_Position, 1.0); vec3 vPosition3 = vPosition4.xyz / vPosition4.w; // get vector to light source vVaryingLightDir = normalize(lightPosition - vPosition3); // Set the position of the current vertex gl_Position = modelViewProjectionMatrix * vec4(in_Position, 1.0); } file: shader.frag #version 150 core out vec4 out_Color; uniform vec3 ambientColor; uniform vec3 diffuseColor; uniform vec3 specularColor; smooth in vec3 vVaryingNormal; smooth in vec3 vVaryingLightDir; void main() { // dot product gives us diffuse intensity float diff = max(0.0, dot(normalize(vVaryingNormal), normalize(vVaryingLightDir))); // multiply intensity by diffuse color, force alpha to 1.0 out_Color = vec4(diff * diffuseColor, 1.0); // add in ambient light out_Color += vec4(ambientColor, 1.0); // specular light vec3 vReflection = normalize(reflect(-normalize(vVaryingLightDir), normalize(vVaryingNormal))); float spec = max(0.0, dot(normalize(vVaryingNormal), vReflection)); if (diff != 0) { float fSpec = pow(spec, 128.0); // Set the output color of our current pixel out_Color.rgb += vec3(fSpec, fSpec, fSpec); } } I know it's a lot to look through, but I'm putting most of the code up so as not to assume where the problem is. Thanks in advance to anyone who has some time to help me pinpoint the problem(s)! I've been trying to sort it out for two days now and I'm not getting anywhere on my own.

    Read the article

  • How to override ATTR_DEFAULT_IDENTIFIER_OPTIONS in Models in Doctrine?

    - by user309083
    Here someone explained that setting a 'primary' attribute for any row in your Model will override Doctrine_Manager's ATTR_DEFAULT_IDENTIFIER_OPTIONS attribute: http://stackoverflow.com/questions/2040675/how-do-you-override-a-constant-in-doctrines-models This works, however if you have a many to many relation whereby the intermediate table is created, even if you have set both columns in the intermediate to primary an error still results when Doctrine tries to place an index on the nonexistant 'id' column upon table creation. Here's my code: //Bootstrap // set the default primary key to be named 'id', integer, 4 bytes Doctrine_Manager::getInstance()->setAttribute( Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS, array('name' => 'id', 'type' => 'integer', 'length' => 4)); //User Model class User extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('users'); } public function setUp() { $this->hasMany('Role as roles', array( 'local' => 'id', 'foreign' => 'user_id', 'refClass' => 'UserRole', 'onDelete' => 'CASCADE' )); } } //Role Model class Role extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('roles'); } public function setUp() { $this->hasMany('User as users', array( 'local' => 'id', 'foreign' => 'role_id', 'refClass' => 'UserRole' )); } } //UserRole Model class UserRole extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('roles_users'); $this->hasColumn('user_id', 'integer', 4, array('primary'=>true)); $this->hasColumn('role_id', 'integer', 4, array('primary'=>true)); } } Resulting error: SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'id' doesn't exist in table. Failing Query: "CREATE TABLE roles_users (user_id INT UNSIGNED NOT NULL, role_id INT UNSIGNED NOT NULL, INDEX id_idx (id), PRIMARY KEY(user_id, role_id)) ENGINE = INNODB". Failing Query: CREATE TABLE roles_users (user_id INT UNSIGNED NOT NULL, role_id INT UNSIGNED NOT NULL, INDEX id_idx (id), PRIMARY KEY(user_id, role_id)) ENGINE = INNODB I'm creating my tables using Doctrine::createTablesFromModels();

    Read the article

  • C# wrapper and Callbacks

    - by fergs
    I'm in the process of writing a C# wrapper for Dallmeier Common API light (Camera & Surviellance systems) and I've never written a wrapper before, but I have used the Canon EDSDK C# wrapper. So I'm using the Canon wrapper as a guide to writing the Dallmeier wrapper. I'm currently having issues with wrapping a callback. In the API manual it has the following: dlm_connect int(unsigned long uLWindowHandle, const char * strIP, const char* strUser1, const char* strPwd1, const char* strUser2, const char* strPwd2, void (*callback)(void *pParameters, void *pResult, void *pInput), void * pInput) Arguments - ulWindowhandle - handle of the window that is passed to the ViewerSDK to display video and messages there - strUser1/2 - names of the users to log in. If only single user login is used strUser2 is - NULL - strPwd1/2 - passwords of both users. If strUser2 is NULL strPwd2 is ignored. Return This function creates a SessionHandle that has to be passed Callback pParameters will be structured: - unsigned long ulFunctionID - unsigned long ulSocketHandle, //handle to socket of the established connection - unsigned long ulWindowHandle, - int SessionHandle, //session handle of the session created - const char * strIP, - const char* strUser1, - const char* strPwd1, - const char* strUser2, - const char * strPWD2 pResult is a pointer to an integer, representing the result of the operation. Zero on success. Negative values are error codes. So from what I've read on the Net and Stack Overflow - C# uses delegates for the purpose of callbacks. So I create a my Callback function : public delegate uint DallmeierCallback(DallPparameters pParameters, IntPtr pResult, IntPtr pInput); I create the connection function [DllImport("davidapidis.dll")] public extern static int dlm_connect(ulong ulWindowHandle, string strIP, string strUser1, string strPwd1, string strUser2, string strPwd2, DallmeierCallback inDallmeierFunc And (I think) the DallPParameters as a struct : [StructLayout(LayoutKind.Sequential)] public struct DallPParameters { public ulong ulfunctionID; public ulong ulsocketHandle; public ulong ulWindowHandle; ... } All of this is in my wrapper class. Am I heading in the right direction or is this completely wrong?

    Read the article

  • is delete p where p is a pointer to array a memory leak ?

    - by Eli
    following a discussion in a software meeting I setup to find out if deleting an dynamically allocated primitive array with plain delete will cause a memory leak. I have written this tiny program and compiled with visual studio 2008 running on windows XP: #include "stdafx.h" #include "Windows.h" const unsigned long BLOCK_SIZE = 1024*100000; int _tmain() { for (unsigned int i =0; i < 1024*1000; i++) { int* p = new int[1024*100000]; for (int j =0;j<BLOCK_SIZE;j++) p[j]= j % 2; Sleep(1000); delete p; } } I than monitored the memory consumption of my application using task manager, surprisingly the memory was allocated and freed correctly, allocated memory did not steadily increase as was expected I've modified my test program to allocate a non primitive type array : #include "stdafx.h" #include "Windows.h" struct aStruct { aStruct() : i(1), j(0) {} int i; char j; } NonePrimitive; const unsigned long BLOCK_SIZE = 1024*100000; int _tmain() { for (unsigned int i =0; i < 1024*100000; i++) { aStruct* p = new aStruct[1024*100000]; Sleep(1000); delete p; } } after running for for 10 minutes there was no meaningful increase in memory I compiled the project with warning level 4 and got no warnings. is it possible that the visual studio run time keep track of the allocated objects types so there is no different between delete and delete[] in that environment ?

    Read the article

  • Bit shift and pointer oddities in C, looking for explanations

    - by foo
    Hi all, I discovered something odd that I can't explain. If someone here can see what or why this is happening I'd like to know. What I'm doing is taking an unsigned short containing 12 bits aligned high like this: 1111 1111 1111 0000 I then want to shif the bits so that each byte in the short hold 7bits with the MSB as a pad. The result on what's presented above should look like this: 0111 1111 0111 1100 What I have done is this: unsigned short buf = 0xfff; //align high buf <<= 4; buf >>= 1; *((char*)&buf) >>= 1; This gives me something like looks like it's correct but the result of the last shift leaves the bit set like this: 0111 1111 1111 1100 Very odd. If I use an unsigned char as a temporary storage and shift that then it works, like this: unsigned short buf = 0xfff; buf <<= 4; buf >>= 1; tmp = *((char*)&buf); *((char*)&buf) = tmp >> 1; The result of this is: 0111 1111 0111 1100 Any ideas what is going on here?

    Read the article

  • setcontext and makecontext to call a generic function pointer

    - by Simone Margaritelli
    In another question i had the problem to port the code unsigned long stack[] = { 1, 23, 33, 43 }; /* save all the registers and the stack pointer */ unsigned long esp; asm __volatile__ ( "pusha" ); asm __volatile__ ( "mov %%esp, %0" :"=m" (esp)); for( i = 0; i < sizeof(stack); i++ ){ unsigned long val = stack[i]; asm __volatile__ ( "push %0" :: "m"(val) ); } unsigned long ret = function_pointer(); /* restore registers and stack pointer */ asm __volatile__ ( "mov %0, %%esp" :: "m" (esp) ); asm __volatile__ ( "popa" ); To a 64bit platform and many guys told me i should use the setcontext and makecontext functions set instead due to the calling conversion differences between 32 and 64 bits and portability issues. Well, i really can't find any useful documentation online, or at least not the kind i need to implement this, so, how can i use those functions to push arguments onto the stack, call a generic function pointer, obtain the return value and then restore the registers?

    Read the article

  • Doctrine 1.2: How do i prevent a contraint from being assigned to both sides of a One-to-many relati

    - by prodigitalson
    Is there a way to prevent Doctrine from assigning a contraint on both sides of a one-to-one relationship? Ive tried moving the definition from one side to the other and using owning side but it still places a constraint on both tables. when I only want the parent table to have a constraint - ie. its possible for the parent to not have an associated child. For example iwant the following sql schema essentially: CREATE TABLE `parent_table` ( `child_id` varchar(50) NOT NULL, `id` integer UNSIGNED NOT NULL auto_increment, PRIMARY KEY (`id`) ); CREATE TABLE `child_table` ( `id` integer UNSIGNED NOT NULL auto_increment, `child_id` varchar(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY (`child_id`), CONSTRAINT `parent_table_child_id_FK_child_table_child_id` FOREIGN KEY (`child_id`) REFERENCES `parent_table` (`child_id`) ); However im getting something like this: CREATE TABLE `parent_table` ( `child_id` varchar(50) NOT NULL, `id` integer UNSIGNED NOT NULL auto_increment, PRIMARY KEY (`id`), CONSTRAINT `child_table_child_id_FK_parent_table_child_id` FOREIGN KEY (`child_id`) REFERENCES `child_table` (`child_id`) ); CREATE TABLE `child_table` ( `id` integer UNSIGNED NOT NULL auto_increment, `child_id` varchar(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY (`child_id`), CONSTRAINT `parent_table_child_id_FK_child_table_child_id` FOREIGN KEY (`child_id`) REFERENCES `parent_table` (`child_id`) ); I could just remove the constraint manually or modify my accessors to return/set a single entity in the collection (using a one-to-many) but it seems like there should built in way to handle this. Also im using Symfony 1.4.4 (pear installtion ATM) - in case its an sfDoctrinePlugin issue and not necessarily Doctrine itself.

    Read the article

  • Question regarding ip checksum code

    - by looktt
    unsigned short /* this function generates header checksums */ csum (unsigned short *buf, int nwords) { unsigned long sum; for (sum = 0; nwords > 0; nwords--) // add words(16bits) together sum += *buf++; sum = (sum >> 16) + (sum & 0xffff); //add carry over sum += (sum >> 16); //what does this step do??? add possible left-over //byte? But isn't it already added in the loop (if //any)? return ((unsigned short) ~sum); } I assume nwords in the number of 16bits word, not 8bits byte (if there are odd byte, nword is rounded to next large), is it correct? The line sum = (sum 16) + (sum & 0xffff) is to add carry over to make 16bit complement sum += (sum 16); What's the purpose of this step? Add left-over byte? How? Thanks!

    Read the article

  • What is different about C++ math.h abs() compared to my abs()

    - by moka
    I am currently writing some glsl like vector math classes in c++, and I just implemented an abs() function like this: template<class T> static inline T abs(T _a) { return _a < 0 ? -_a : _a; } I compared its speed to the default c++ abs from math.h like this: clock_t begin = clock(); for(int i=0; i<10000000; ++i) { float a = abs(-1.25); }; clock_t end = clock(); unsigned long time1 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0)); begin = clock(); for(int i=0; i<10000000; ++i) { float a = myMath::abs(-1.25); }; end = clock(); unsigned long time2 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0)); std::cout<<time1<<std::endl; std::cout<<time2<<std::endl; Now the default abs takes about 25ms while mine takes 60. I guess there is some low level optimisation going on. Does anybody know how math.h abs works internally? The performance difference is nothing dramatic, but I am just curious!

    Read the article

  • Bitwise operators and converting an int to 2 bytes and back again.

    - by aKiwi
    first time user, Hi guys! So hopefully someone can help.. My background is php so entering the word of lowend stuff like, char is bytes, which are bits.. which is binary values.. etc is taking some time to get the hang of ;) What im trying to do here is sent some values from an Ardunio board to openFrameWorks (both are c++). What this script currently does (and works well for one sensor i might add) when asked for the data to be sent is.. int value_01 = analogRead(0); // which outputs between 0-1024 unsigned char val1; unsigned char val2; //some Complicated bitshift operation val1 = value_01 &0xFF; val2 = (value_01 >> 8) &0xFF; //send both bytes Serial.print(val1, BYTE); Serial.print(val2, BYTE); Apparently this is the most reliable way of getting the data across.. So now that it is send via serial port, the bytes are added to a char string and converted back by.. int num = ( (unsigned char)bytesReadString[1] << 8 | (unsigned char)bytesReadString[0] ); So to recap, im trying to get 4 sensors worth of data (which im assuming will be 8 of those serialprints?) and to have int num_01 - num_04... at the end of it all. Im assuming this (as with most things) might be quite easy for someone with experience in these concepts.. Any help would be greatly appreciated. Thanks

    Read the article

  • How to declare a 2D array of 2D array pointers and access them?

    - by vikramtheone
    Hi Guys, How can I declare an 2D array of 2D Pointers? And later access the individual array elements of the 2D arrays. Is my approach correct? void alloc_2D(int ***memory, unsigned int rows, unsigned int cols); int main() { int i, j; int **ptr; int **array[10][10]; for(i=0;i<10;i++) { for(j=0;j<10;j++) { alloc_2D(&ptr, 10, 10); array[i][j] = ptr; } } //After I do this, how can I access the 10 individual 2D arrays? return 0; } void alloc_2D(int ***memory, unsigned int rows, unsigned int cols) { int **ptr; *memory = NULL; ptr = malloc(rows * sizeof(int*)); if(ptr == NULL) { printf("\nERROR: Memory allocation failed!"); } else { int i; for(i = 0; i< rows; i++) { ptr[i] = malloc(cols * sizeof(float)); if(ptr[i]==NULL) { printf("\nERROR: Memory allocation failed!"); } } } *memory = ptr; }

    Read the article

  • How slow are bit fields in C++

    - by Shane MacLaughlin
    I have a C++ application that includes a number of structures with manually controlled bit fields, something like #define FLAG1 0x0001 #define FLAG2 0x0002 #define FLAG3 0x0004 class MyClass { ' ' unsigned Flags; int IsFlag1Set() { return Flags & FLAG1; } void SetFlag1Set() { Flags |= FLAG1; } void ResetFlag1() { Flags &= 0xffffffff ^ FLAG1; } ' ' }; For obvious reasons I'd like to change this to use bit fields, something like class MyClass { ' ' struct Flags { unsigned Flag1:1; unsigned Flag2:1; unsigned Flag3:1; }; ' ' }; The one concern I have with making this switch is that I've come across a number of references on this site stating how slow bit fields are in C++. My assumption is that they are still faster than the manual code shown above, but is there any hard reference material covering the speed implications of using bit fields on various platforms, specifically 32bit and 64bit windows. The application deals with huge amounts of data in memory and must be both fast and memory efficient, which could well be why it was written this way in the first place.

    Read the article

  • User defined literal arguments are not constexpr?

    - by Pubby
    I'm testing out user defined literals. I want to make _fac return the factorial of the number. Having it call a constexpr function works, however it doesn't let me do it with templates as the compiler complains that the arguments are not and cannot be constexpr. I'm confused by this - aren't literals constant expressions? The 5 in 5_fac is always a literal that can be evaluated during compile time, so why can't I use it as such? First method: constexpr int factorial_function(int x) { return (x > 0) ? x * factorial_function(x - 1) : 1; } constexpr int operator "" _fac(unsigned long long x) { return factorial_function(x); // this works } Second method: template <int N> struct factorial { static const unsigned int value = N * factorial<N - 1>::value; }; template <> struct factorial<0> { static const unsigned int value = 1; }; constexpr int operator "" _fac(unsigned long long x) { return factorial_template<x>::value; // doesn't work - x is not a constexpr }

    Read the article

  • MySql Check if NOW() falls within a weekday/time range

    - by Niall
    I have a table as follows: CREATE TABLE `zonetimes` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `zone_id` int(10) unsigned NOT NULL, `active_from_day` tinyint(1) unsigned NOT NULL DEFAULT '2', `active_to_day` tinyint(1) unsigned NOT NULL DEFAULT '2', `active_from` time NOT NULL, `active_to` time NOT NULL PRIMARY KEY (`id`) ) ENGINE=MyISAM ; So, a user could add a time entry starting on a particular day and time and ending on a particular day and time, eg: Between Monday 08:00 and Friday 18:00 or Between Thursday 15:00 and Tuesday 15:00 (Note the crossover at the end of the week). I need to query this data and determine if a zone is currently active (NOW(), DAYOFWEEK() etc)... This is turning out to be quite tricky. If I didn't have overlaps, eg: from 'Wednesday 8pm to Tuesday 4am' or from 'Thursday 4pm to Tuesday 4pm' this would be easy with BETWEEN. Also, need to allow a user to add for the entire week, eg: Monday 8am - Monday 8am (This should be easy enough, eg: where (active_from_day=active_to_day AND active_from=active_to) OR .. Any ideas? Note: I found a similar question here Timespan - Check for weekday and time of day in mysql but it didn't get an answer. One of the suggestions was to store each day as a separate row. I would much rather store one time span for multiple days though.

    Read the article

  • C++, using one byte to store two variables

    - by 2di
    Hi All I am working on representation of the chess board, and I am planning to store it in 32 bytes array, where each byte will be used to store two pieces. (That way only 4 bits are needed per piece) Doing it in that way, results in a overhead for accessing particular index of the board. Do you think that, this code can be optimised or completely different method of accessing indexes can be used? c++ char getPosition(unsigned char* c, int index){ //moving pointer c+=(index>>1); //odd number if (index & 1){ //taking right part return *c & 0xF; }else { //taking left part return *c>>4; } } void setValue(unsigned char* board, char value, int index){ //moving pointer board+=(index>>1); //odd number if (index & 1){ //replace right part //save left value only 4 bits *board = (*board & 0xF0) + value; }else { //replacing left part *board = (*board & 0xF) + (value<<4); } } int main() { char* c = (char*)malloc(32); for (int i = 0; i < 64 ; i++){ setValue((unsigned char*)c, i % 8,i); } for (int i = 0; i < 64 ; i++){ cout<<(int)getPosition((unsigned char*)c, i)<<" "; if (((i+1) % 8 == 0) && (i > 0)){ cout<<endl; } } return 0; } I am equally interested in your opinions regarding chess representations, and optimisation of the method above, as a stand alone problem. Thanks a lot

    Read the article

  • symfony + doctrine + inheritance, how to make them work?

    - by imac
    I am beginning to work with Symfony, I've found some documentation about inheritance. But also found this discouraging article, which make me doubt if Doctrine handles inheritance any good at all... Has anyone find a smart solution for inheritance in Symfony+Doctrine? As an example, I have already structured the database something like this: CREATE TABLE `poster` ( `poster_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, PRIMARY KEY (`poster_id`), UNIQUE KEY `id` (`poster_id`), ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; CREATE TABLE `user` ( `user_id` int(11) NOT NULL, `real_name` varchar(50) DEFAULT NULL, PRIMARY KEY (`user_id`), UNIQUE KEY `user_id` (`user_id`), CONSTRAINT `user_fk` FOREIGN KEY (`user_id`) REFERENCES `poster` (`poster_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; From that, Doctrine generated this "schema.yml": Poster: connection: doctrine tableName: poster columns: poster_id: type: integer(4) fixed: false unsigned: false primary: true autoincrement: true user_name: type: string(50) fixed: false unsigned: false primary: false notnull: true autoincrement: false relations: Post: local: poster_id foreign: poster_id type: many User: local: poster_id foreign: user_id type: many Version: local: poster_id foreign: poster_id type: many User: connection: doctrine tableName: user columns: user_id: type: integer(4) fixed: false unsigned: false primary: true autoincrement: false real_name: type: string(50) fixed: false unsigned: false primary: false notnull: false autoincrement: false relations: Poster: local: user_id foreign: poster_id type: one User creation for this structure with Doctrine auto-generated forms does not work. Any clue will be appreciated.

    Read the article

  • Storing data in a MySQL database using MySQL & PHP

    - by comma
    I'm new to PHP and MySQL and I'm trying to store a users entered data from the following fields $skill, $experience, $years which a user can also add additional fields of $skill, $experience, $years if needed so in instead of 1 of each field there might be multiples of each field. I was wondering how can I store the fields in my MySQL database using PHP and MySQL? I have the following script but I know its wrong. can some one help me fix the script listed below? Here is the PHP and MySQL code. $skill = serialize($_POST['skill']); $experience = serialize($_POST['experience']); $years = serialize($_POST['years']); for (($s = 0; $s < count($skill); $s++) && ($x = 0; $x < count($experience); $x++) && ($g = 0; $g < count($years); $g++)){ $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $query1 = "INSERT INTO learned_skills (skill, experience, years) VALUES ('" . $skill[$s] . "', '" . $experience[$x] . "', '" . $years[$g] . "')"; if (!mysqli_query($mysqli, $query1)) { print mysqli_error($mysqli); return; } } Here is my MySQL table. CREATE TABLE learned_skills ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, skill TEXT NOT NULL, experience TEXT NOT NULL, years INT NOT NULL, PRIMARY KEY (id) ); CREATE TABLE u_skills ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, skill_id INT UNSIGNED NOT NULL, users_id INT UNSIGNED NOT NULL, PRIMARY KEY (id) );

    Read the article

  • OpenCV compare two images and get different pixels

    - by Richard Knop
    For some reason the code bellow is not working. I have two 640*480 images which are very similar but not the same (at least few hundred/thousand pixels should be different). This is how I am comparing them and counting different pixels: unsigned char* row; unsigned char* row2; int count = 0; // this happens in a loop // fIplImageHeader is current image // lastFIplImageHeader is image from previous iteration if ( NULL != lastFIplImageHeader->imageData ) { for( int y = 0; y < fIplImageHeader->height; y++ ) { row = &CV_IMAGE_ELEM( fIplImageHeader, unsigned char, y, 0 ); row2 = &CV_IMAGE_ELEM( lastFIplImageHeader, unsigned char, y, 0 ); for( int x = 0; x < fIplImageHeader->width*fIplImageHeader->nChannels; x += fIplImageHeader->nChannels ) { if (row[x] == row2[x]) // the pixel in the first channel (usually G) { count++; } if (row[x+1] == row2[x+1]) // ... second channel (usually B) { count++; } if (row[x+2] == row2[x+2]) // ... third channel (usually R) { count++; } } } } Now at the end I get number 3626 which would seem alright. But, I tried opening one of the images in MS Paint and drawing thick red lines all over it which should increase the number of different pixels substantially. I got the same number again: 3626. Obviously I am doing something wrong here. I am comparing these images in a loop. This line is before the loop: IplImage* lastFIplImageHeader = cvCreateImageHeader(cvSize(640, 480), 8, 3); Then inside the loop I load images like this: IplImage* fIplImageHeader = cvLoadImage( filePath.c_str() ); // here I compare the pixels (the first code snippet) lastFIplImageHeader->imageData = fIplImageHeader->imageData; So lastFIplImageHeader is storing the image from the previous iteration and fIplImageHeader is storing the current image.

    Read the article

  • Using unions to simplify casts

    - by Steven Lu
    I realize that what I am trying to do isn't safe. But I am just doing some testing and image processing so my focus here is on speed. Right now this code gives me the corresponding bytes for a 32-bit pixel value type. struct Pixel { unsigned char b,g,r,a; }; I wanted to check if I have a pixel that is under a certain value (e.g. r, g, b <= 0x10). I figured I wanted to just conditional-test the bit-and of the bits of the pixel with 0x00E0E0E0 (I could have wrong endianness here) to get the dark pixels. Rather than using this ugly mess (*((uint32_t*)&pixel)) to get the 32-bit unsigned int value, i figured there should be a way for me to set it up so I can just use pixel.i, while keeping the ability to reference the green byte using pixel.g. Can I do this? This won't work: struct Pixel { unsigned char b,g,r,a; }; union Pixel_u { Pixel p; uint32_t bits; }; I would need to edit my existing code to say pixel.p.g to get the green color byte. Same happens if I do this: union Pixel { unsigned char c[4]; uint32_t bits; }; This would work too but I still need to change everything to index into c, which is a bit ugly but I can make it work with a macro if i really needed to.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >