int QDeclarativeAnchorSet::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; #ifndef QT_NO_PROPERTIES if (_c == QMetaObject::ReadProperty) { void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< QDeclarativeScriptString*>(_v) = left(); break; case 1: *reinterpret_cast< QDeclarativeScriptString*>(_v) = right(); break; case 2: *reinterpret_cast< QDeclarativeScriptString*>(_v) = horizontalCenter(); break; case 3: *reinterpret_cast< QDeclarativeScriptString*>(_v) = top(); break; case 4: *reinterpret_cast< QDeclarativeScriptString*>(_v) = bottom(); break; case 5: *reinterpret_cast< QDeclarativeScriptString*>(_v) = verticalCenter(); break; case 6: *reinterpret_cast< QDeclarativeScriptString*>(_v) = baseline(); break; } _id -= 7; } else if (_c == QMetaObject::WriteProperty) { void *_v = _a[0]; switch (_id) { case 0: setLeft(*reinterpret_cast< QDeclarativeScriptString*>(_v)); break; case 1: setRight(*reinterpret_cast< QDeclarativeScriptString*>(_v)); break; case 2: setHorizontalCenter(*reinterpret_cast< QDeclarativeScriptString*>(_v)); break; case 3: setTop(*reinterpret_cast< QDeclarativeScriptString*>(_v)); break; case 4: setBottom(*reinterpret_cast< QDeclarativeScriptString*>(_v)); break; case 5: setVerticalCenter(*reinterpret_cast< QDeclarativeScriptString*>(_v)); break; case 6: setBaseline(*reinterpret_cast< QDeclarativeScriptString*>(_v)); break; } _id -= 7; } else if (_c == QMetaObject::ResetProperty) { switch (_id) { case 0: resetLeft(); break; case 1: resetRight(); break; case 2: resetHorizontalCenter(); break; case 3: resetTop(); break; case 4: resetBottom(); break; case 5: resetVerticalCenter(); break; case 6: resetBaseline(); break; } _id -= 7; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 7; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 7; } #endif // QT_NO_PROPERTIES return _id; }
/* Test the method 'transformToVectorCoordinates'*/ TEST_F(PositionVectorTest, test_method_transformToVectorCoordinates) { { PositionVector vec1; vec1.push_back(Position(1,0)); vec1.push_back(Position(10,0)); vec1.push_back(Position(10,5)); vec1.push_back(Position(20,5)); Position on(4,0); Position left(4,1); Position right(4,-1); Position left2(4,2); Position right2(4,-2); Position cornerRight(13,-4); Position cornerLeft(7,9); Position before(0,-1); Position beyond(24,9); EXPECT_EQ(Position(3, 0), vec1.transformToVectorCoordinates(on)); EXPECT_EQ(Position(3, -1), vec1.transformToVectorCoordinates(left)); EXPECT_EQ(Position(3, 1), vec1.transformToVectorCoordinates(right)); EXPECT_EQ(Position(3, -2), vec1.transformToVectorCoordinates(left2)); EXPECT_EQ(Position(3, 2), vec1.transformToVectorCoordinates(right2)); EXPECT_EQ(Position(9, 5), vec1.transformToVectorCoordinates(cornerRight)); EXPECT_EQ(Position(14, -5), vec1.transformToVectorCoordinates(cornerLeft)); EXPECT_EQ(Position::INVALID, vec1.transformToVectorCoordinates(before)); EXPECT_EQ(Position::INVALID, vec1.transformToVectorCoordinates(beyond)); EXPECT_EQ(Position(-1, 1), vec1.transformToVectorCoordinates(before, true)); EXPECT_EQ(Position(28, -4), vec1.transformToVectorCoordinates(beyond, true)); } { PositionVector vec1; // the same tests as before, mirrored on x-axis vec1.push_back(Position(1,0)); vec1.push_back(Position(10,0)); vec1.push_back(Position(10,-5)); vec1.push_back(Position(20,-5)); Position on(4,0); Position left(4,-1); Position right(4,1); Position left2(4,-2); Position right2(4,2); Position cornerRight(13,4); Position cornerLeft(7,-9); Position before(0,1); Position beyond(24,-9); EXPECT_EQ(Position(3, 0), vec1.transformToVectorCoordinates(on)); EXPECT_EQ(Position(3, 1), vec1.transformToVectorCoordinates(left)); EXPECT_EQ(Position(3, -1), vec1.transformToVectorCoordinates(right)); EXPECT_EQ(Position(3, 2), vec1.transformToVectorCoordinates(left2)); EXPECT_EQ(Position(3, -2), vec1.transformToVectorCoordinates(right2)); EXPECT_EQ(Position(9, -5), vec1.transformToVectorCoordinates(cornerRight)); EXPECT_EQ(Position(14, 5), vec1.transformToVectorCoordinates(cornerLeft)); EXPECT_EQ(Position::INVALID, vec1.transformToVectorCoordinates(before)); EXPECT_EQ(Position::INVALID, vec1.transformToVectorCoordinates(beyond)); EXPECT_EQ(Position(-1, -1), vec1.transformToVectorCoordinates(before, true)); EXPECT_EQ(Position(28, 4), vec1.transformToVectorCoordinates(beyond, true)); } }
void NotificationView::Draw(BRect updateRect) { BRect progRect; SetDrawingMode(B_OP_ALPHA); SetBlendingMode(B_PIXEL_ALPHA, B_ALPHA_OVERLAY); // Icon size float iconSize = (float)fParent->IconSize(); BRect stripeRect = Bounds(); stripeRect.right = kIconStripeWidth; SetHighColor(tint_color(ui_color(B_PANEL_BACKGROUND_COLOR), B_DARKEN_1_TINT)); FillRect(stripeRect); SetHighColor(fStripeColor); stripeRect.right = 2; FillRect(stripeRect); SetHighColor(ui_color(B_PANEL_TEXT_COLOR)); // Rectangle for icon and overlay icon BRect iconRect(0, 0, 0, 0); // Draw icon if (fBitmap) { float ix = 18; float iy = (Bounds().Height() - iconSize) / 4.0; // Icon is vertically centered in view if (fNotification->Type() == B_PROGRESS_NOTIFICATION) { // Move icon up by half progress bar height if it's present iy -= (progRect.Height() + kEdgePadding); } iconRect.Set(ix, iy, ix + iconSize - 1.0, iy + iconSize - 1.0); DrawBitmapAsync(fBitmap, fBitmap->Bounds(), iconRect); } // Draw content LineInfoList::iterator lIt; for (lIt = fLines.begin(); lIt != fLines.end(); lIt++) { LineInfo *l = (*lIt); SetFont(&l->font); // Truncate the string. We have already line-wrapped the text but if // there is a very long 'word' we can only truncate it. TruncateString(&(l->text), B_TRUNCATE_END, Bounds().Width() - l->location.x); DrawString(l->text.String(), l->text.Length(), l->location); } rgb_color detailCol = ui_color(B_CONTROL_BORDER_COLOR); detailCol = tint_color(detailCol, B_LIGHTEN_2_TINT); AppGroupView* groupView = dynamic_cast<AppGroupView*>(Parent()); if (groupView != NULL && groupView->ChildrenCount() > 1) _DrawCloseButton(updateRect); SetHighColor(tint_color(ViewColor(), B_DARKEN_1_TINT)); BPoint left(Bounds().left, Bounds().top); BPoint right(Bounds().right, Bounds().top); StrokeLine(left, right); Sync(); }
splitPair* treap::splitDecrease() { splitPair* result = new splitPair; if (root == NULL) // Вариант пустого дерева { result->leftTreap = new treap; result->rightTreap = new treap; return result; } push(); // Проталкивание реверса if (getIsDecreas()) // Если все дерево убывает { treap *prefix = new treap, *suffix = new treap; suffix->setRoot(root); // Суффикс это все дерево, а префикс пуст // Возвращаем результат result->rightTreap = suffix; result->leftTreap = prefix; return result; } //Сделаем две будевые переменные о наличии правого и левого поддерева для удобства bool isRight = (right()->getRoot() != NULL), isLeft = (left()->getRoot() != NULL); bool needRight = false; // Рещаем, находится суффикс только в правом поддереве или нет if (isRight) if (! root->getRight()->getIsDecreas()) needRight = true; if (needRight) // Если правое поддерево не полностью убывает, то искать надо в нем { treap *prefix = new treap, *suffix = new treap; splitPair* tempSplit = right()->splitDecrease(); // Рекрсивно отрезаем суффикс в правом поддереве suffix->setRoot(tempSplit->rightTreap->getRoot()); // А потом восстанавливаем префикс root->setRight (NULL); setRight(tempSplit->leftTreap->getRoot()); prefix->setRoot(root); // Собираем и возвращаем рузультат result->leftTreap = prefix; result->rightTreap = suffix; return result; // И возвращаем результат } else // Иначе надо отрезать какую-то часть левого поддерева { // Сначала решаем, нужно ли брать корень дерева bool needRoot = false; if (!isRight) needRoot = true; else if ( root->getValue() >= right()->getMax() ) needRoot = true; if (needRoot) // Если корень нужен { splitPair* tempSplit = new splitPair; treap *prefix = new treap, *suffix = new treap; if (isLeft) // Если есть левое поддерево tempSplit = left()->splitDecrease (); // Рекурсивно отрезаем от него его суффикс // Первоначальные заготовки префикса и суффикса prefix->setRoot(tempSplit->leftTreap->getRoot()); root->setLeft(NULL); suffix->setRoot(root); bool needTempSuf = false; // Теперь решаем, нужно ли тот, рекурсивно отрезаный суффикс прикреплять к основному if (tempSplit->rightTreap->getRoot() != NULL) if (root->getValue() <= tempSplit->rightTreap->getMin()) needTempSuf = true; if (needTempSuf) // В зависивости от этого прикрепляем рекурсивно отрезаный суффикс к префиксу или основному суффиксу suffix = merge (tempSplit->rightTreap, suffix); else prefix = merge (prefix, tempSplit->rightTreap); // Собираем и возвращаем результат result->leftTreap = prefix; result->rightTreap = suffix; return result; } else // А если корень не нужен { treap *prefix = new treap, *suffix = new treap; suffix->setRoot(root->getRight()); // То суффикс это правое поддерево root->setRight(NULL); prefix->setRoot(root); // А префикс - все остальное (с отрезаным правым поддеревом) // Результат result->rightTreap = suffix; result->leftTreap = prefix; return result; } } }
void ExploreLiveView::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget * widget) { if(!isReady) return; prePaint(painter); postPaint(painter); auto glwidget = (Viewer*)widget; if (glwidget && meshes.size()) { QRectF parentRect = parentItem()->sceneBoundingRect(); if (isCacheImage && cachedImage.isNull()) { QOpenGLContext context; context.setShareContext(glwidget->context()); context.setFormat(glwidget->format()); context.create(); QOffscreenSurface m_offscreenSurface; m_offscreenSurface.setFormat(context.format()); m_offscreenSurface.create(); context.makeCurrent(&m_offscreenSurface); QOpenGLFramebufferObjectFormat fboformat; fboformat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); QOpenGLFramebufferObject renderFbo(cacheImageSize*1.5, cacheImageSize, fboformat); renderFbo.bind(); glwidget->glEnable(GL_DEPTH_TEST); glwidget->glEnable(GL_BLEND); glwidget->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glwidget->glCullFace(GL_BACK); glwidget->glClearColor(0,0,0,0); glwidget->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glwidget->glViewport(0, 0, cacheImageSize*1.5, cacheImageSize); // XXX Fix // glwidget->glPointSize(10); // Draw aux meshes for (auto mesh : meshes) { if (mesh.isPoints) glwidget->drawOrientedPoints(mesh.points, mesh.normals, mesh.color, glwidget->pvm); else glwidget->drawTriangles(mesh.color, mesh.points, mesh.normals, glwidget->pvm); } glwidget->glDisable(GL_DEPTH_TEST); glwidget->glFlush(); renderFbo.release(); cachedImage = renderFbo.toImage(); isReady = true; // Thanks for sharing! glwidget->makeCurrent(); } // Draw as image if(isCacheImage) { int w = shapeRect.width(); painter->drawImage(w * -0.5, w * -0.5, cachedImage.scaledToWidth(w)); } if(!isCacheImage) { auto r = shapeRect; // scale view double s = 1.5; r.setWidth(r.width() * s); r.setHeight(r.height() * s); r.moveCenter(this->mapToScene(boundingRect().center())); painter->beginNativePainting(); auto v = scene()->views().first(); QPoint viewDelta = v->mapFromScene(r.topLeft()); if (viewDelta.manhattanLength() > 5) r.moveTopLeft(viewDelta); auto camera = ExploreProcess::defaultCamera(document->extent().length()); glwidget->eyePos = camera.first; glwidget->pvm = camera.second; glwidget->glViewport(r.left(), v->height() - r.height() - r.top(), r.width(), r.height()); // Clipping OpenGL glwidget->glEnable(GL_SCISSOR_TEST); glwidget->glScissor(parentRect.x(), v->height() - parentRect.height() - parentRect.top(), parentRect.width(), parentRect.height()); glwidget->glClear(GL_DEPTH_BUFFER_BIT); // FIX XXX // glwidget->glPointSize(2); // Draw aux meshes for (auto mesh : meshes) { if (mesh.isPoints) glwidget->drawOrientedPoints(mesh.points, mesh.normals, mesh.color, glwidget->pvm); else glwidget->drawTriangles(mesh.color, mesh.points, mesh.normals, glwidget->pvm); } glwidget->glDisable(GL_SCISSOR_TEST); painter->endNativePainting(); } } }
NS_IMETHODIMP nsEnigMsgCompose::OnDataAvailable(nsIRequest* aRequest, nsISupports* aContext, nsIInputStream *aInputStream, PRUint32 aSourceOffset, PRUint32 aLength) { nsresult rv; DEBUG_LOG(("nsEnigMsgCompose::OnDataAVailable: %d\n", aLength)); if (!mPipeTrans) return NS_ERROR_NOT_INITIALIZED; char buf[kCharMax]; PRUint32 readCount, readMax, writeCount; while (aLength > 0) { readMax = (aLength < kCharMax) ? aLength : kCharMax; rv = aInputStream->Read((char *) buf, readMax, &readCount); if (NS_FAILED(rv)){ DEBUG_LOG(("nsEnigMsgCompose::OnDataAvailable: Error in reading from input stream, %p\n", rv)); return rv; } if (readCount <= 0) return NS_OK; writeCount = readCount; if (mMultipartSigned) { nsCString tmpStr; tmpStr.Assign(buf, readCount); nsCString left(tmpStr); left.SetLength(15); if (left.LowerCaseEqualsLiteral("x-mozilla-keys:")) { DEBUG_LOG(("nsEnigMimeWriter::OnDataAvailable: workaround for 'X-Mozilla-Keys:' header\n")); tmpStr.StripWhitespace(); if (left == tmpStr) { if (buf[readCount-2] == '\r' && buf[readCount-1] == '\n') { tmpStr.Append("\r\n"); } else tmpStr.Append("\n"); rv = WriteToPipe(tmpStr.get(), tmpStr.Length()); if (NS_FAILED(rv)) return rv; rv = WriteOut(tmpStr.get(), tmpStr.Length()); if (NS_FAILED(rv)) return rv; aLength -= readCount; return NS_OK; } } rv = WriteToPipe(buf, readCount); if (NS_FAILED(rv)) return rv; rv = WriteOut(buf, readCount); if (NS_FAILED(rv)) return rv; } else { rv = WriteToPipe(buf, readCount); if (NS_FAILED(rv)) return rv; } aLength -= readCount; } return NS_OK; }
task main() { init(); waitForStart(); driveSonar(1,25,80); allStop(); wait1Msec(100); backward(20); wait1Msec(700); sticksDown(); wait1Msec(250); allStop(); wait1Msec(100); raiseLift(100); time1[T1]=0; while (nMotorEncoder[intake] < 410 && time1[T1] < 2500) //while the encoder wheel turns one revolution { times = time1[T1]; } allStop(); wait1Msec(500); //if(time1[T1]>2500) // while(true){ // nxtDisplayCenteredBigTextLine(1,":("); // } releaseBalls(); allStop(); wait1Msec(3000); retainBalls(); allStop(); wait1Msec(750); lowerLift(80); while (nMotorEncoder[intake] > 220) //while the encoder wheel turns one revolution { } allStop(); wait1Msec(500); releaseAutoBall(); wait1Msec(500); motor[intake] = 100; wait1Msec(1000); motor[intake] = 0; turn(0,180,100); allStop(); wait1Msec(100); drive(1,1,75); sticksUp(); drive(0,1,75); time1[T1]=0; while(SensorValue[sonarSensor]>30||time1[T1]<1200){ left(50); } while(SensorValue[sonarSensor]<200){ left(50); } allStop(); wait1Msec(100); turn(0,25,70); allStop(); wait1Msec(100); driveSonar(1,25,50); backward(30); wait1Msec(700); sticksDown(); wait1Msec(250); allStop(); raiseLift(100); while (nMotorEncoder[intake] < 1000) //while the encoder wheel turns one revolution { } allStop(); wait1Msec(500); releaseBalls(); allStop(); wait1Msec(3000); retainBalls(); allStop(); wait1Msec(750); lowerLift(80); while (nMotorEncoder[intake] > 740) //while the encoder wheel turns one revolution { } allStop(); wait1Msec(500); }
int hasLeft(Tas *t, int i) { return isNoeud(t, left(i)); }
// for: _iadd, _imul, _isub, _idiv, _irem void LIRGenerator::do_ArithmeticOp_Int(ArithmeticOp* x) { if (x->op() == Bytecodes::_idiv || x->op() == Bytecodes::_irem) { // The requirements for division and modulo // input : eax: dividend min_int // reg: divisor (may not be eax/edx) -1 // // output: eax: quotient (= eax idiv reg) min_int // edx: remainder (= eax irem reg) 0 // eax and edx will be destroyed // Note: does this invalidate the spec ??? LIRItem right(x->y(), this); LIRItem left(x->x() , this); // visit left second, so that the is_register test is valid left.set_destroys_register(); right.set_destroys_register(); left.load_item(); right.load_item(); if (x->op() == Bytecodes::_idiv) { set_result(x, divOutRInfo()); } else { set_result(x, remOutRInfo()); } if (!ImplicitDiv0Checks) { CodeEmitInfo* info = state_for(x); emit()->explicit_div_by_zero_check(right.result(), info); } CodeEmitInfo* info = state_for(x); RInfo tmp = FrameMap::_edxRInfo; // idiv and irem use edx in their implementation emit()->arithmetic_idiv(x->op(), x->operand(), left.result(), right.result(), tmp, info); } else { // missing test if instr is commutative and if we should swap LIRItem left(x->x(), this); LIRItem right(x->y(), this); LIRItem* left_arg = &left; LIRItem* right_arg = &right; if (x->is_commutative() && left.is_stack() && right.is_register()) { // swap them if left is real stack (or cached) and right is real register(not cached) left_arg = &right; right_arg = &left; } left_arg->set_destroys_register(); left_arg->load_item(); // do not need to load right, as we can handle stack and constants if (x->op() == Bytecodes::_imul ) { // check if we can use shift instead RInfo tmp; bool use_constant = false; bool use_tmp = false; if (right_arg->is_constant()) { int iconst = right_arg->get_jint_constant(); if (iconst > 0) { if (is_power_of_2(iconst)) { use_constant = true; } else if (is_power_of_2(iconst - 1) || is_power_of_2(iconst + 1)) { use_constant = true; use_tmp = true; } } } if (use_constant) { right_arg->dont_load_item(); } else { right_arg->load_item(); } if (use_tmp) { tmp = new_register(T_INT)->rinfo(); } RInfo reg = rlock_result(x)->rinfo(); emit()->arithmetic_op_int(x->op(), x->operand(), left_arg->result(), right_arg->result(), tmp); } else { right_arg->dont_load_item(); RInfo reg = rlock_result(x)->rinfo(); RInfo tmp; emit()->arithmetic_op_int(x->op(), x->operand(), left_arg->result(), right_arg->result(), tmp); } } }
void rev_getForks(int p) { printf(1, "%d tries to get forks\n",p); pthread_sem_wait(&forks[right(p)]); pthread_sem_wait(&forks[left(p)]); printf(1, "%d gets forks\n",p); }
void putForks(int p) { printf(1, "%d puts the forks\n",p); pthread_sem_post(&forks[left(p)]); pthread_sem_post(&forks[right(p)]); }
bool interval_range_query::writeRecordLocations(vmgr_reply &mgr_reply, node_deque_t &node_deque, metadata::replica_list_t &provider_list) { if (node_deque.empty()) return false; bool result = true; metadata::query_t query = mgr_reply.intervals.rbegin()->first; DBG("root size = " << mgr_reply.root_size); // first write the nodes in the queue for (unsigned int i = 0, j = 0; result && (i < node_deque.size()); i++, j += mgr_reply.stable_root.replica_count) { metadata::dhtnode_t node(true); metadata::replica_list_t providers; node.left = node_deque[i]; node_deque[i].version = query.version; node_deque[i].offset = query.offset + node_deque[i].offset * node_deque[i].size; for (unsigned int k = j; result && k < j + mgr_reply.stable_root.replica_count; k++) providers.push_back(provider_list[k]); // put list of providers DBG("PUT PAGE KEY: " << node.left); dht->put(buffer_wrapper(node.left, true), buffer_wrapper(providers, true), TTL, SECRET, bind(write_callback, boost::ref(result), _1) ); DBG("PUT LEAF: " << node_deque[i]); dht->put(buffer_wrapper(node_deque[i], true), buffer_wrapper(node, true), TTL, SECRET, bind(write_callback, boost::ref(result), _1) ); } // calculate the left and right leaf boost::uint64_t page_size = mgr_reply.stable_root.page_size; metadata::query_t left(query.id, query.version, (query.offset / page_size) * page_size, page_size); metadata::query_t right(query.id, query.version, ((query.offset + query.size) / page_size - ((query.offset + query.size) % page_size == 0 ? 1 : 0)) * page_size, page_size); // compute left and right sibling versions. metadata::siblings_enum_t left_siblings, right_siblings; mgr_reply.intervals.erase(mgr_reply.intervals.rbegin()->first); compute_sibling_versions(left_siblings, left, mgr_reply.intervals, mgr_reply.root_size); compute_sibling_versions(right_siblings, right, mgr_reply.intervals, mgr_reply.root_size); // fill in the left siblings from the stable version if we intresect the stable root, or use it directly if not DBG("stable root: " << mgr_reply.stable_root.node); if (mgr_reply.stable_root.node.intersects(node_deque.front())) dht->get(buffer_wrapper(mgr_reply.stable_root.node, true), boost::bind(siblings_callback, dht, true, boost::ref(node_deque.front()), boost::ref(left_siblings), mgr_reply.stable_root.node, _1 ) ); else if (vmgr_reply::search_list(left_siblings, mgr_reply.stable_root.node.offset, mgr_reply.stable_root.node.size).empty()) left_siblings.push_back(mgr_reply.stable_root.node); // fill in the missing right siblings from the stable version (only if it makes sense) if (mgr_reply.stable_root.node.intersects(node_deque.back())) dht->get(buffer_wrapper(mgr_reply.stable_root.node, true), boost::bind(siblings_callback, dht, false, boost::ref(node_deque.back()), boost::ref(right_siblings), mgr_reply.stable_root.node, _1 ) ); dht->wait(); // process the nodes while (result && !node_deque.empty()) { metadata::query_t first_node = node_deque.front(); node_deque.pop_front(); if (first_node.size == mgr_reply.root_size) continue; metadata::query_t first_parent; unsigned int position = first_node.getParent(first_parent); metadata::query_t next_node; // if the next node has the same parent with first_node, elliminate both if (!node_deque.empty()) { next_node = node_deque.front(); metadata::query_t next_parent; if (next_node.size != mgr_reply.root_size && next_node.getParent(next_parent) == metadata::RIGHT_CHILD && first_parent == next_parent) { position = metadata::ROOT; node_deque.pop_front(); } } // if I was a left child, get my right brother if (position == metadata::LEFT_CHILD) { uint64_t new_size = first_node.offset + first_node.size; next_node = vmgr_reply::search_list(right_siblings, new_size, first_node.size); } // if I was a right child, get my left brother if (position == metadata::RIGHT_CHILD) { uint64_t new_size = first_node.offset - first_node.size; next_node = first_node; first_node = vmgr_reply::search_list(left_siblings, new_size, next_node.size); } node_deque.push_back(first_parent); metadata::dhtnode_t node(false); node.left = first_node; node.right = next_node; DBG("PUT: " << first_parent << " -> " << node); dht->put(buffer_wrapper(first_parent, true), buffer_wrapper(node, true), TTL, SECRET, bind(write_callback, boost::ref(result), _1) ); } dht->wait(); return result; }
void draw_it(const std::vector<std::vector<sf::Vertex>> & sims, float time, float height, std::string title) { //http://www.sfml-dev.org/tutorials/2.1/start-vc.php //nb -s for static libs const float edge = 30.0f; const float lineWidth = 5.0f; const float width = 500.0f; const float x_scale = width/time; const auto bagColour = sf::Color(180, 120, 60); sf::RenderWindow window(sf::VideoMode(static_cast<int>(width + 2*edge), static_cast<int>(height + 2*edge)), title); window.clear(sf::Color::Black); sf::RectangleShape left(sf::Vector2f(lineWidth, static_cast<float>(height))); left.setFillColor(bagColour); left.setPosition(edge, edge); window.draw(left); sf::RectangleShape right(sf::Vector2f(lineWidth, static_cast<float>(height))); right.setFillColor(bagColour); right.setPosition(edge + width, edge); window.draw(right); sf::RectangleShape base(sf::Vector2f(static_cast<float>(width) + lineWidth, lineWidth)); base.setFillColor(bagColour); base.setPosition(edge, edge + height); window.draw(base); assert(sims.begin()->size()); //TODO - and they are all the same size_t penultimate = sims.begin()->size() - 1; size_t last = 1; while (window.isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { // "close requested" event: we close the window if (event.type == sf::Event::Closed) window.close(); break; } window.clear(); window.draw(left); window.draw(right); window.draw(base); last = std::min(++last, sims.begin()->size() - 1); for(const auto & points: sims) { bool out = false; for(size_t i=0; i < last; ++i) { out |= (points[i].position.y > height);//what about the edge? sf::Color colour = out ? sf::Color::Green: sf::Color::White; auto scaled_start = to_vertex(points[i], colour, edge + lineWidth, x_scale, height); auto scaled_point = to_vertex(points[i+1], colour, edge + lineWidth, x_scale, height); sf::Vertex line[] = {scaled_start, scaled_point}; window.draw(line, 2, sf::Lines); } } window.display(); std::this_thread::sleep_for(std::chrono::milliseconds(50));//set render rate... or whatever it's called } }
//=========================================================================== int main () { { //------------------------------------------------------ // SETUP FIXTURE String left(X); String right(X); // TEST RESULT_TYPE result = (left OP right); // VERIFY assert(result == X); assert(left == X); assert(right == X); } { //------------------------------------------------------ // SETUP FIXTURE String left(X); String right(X); // TEST RESULT_TYPE result = (left OP right); // VERIFY assert(result == X); assert(left == X); assert(right == X); } { //------------------------------------------------------ // SETUP FIXTURE String left(X); String right(X); // TEST RESULT_TYPE result = (left OP right); // VERIFY assert(result == X); assert(left == X); assert(right == X); } { //------------------------------------------------------ // SETUP FIXTURE String left(X); String right(X); // TEST RESULT_TYPE result = (left OP right); // VERIFY assert(result == X); assert(left == X); assert(right == X); } { //------------------------------------------------------ // SETUP FIXTURE String left(X); String right(X); // TEST RESULT_TYPE result = (left OP right); // VERIFY assert(result == X); assert(left == X); assert(right == X); } { //------------------------------------------------------ // SETUP FIXTURE String left(X); String right(X); // TEST RESULT_TYPE result = (left OP right); // VERIFY assert(result == X); assert(left == X); assert(right == X); } // ADD ADDITIONAL TESTS AS NECESSARY std::cout << "Done testing XXX." << std::endl; }
void PlayerInputStruct::invertLeft() { setLeft(1000000 - left()); }
static bool findKey (Tree pl, Tree key, Tree& val) { if (isNil(pl)) return false; if (left(hd(pl)) == key) { val= right(hd(pl)); return true; } /* left(hd(pl)) != key */ return findKey (tl(pl), key, val); }
void VideoCorrect::correctImage(Mat& inputFrame, Mat& outputFrame, bool developerMode){ resize(inputFrame, inputFrame, CAMERA_RESOLUTION); inputFrame.copyTo(img); //Convert to YCbCr color space cvtColor(img, ycbcr, CV_BGR2YCrCb); //Skin color thresholding inRange(ycbcr, Scalar(0, 150 - Cr, 100 - Cb), Scalar(255, 150 + Cr, 100 + Cb), bw); if(IS_INITIAL_FRAME){ face = detectFaces(img); if(face.x != 0){ lastFace = face; } else{ outputFrame = img; return; } prevSize = Size(face.width/2, face.height/2); head = Mat::zeros(bw.rows, bw.cols, bw.type()); ellipse(head, Point(face.x + face.width/2, face.y + face.height/2), prevSize, 0, 0, 360, Scalar(255,255,255,0), -1, 8, 0); if(face.x > 0 && face.y > 0 && face.width > 0 && face.height > 0 && (face.x + face.width) < img.cols && (face.y + face.height) < img.rows){ img(face).copyTo(bestImg); } putText(img, "Give your best pose!", Point(face.x, face.y), CV_FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255,255,255,0), 1, CV_AA); } firstFrameCounter--; if(face.x == 0) //missing face prevention face = lastFace; //Mask the background out bw &= head; //Compute more accurate image moments after background removal m = moments(bw, true); angle = (atan((2*m.nu11)/(m.nu20-m.nu02))/2)*180/PI; center = Point(m.m10/m.m00,m.m01/m.m00); //Smooth rotation (running average) bufferCounter++; rotationBuffer[ bufferCounter % SMOOTHER_SIZE ] = angle; smoothAngle += (angle - rotationBuffer[(bufferCounter + 1) % SMOOTHER_SIZE]) / SMOOTHER_SIZE; //Expand borders copyMakeBorder( img, img, BORDER_EXPAND, BORDER_EXPAND, BORDER_EXPAND, BORDER_EXPAND, BORDER_REPLICATE, Scalar(255,255,255,0)); if(!IS_INITIAL_FRAME){ //Rotate the image to correct the leaning angle rotateImage(img, smoothAngle); //After rotation detect faces face = detectFaces(img); if(face.x != 0) lastFace = face; //Create background mask around the face head = Mat::zeros(bw.rows, bw.cols, bw.type()); ellipse(head, Point(face.x - BORDER_EXPAND + face.width/2, face.y -BORDER_EXPAND + face.height/2), prevSize, 0, 0, 360, Scalar(255,255,255,0), -1, 8, 0); //Draw a rectangle around the face //rectangle(img, face, Scalar(255,255,255,0), 1, 8, 0); //Overlay the ideal pose if(replaceFace && center.x > 0 && center.y > 0){ center = Point(face.x + face.width/2, face.y + face.width/2); overlayImage(img, bestImg, center, smoothSize); } } else{ face.x += BORDER_EXPAND; //position alignment after border expansion (not necessary if we detect the face after expansion) face.y += BORDER_EXPAND; } //Smooth ideal image size (running average) sizeBuffer[ bufferCounter % SMOOTHER_SIZE ] = face.width; smoothSize += (face.width - sizeBuffer[(bufferCounter + 1) % SMOOTHER_SIZE]) / SMOOTHER_SIZE; //Get ROI center = Point(face.x + face.width/2, face.y + face.width/2); roi = getROI(img, center); if(roi.x > 0 && roi.y > 0 && roi.width > 0 && roi.height > 0 && (roi.x + roi.width) < img.cols && (roi.y + roi.height) < img.rows){ img = img(roi); } //Resize the final image resize(img, img, CAMERA_RESOLUTION); if(developerMode){ Mat developerScreen(img.rows, img.cols + inputFrame.cols + bw.cols, CV_8UC3); Mat left(developerScreen, Rect(0, 0, img.size().width, img.size().height)); img.copyTo(left); Mat center(developerScreen, Rect(img.cols, 0, inputFrame.cols, inputFrame.rows)); inputFrame.copyTo(center); cvtColor(bw, bw, CV_GRAY2BGR); Mat right(developerScreen, Rect(img.size().width + inputFrame.size().width, 0, bw.size().width, bw.size().height)); bw.copyTo(right); Mat rightmost(developerScreen, Rect(img.size().width + inputFrame.size().width + bw.size().width - bestImg.size().width, 0, bestImg.size().width, bestImg.size().height)); bestImg.copyTo(rightmost); outputFrame = developerScreen; } else{ outputFrame = img; } }
static Tree updateKey (Tree pl, Tree key, Tree val) { if (isNil(pl)) return cons ( cons(key,val), nil ); if (left(hd(pl)) == key) return cons ( cons(key,val), tl(pl) ); /* left(hd(pl)) != key */ return cons ( hd(pl), updateKey( tl(pl), key, val )); }
bool Combo::operator ==(const Combo &ev) { return left() == ev.left() && right() == ev.right() && up() == ev.up() && down() == ev.down() && mid() == ev.mid(); }
static Tree removeKey (Tree pl, Tree key) { if (isNil(pl)) return nil; if (left(hd(pl)) == key) return tl(pl); /* left(hd(pl)) != key */ return cons (hd(pl), removeKey(tl(pl), key)); }
splitPair* treap::split (int x) { splitPair* result = new splitPair; // Возвращаемая величина if (root == NULL) // Пустое дерево не на что разбивать { result->leftTreap = new treap; result->rightTreap = new treap; return result; } if (x == 0) // Отдельно разбираем случай отрезания 0 слева { treap* treapR = new treap; treapR->setRoot(root); result->rightTreap = treapR; // В таком случае возвращается правым деревом будет все исходное result->leftTreap = new treap; // А левое пусто return result; } if (root->getSize() == x) // Еще один случай, когда все дерево надо отрезать полностью { treap* treapL = new treap; treapL->setRoot(root); result->leftTreap = treapL; // Тогда левое дерево - все исходное result->rightTreap = new treap; // А правое пустое return result; } int rootIndex = left()->getSize() + 1; // Посчитаем индекс корня для удобвства if (rootIndex == x) // Последний случай, когда надо разрезать ровно по корню { treap *treapL = new treap; treapL->setRoot(root); result->rightTreap = right(); //Тогда правое поддерево записываем вправо root->setRight(NULL); result->leftTreap = treapL; // А остальное, отрезав правую часть влево return result; } // Теперь невырожденные случаи push(); // Сначала протилкивание реверса treap *treapL = new treap, *treapR = new treap; //Сюда запишем наши деревья if (rootIndex <= x) // Смотрим, в левой или правой части дерева надо дальше разрезать { splitPair* temp = new splitPair; if (right()->getRoot() != NULL) // В правой разрезаем по ключу x - rootIndex temp = right()->split(x - rootIndex); // Потом правильно соберем левую часть treapL->setRoot(root); // Из того, что было слева корня if (temp->leftTreap != NULL) treapL->setRight ( temp->leftTreap->getRoot() ); // И того, что рекурсивно отрезали else treapL->setRight (NULL); treapR = temp->rightTreap; //Правая часть остается обрубком } else { splitPair* temp = new splitPair; if (left()->getRoot() != NULL) // В левой части резать надо по тому же ключу, что и раньше temp = left()->split(x); // А собирать по частям теперь будем правое дерево treapR->setRoot(root); if (temp->rightTreap != NULL ) treapR->setLeft( temp->rightTreap->getRoot() ); // Приклеивая к правой части старого дерева отрезанное рекурсивно else treapR->setLeft(NULL); treapL = temp->leftTreap; // Левая часть остается обрубком } //Теперь записываем результат result->leftTreap = treapL; result->rightTreap = treapR; return result; // И возвращаем его }
int main(void) //beginning of main function { DDRA=asmfunction(); //set PORTA to write DDRB=0xFF; //set PORTB to write DDRC=0xFF; //set PORTC to write DDRD=0b10111011; //set PIND2 and PIND6 to read and the rest of PORTD to write PORTB=PORTB&0b01111111; //set PINB7 to logic zero (turn on green LED) PORTB=PORTB|0b01000000; //set PINB6 to logic one (turn off red LED) PORTD=0b01000100; //enable pull-up resistors of PIND2 and PIND6 lcd_init(); //initialize LCD display lcd_clear(); //clear LCD display lcd_home(); //set cursor of LCD to the first character position /*The next two lines configure T/C0 and T/C2 to set OCR0 and OCR2, respectively on compare match when the T/C subsystem's respective counting register is counting up and to clear OCR0 and OCR2 when counting down. Configured as Fast PWM, Phase-Correct with a prescalar of one.*/ TCCR2=(1<<WGM20)|(1<<COM21)|(1<<COM20)|(1<<CS20); TCCR0=(1<<WGM00)|(1<<COM01)|(1<<COM00)|(1<<CS00); /*The next two lines configure TCNT1 to increment every clock cycle; Configure Enable Input Capture Interrupt to trigger on rising edge; Enable Input Capture Noise Canceller; Locally enable T/C 1 Input Capture Interrupt and T/C 1 Overflow Interrupt.*/ TCCR1B=(1<<ICES1)|(1<<CS10)|(1<<ICNC1); TIMSK=(1<<TICIE1)|(1<<TOIE1); MCUCR=(1<<ISC00)|(1<<ISC01);//configure external interrupt 1 to trigger on rising edge GICR=(1<<INT0); //locally enable external interrupt 1 sei(); //set global interrupt flag unsigned long int button=0; //unsigned long integer (32 bits--sent by IR remote) uint8_t led=0; //state of LED (used to confirm 34-bit transmission by IR remote) int speed=0; //speed of motors at maximum int lights=off; lcd_printf("Waiting"); //print "Waiting" on LCD (wait for button to be pushed on IR remote) PORTB=PORTB|0b00000010; while(1) //infinite loop { if(bit==34) //wait until bit=34--Input Capture ISR called 34 times (1 start bit, 32 data bits, and 1 stop bit sent by IR remote) { button=decipher(remote); //decipher the 32 data bits as either 1 or 0 depending on TCNT1 values; //pass remote as parameter and set button equal to return value bit=0; //reset bit equal to 0 (prepare to receive a new command) if(led==0) //if the state of led is 0, turn off green LED and turn on red LED { //then switch the state of led to 1 PORTB=PORTB&0b10111111; PORTB=PORTB|0b10000000; led++; } else //if the state of led is not 0 (state is 1), turn off red LED and turn on green LED { //then switch the state of led to 0 PORTB=PORTB&0b01111111; PORTB=PORTB|0b01000000; led--; } switch(button) //check the value of button (button that was pushed on remote) { case up_arrow: //if up arrow was pushed, make robot go forward forward(); break; case down_arrow: //if down arrow was pushed, make robot go backward backward(); break; case left_arrow: //if left arrow was pushed, make robot go left left(); break; case right_arrow: //if right arrow was pushed, make robot go right right(); break; case channel_up: //if channel up was pushed, speed robot up (speed is parameter sent to speed_up function); speed equals returned value speed=speed_up(speed); break; case channel_down: //if channel down was pushed, slow robot down (speed is parameter sent to speed_down function); speed equals returned value speed=slow_down(speed); break; case mute: //if mute was pushed, toggle lights from off to on or on to off; pass lights as parameter and set lights equal to returned value lights=toggle_lights(lights); break; default: //if any other button was pushed, stop robot stop(); break; } OCR0=speed; //set the speed of the left motor depending on value of speed OCR2=speed; //set the speed of the right motor depending on value of speed } } }
Animator::Animator(AbstractItemView *view) : QObject(view) { connect(view, SIGNAL(entered(QModelIndex)), SLOT(entered(QModelIndex))); connect(view, SIGNAL(left(QModelIndex)), SLOT(left(QModelIndex))); }
QList<Polygon> Polygon::convexPartition() const { // precondition: ccw; see mnbayazit.com/406/bayazit for details about how this works QList<Polygon> list; qreal d, dist1, dist2; QPointF ip, ip1, ip2; // intersection points int ind1, ind2; Polygon poly1, poly2; for(int i = 0; i < size(); ++i) { if(reflex(i)) { dist1 = dist2 = std::numeric_limits<qreal>::max(); for(int j = 0; j < size(); ++j) { if(left(at(i - 1), at(i), at(j)) && rightOn(at(i - 1), at(i), at(j - 1))) { // if ray (i-1)->(i) intersects with edge (j, j-1) QLineF(at(i - 1), at(i)).intersect(QLineF(at(j), at(j - 1)), &ip); if(right(at(i + 1), at(i), ip)) { // intersection point isn't caused by backwards ray d = sqdist(at(i), ip); if(d < dist1) { // take the closest intersection so we know it isn't blocked by another edge dist1 = d; ind1 = j; ip1 = ip; } } } if(left(at(i + 1), at(i), at(j + 1)) && rightOn(at(i + 1), at(i), at(j))) { // if ray (i+1)->(i) intersects with edge (j+1, j) QLineF(at(i + 1), at(i)).intersect(QLineF(at(j), at(j + 1)), &ip); if(left(at(i - 1), at(i), ip)) { d = sqdist(at(i), ip); if(d < dist2) { dist2 = d; ind2 = j; ip2 = ip; } } } } if(ind1 == (ind2 + 1) % size()) { // no vertices in range QPointF sp((ip1 + ip2) / 2); poly1 = copy(i, ind2); poly1.append(sp); poly2 = copy(ind1, i); poly2.append(sp); } else { double highestScore = 0, bestIndex = ind1, score; while(ind2 < ind1) ind2 += size(); for(int j = ind1; j <= ind2; ++j) { if(canSee(i, j)) { score = 1 / (sqdist(at(i), at(j)) + 1); if(reflex(j)) { if(rightOn(at(j - 1), at(j), at(i)) && leftOn(at(j + 1), at(j), at(i))) { score += 3; } else { score += 2; } } else { score += 1; } if(score > highestScore) { bestIndex = j; highestScore = score; } } } poly1 = copy(i, bestIndex); poly2 = copy(bestIndex, i); } list += poly1.convexPartition(); list += poly2.convexPartition(); return list; } } // polygon is already convex if(size() > b2_maxPolygonVertices) { poly1 = copy(0, size() / 2); poly2 = copy(size() / 2, 0); list += poly1.convexPartition(); list += poly2.convexPartition(); } else list.append(*this); return list; }
int main(int argc, char *argv[]) try { WSAHandler wsaHandler; QApplication application{argc, argv}; application.setApplicationName("Kadu"); application.setQuitOnLastWindowClosed(false); auto executionArgumentsParser = ExecutionArgumentsParser{}; // do not parse program name auto executionArguments = executionArgumentsParser.parse(QCoreApplication::arguments().mid(1)); if (executionArguments.queryVersion()) { printVersion(); return 0; } if (executionArguments.queryUsage()) { printUsage(); return 0; } if (!executionArguments.debugMask().isEmpty()) { bool ok; executionArguments.debugMask().toInt(&ok); if (ok) qputenv("DEBUG_MASK", executionArguments.debugMask().toUtf8()); else fprintf(stderr, "Ignoring invalid debug mask '%s'\n", executionArguments.debugMask().toUtf8().constData()); } qRegisterMetaType<Message>(); auto profileDirectory = executionArguments.profileDirectory().isEmpty() ? QString::fromUtf8(qgetenv("CONFIG_DIR")) : executionArguments.profileDirectory(); auto modules = std::vector<std::unique_ptr<injeqt::module>> {}; modules.emplace_back(std::make_unique<AccountModule>()); modules.emplace_back(std::make_unique<ActionsModule>()); modules.emplace_back(std::make_unique<AvatarModule>()); modules.emplace_back(std::make_unique<BuddyModule>()); modules.emplace_back(std::make_unique<ChatModule>()); modules.emplace_back(std::make_unique<ChatStyleModule>()); modules.emplace_back(std::make_unique<ChatWidgetModule>()); modules.emplace_back(std::make_unique<ChatWindowModule>()); modules.emplace_back(std::make_unique<CoreModule>(std::move(profileDirectory))); modules.emplace_back(std::make_unique<ConfigurationModule>()); modules.emplace_back(std::make_unique<ContactModule>()); modules.emplace_back(std::make_unique<DomModule>()); modules.emplace_back(std::make_unique<FileTransferModule>()); modules.emplace_back(std::make_unique<FormattedStringModule>()); modules.emplace_back(std::make_unique<GuiModule>()); modules.emplace_back(std::make_unique<IconsModule>()); modules.emplace_back(std::make_unique<IdentityModule>()); modules.emplace_back(std::make_unique<MessageModule>()); modules.emplace_back(std::make_unique<MultilogonModule>()); modules.emplace_back(std::make_unique<NetworkModule>()); modules.emplace_back(std::make_unique<NotificationModule>()); modules.emplace_back(std::make_unique<OsModule>()); modules.emplace_back(std::make_unique<ParserModule>()); modules.emplace_back(std::make_unique<PluginModule>()); modules.emplace_back(std::make_unique<RosterModule>()); modules.emplace_back(std::make_unique<SslModule>()); modules.emplace_back(std::make_unique<StatusModule>()); modules.emplace_back(std::make_unique<TalkableModule>()); modules.emplace_back(std::make_unique<ThemesModule>()); auto injector = injeqt::injector{std::move(modules)}; try { injector.instantiate<Application>(); // force creation of Application object #ifndef Q_OS_WIN // Qt version is better on win32 qInstallMsgHandler(kaduQtMessageHandler); #endif #ifdef DEBUG_OUTPUT_ENABLED showTimesInDebug = (0 != qgetenv("SHOW_TIMES").toInt()); #endif Core core{std::move(injector)}; return core.executeSingle(executionArguments); } catch (ConfigurationUnusableException &) { auto profilePath = injector.get<ConfigurationPathProvider>()->configurationDirectoryPath(); auto errorMessage = QCoreApplication::translate("@default", "We're sorry, but Kadu cannot be loaded. " "Profile is inaccessible. Please check permissions in the '%1' directory.") .arg(profilePath.left(profilePath.length() - 1)); QMessageBox::critical(0, QCoreApplication::translate("@default", "Profile Inaccessible"), errorMessage, QMessageBox::Abort); throw; } } #if defined(Q_OS_WIN) catch (WSAException &) { return 2; } #endif catch (ConfigurationUnusableException &) { // already handled } catch (...) { throw; }
bool Polygon::left(int i) const { return left(at(i - 1), at(i), at(i + 1)); }
/* Test the method 'distance'*/ TEST_F(PositionVectorTest, test_method_distance) { { PositionVector vec1; vec1.push_back(Position(1,0)); vec1.push_back(Position(10,0)); vec1.push_back(Position(10,5)); vec1.push_back(Position(20,5)); Position on(4,0); Position left(4,1); Position right(4,-1); Position left2(4,2); Position right2(4,-2); Position cornerRight(13,-4); Position cornerLeft(7,9); Position before(-3,-3); Position beyond(24,8); EXPECT_EQ(0, vec1.distance(on)); EXPECT_EQ(1, vec1.distance(left)); EXPECT_EQ(1, vec1.distance(right)); EXPECT_EQ(2, vec1.distance(left2)); EXPECT_EQ(2, vec1.distance(right2)); EXPECT_EQ(5, vec1.distance(cornerRight)); EXPECT_EQ(5, vec1.distance(cornerLeft)); EXPECT_EQ(GeomHelper::INVALID_OFFSET, vec1.distance(before, true)); EXPECT_EQ(GeomHelper::INVALID_OFFSET, vec1.distance(beyond, true)); EXPECT_EQ(5, vec1.distance(before)); EXPECT_EQ(5, vec1.distance(beyond)); } { PositionVector vec1; // the same tests as before, mirrored on x-axis vec1.push_back(Position(1,0)); vec1.push_back(Position(10,0)); vec1.push_back(Position(10,-5)); vec1.push_back(Position(20,-5)); Position on(4,0); Position left(4,-1); Position right(4,1); Position left2(4,-2); Position right2(4,2); Position cornerRight(13,4); Position cornerLeft(7,-9); Position before(-3,3); Position beyond(24,-8); EXPECT_EQ(0, vec1.distance(on)); EXPECT_EQ(1, vec1.distance(left)); EXPECT_EQ(1, vec1.distance(right)); EXPECT_EQ(2, vec1.distance(left2)); EXPECT_EQ(2, vec1.distance(right2)); EXPECT_EQ(5, vec1.distance(cornerRight)); EXPECT_EQ(5, vec1.distance(cornerLeft)); EXPECT_EQ(GeomHelper::INVALID_OFFSET, vec1.distance(before, true)); EXPECT_EQ(GeomHelper::INVALID_OFFSET, vec1.distance(beyond, true)); EXPECT_EQ(5, vec1.distance(before)); EXPECT_EQ(5, vec1.distance(beyond)); } }
bool PlayerInputStruct::pollEvents(PlayerInputStruct &oldInputs, GameEvent &e) { //Check if the given event is already a game input event. if(e.type() != GameEvent::GameInput) { e = event::GameInput(); } if(oldInputs.action() != action()) { e.gameInput.setControl(GameControl::ACTION); e.gameInput.setState(action()); oldInputs.setAction(action()); return true; } if(oldInputs.up() != up()) { e.gameInput.setControl(GameControl::UP); e.gameInput.setValue(up()); oldInputs.setUp(up()); return true; } if(oldInputs.down() != down()) { e.gameInput.setControl(GameControl::DOWN); e.gameInput.setValue(down()); oldInputs.setDown(down()); return true; } if(oldInputs.left() != left()) { e.gameInput.setControl(GameControl::LEFT); e.gameInput.setValue(left()); oldInputs.setLeft(left()); return true; } if(oldInputs.right() != right()) { e.gameInput.setControl(GameControl::RIGHT); e.gameInput.setValue(right()); oldInputs.setRight(right()); return true; } if(oldInputs.button1() != button1()) { e.gameInput.setControl(GameControl::BUTTON1); e.gameInput.setState(button1()); oldInputs.setButton1(button1()); return true; } if(oldInputs.button2() != button2()) { e.gameInput.setControl(GameControl::BUTTON2); e.gameInput.setState(button2()); oldInputs.setButton2(button2()); return true; } if(oldInputs.button3() != button3()) { e.gameInput.setControl(GameControl::BUTTON3); e.gameInput.setState(button3()); oldInputs.setButton3(button3()); return true; } if(oldInputs.button4() != button4()) { e.gameInput.setControl(GameControl::BUTTON4); e.gameInput.setState(button4()); oldInputs.setButton4(button4()); return true; } if(oldInputs.button5() != button5()) { e.gameInput.setControl(GameControl::BUTTON5); e.gameInput.setState(button5()); oldInputs.setButton5(button5()); return true; } if(oldInputs.button6() != button6()) { e.gameInput.setControl(GameControl::BUTTON6); e.gameInput.setState(button6()); oldInputs.setButton6(button6()); return true; } return false; }
DEM read_dem () { int c; DEM f, a, b, d, x; int i; char buf[200]; DEM s; DEM d1; int flags1; DEM used1; extern DEM used; loop: do c = readchar (); while (c==' ' || c=='\t' || c=='\n' || c==0); switch (c) { case 'I': return I; case 'K': return K; case 'S': return S; case 'E': return E; case 'F': return If; case 'O': return Ord; case '-': f = read_dem (); a = read_dem (); return ap (f, a); case '/': a = read_dem (); b = read_dem (); return transym (a, b); case 'T': a = read_dem (); b = read_dem (); return trans (a, b); case 'X': a = read_dem (); return sym (a); case '#': a = read_dem (); b = read_dem (); return Axm (a, b); case 'i': a = read_dem (); return defI (a); case 'k': a = read_dem (); b = read_dem (); return defK (a, b); case 's': a = read_dem (); b = read_dem (); d = read_dem (); return defS (a, b, d); case ')': a = read_dem (); b = read_dem (); return IfNode (a, b); case '1': return Ext1; case '2': return Ext2; case '3': return Ext3; case '4': return Ext4; case '5': return Ext5; case '6': return Ext6; case 'e': return AE; case 'f': return EA0; /* a = read_dem (); return EA (a); */ case 'm': return MP; case 'a': return AI; case 'b': return AK; case 'c': return AS; case 'r': return RPA; case '0': return ZeroIsOrd; case '+': return SucIsOrd; case 'w': return LimIsOrd; case 'p': return PredIsOrd; case 'n': return StepIsOrd; case 'W': return TfI; case '<': a = read_dem (); return left (a); case '>': a = read_dem (); return right (a); case '\'': a = read_dem (); return rep(a); case '%': /*printf ("*1*");*/ a = read_dem (); /*printf ("*2*");*/ trace_dem ("read", a); /*printf ("*3*");*/ b = red (a); /*printf ("*4*");*/ trace_dem ("red", b); return b; /* return red (a); */ case 'R': a = read_dem (); return red1 (a, 0); case '@': a = read_dem (); return reduc (a, 1); case '~': a = read_dem (); return reduc (a, 0); case '$': a = read_dem (); return redu (a); case 'x': a = read_dem (); b = read_dem (); return ext (a, b); case '\\': a = read_dem (); b = read_dem (); trace_dem ("^(0)", a); trace_dem ("^(1)", b); d = exten (a, b); trace_dem ("^(r)", d); return d; case ']': a = read_dem (); b = read_dem (); d = dbextens (a, b); return d; case 'l': a = read_dem (); b = read_dem (); return Ext (a, b); /* return Lambda (a, b); */ case 'L': a = read_dem (); b = read_dem (); return Lambda (a, b); case '.': a = read_dem (); return DBLambda (a); case '!': a = read_dem (); b = read_dem (); return DB_lambda (a, b); /* return DBLambda (DBname (0, a, b)); */ case '?': a = read_dem (); b = read_dem (); return DB_Subst (a, b); case '_': a = read_dem (); b = read_dem (); d = read_dem (); return Subst (a, b, d); case ':': a = read_dem (); b = read_dem (); d = read_dem (); return ap (exten(a,d) ,b); case 'V': x = read_dem (); d = read_dem (); a = mk_dem (node(d), 0, NULL, DB_lambda (x, subdem(0,d)), DB_lambda (x, subdem(1,d)), subdem(2,d) == NULL ? NULL : DB_lambda (x, subdem(2,d)), NULL, NULL, NULL); return a; case 'A': x = read_dem (); d = read_dem (); a = mk_dem (node(d), 0, NULL, ap (x, subdem(0,d)), ap (x, subdem(1,d)), subdem(2,d) == NULL ? NULL : ap (x, subdem(2,d)), NULL, NULL, NULL); return a; case '"': a = read_dem (); /* return NoRed (a); */ no_red[nnr++] = a; return a; case '|': a = read_dem (); no_red[nnr++] = a; b = read_dem (); return b; case 'u': used1 = used; used = read_dem (); a = read_dem (); used = used1; return a; case '(': flags1 = flags; i = 0; for (;;) { c = readchar (); if (c == ')') break; buf[i++] = c; } buf[i] = 0; sscanf (buf, "%x", &flags); a = read_dem (); if ((flags & FLAG_PERM) == 0) flags = flags1; return a; case ',': a = read_dem (); return step (a); case '*': a = read_dem (); return rstep (a); case '`': a = read_dem (); return list_ap (a, nil); case '&': c = readchar (); switch (c) { case '/': return itransym; case 'i': return idefI; case 'k': return idefK; case 's': return idefS; case '<': return ileft; case '>': return iright; case '=': return ieq; case '#': return inode; case '0': return isubdem0; case '1': return isubdem1; case '2': return isubdem2; case '%': return ired; case '$': return iredu; case '\\': return iext; case ',': return istep; case '*': return irstep; default: fprintf (stderr, "Undefined &%c.\n", c); return I; } break; case '[': /* trace_dem ("read symbol", I); */ for (i=0; i<sizeof(buf); i++) { c = readchar(); if (c == ']') { buf[i] = 0; #ifdef TRACE1 printf ("buf=<%s>\n", buf); #endif if (buf[0] >= '0' && buf[0] <= '9') { #ifdef TRACE printf ("\nDBVar <%s>", buf); #endif d1 = DBVar (atoi(buf)); trace_dem ("", d); return d1; } s = Sym(buf); #ifdef TRACE1 trace_dem ("read symbol", s); #endif if (subdem(0,s) == NULL) { #ifdef TRACE1 trace_dem ("return symbol", s); #endif return s; } else { #ifdef TRACE trace_dem ("return value of", s); #endif return subdem(0,s); } } buf[i] = c; } fprintf (stderr, "Symbol too long\n"); return Sym(buf); default: return defined_dems[(unsigned char)c]; /* printf ("Illegal character 0x%02X\n", c); goto loop; */ } }
bool ZLTextView::PositionIndicator::isResponsibleFor(int x, int y) { x = myTextView.textArea().realX(x); return x >= left() && x <= right() && y >= top() && y <= bottom(); }