Example #1
0
void drawPong(const uint8_t paddle1_y, const uint8_t paddle2_y, const uint8_t ball_x, const uint8_t ball_y) {
	// paddles are 3 pixels high
	uint8_t row, col;
#if ROW == 0
	for (uint8_t i = 0; i < 8; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTB = 0x01 << i;
		PORTA = getPongLine(row, col, paddle1_y, paddle2_y, ball_x, ball_y);
		_delay_ms(0.1);
		PORTB = 0;
		PORTA = 0xff;
		_delay_ms(0.1);
	}
	for (uint8_t i = 8; i < 16; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTD = 0x01 << (i - 8);
		PORTA = getPongLine(row, col, paddle1_y, paddle2_y, ball_x, ball_y);
		_delay_ms(0.1);
		PORTD = 0;
		PORTA = 0xff;
		_delay_ms(0.1);
	}
#else
	// bottom
	for (uint8_t i = 0; i < 8; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTD = 0x01 << (7 - i);
		PORTA = reversed(getPongLine(row, col, paddle1_y, paddle2_y, ball_x, ball_y));
		_delay_ms(0.1);
		PORTD = 0;
		PORTA = 0xff;
		_delay_ms(0.1);
	}
	for (uint8_t i = 8; i < 16; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTB = 0x01 << (15 - i);
		PORTA = reversed(getPongLine(row, col, paddle1_y, paddle2_y, ball_x, ball_y));
		_delay_ms(0.1);
		PORTB = 0;
		PORTA = 0xff;
		_delay_ms(0.1);
	}
#endif				
}
Example #2
0
size_t DirectedGraph<T, MASK>::scc(std::vector<size_t>* vertex_color) const {
	const DirectedGraph<T, MASK> rev_graph = reversed();
	std::vector<size_t> order(this->vertices_count_);
	top_sort_rec(&order);
	std::vector<bool> used(this->vertices_count_, false);
	std::vector<size_t> color(this->vertices_count_);
	Queue<size_t> queue(this->vertices_count_);
	size_t components_count = 0;
	for (const auto& v : order) {
		if (!used[v]) {
			queue.clear();
			queue.push(v);
			while (!queue.empty()) {
				const size_t vertex = queue.pop_front();
				color[vertex] = components_count;
				used[vertex] = true;
				for (const auto& it : rev_graph.edges(vertex)) {
					const size_t to = it.to();
					if (!used[to]) {
						used[to] = true;
						queue.push(to);
					}
				}
			}
			++components_count;
		}
	}
	if (vertex_color != nullptr) {
		vertex_color->swap(color);
	}
	return components_count;
}
Example #3
0
        void build_suffix_table ( patIter first, patIter last ) {
            const std::size_t count = (std::size_t) std::distance ( first, last );

            if ( count > 0 ) {  // empty pattern
                std::vector<typename std::iterator_traits<patIter>::value_type> reversed(count);
                (void) std::reverse_copy ( first, last, reversed.begin ());

                std::vector<difference_type> prefix (count);
                compute_bm_prefix ( first, last, prefix );

                std::vector<difference_type> prefix_reversed (count);
                compute_bm_prefix ( reversed.begin (), reversed.end (), prefix_reversed );

                for ( std::size_t i = 0; i <= count; i++ )
                    suffix_[i] = count - prefix [count-1];

                for ( std::size_t i = 0; i < count; i++ ) {
                    const std::size_t     j = count - prefix_reversed[i];
                    const difference_type k = i -     prefix_reversed[i] + 1;

                    if (suffix_[j] > k)
                        suffix_[j] = k;
                    }
                }
            }
Example #4
0
/* Actually changes the LEDs on the board to reflect the displayables in the display list. */
void draw(void) {
	uint32_t row, col;
#if ROW == 0
	for (uint8_t i = 0; i < 8; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTB = 0x01 << i;
		PORTA = getCombinedLine(row, col);
		_delay_ms(0.1);
		PORTB = 0;
		//PORTA = 0xff;
		_delay_ms(0.1);
	}
	for (uint8_t i = 8; i < 16; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTD = 0x01 << (i - 8);
		PORTA = getCombinedLine(row, col);
		_delay_ms(0.1);
		PORTD = 0;
		//PORTA = 0xff;
		_delay_ms(0.1);
	}
#else
	// bottom
	for (uint8_t i = 0; i < 8; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTD = 0x01 << (7 - i);
		PORTA = reversed(getCombinedLine(row, col));
		_delay_ms(0.1);
		PORTD = 0;
		//PORTA = 0xff;
		_delay_ms(0.1);
	}
	for (uint8_t i = 8; i < 16; i++) {
		row = ROWOFFSET + i;
		col = COLOFFSET;
		PORTB = 0x01 << (15 - i);
		PORTA = reversed(getCombinedLine(row, col));
		_delay_ms(0.1);
		PORTB = 0;
		//PORTA = 0xff;
		_delay_ms(0.1);
	}
#endif				
}
Example #5
0
static void cmd_room_typing2 (char *room)
{
  int r;
  SLOT_LIST *sl;
  SLOT *sp;
  int nobody = 1;

  if (room[0]) {
    r = atoi (room);
    if (r < 1 || r > 99) {
      writestr (cur_slot, "Incorrect room number.\n");
      setproc (sendpub, MAXMSG, 0);
      return;
    }
  } else
    r = cur_slot->acct.chan;

  if (r != cur_slot->acct.chan &&
      !channels[r].name &&
      cur_slot->acct.level != TOPLEVEL) {
    writestr (cur_slot, "Sorry, you cannot look into that room.\n");
    setproc (sendpub, MAXMSG, 0);
    return;
  }

  for (sl = channels[r].members; sl; sl = sl->next) {
    sp = sl->slot;
    if (sp == cur_slot || !sp->flags.stopped)
      continue;
    if ((squelched (cur_slot, sp) || reversed (sp, cur_slot)) &&
        cur_slot->acct.level != TOPLEVEL)
      continue;
    if (nobody) {
      if (channels[r].name)
        sprintf (msg_buf,
                 "Users currently typing in room %02d (%s):\n",
                 r, channels[r].name);
      else
        sprintf (msg_buf,
                 "Users currently typing in room %02d (unnamed):\n", r);
      writestr (cur_slot, msg_buf);
      nobody = 0;
    }
    print_typing (sp);
  }

  if (nobody) {
    if (channels[r].name)
      sprintf (msg_buf, "Nobody is typing in room %02d (%s).\n",
               r, channels[r].name);
    else
      sprintf (msg_buf, "Nobody is typing in room %02d (unnamed).\n", r);
    writestr (cur_slot, msg_buf);
  }

  setproc (sendpub, MAXMSG, 0);
}
Example #6
0
    ActionPtr Sequence::Reversed() const
    {
        SequencePtr reversed(new Sequence());

        std::for_each(m_actions.rbegin(), m_actions.rend(), [&reversed](FiniteActionPtr action) {
            reversed->Actions().push_back(std::dynamic_pointer_cast<FiniteAction>(action->Reversed()));
        });

        return reversed;
    }
Example #7
0
Stream<int> test3()
{
    auto s4 = test1();
    auto rv = s4.reversed();
    std::cout << "reversedd\n";
    lazyPrint(rv);
    forcePrint(rv);
    auto cat = concat(s4, rv);
    return cat;
}
Example #8
0
void favoritesTab::updateFavorites()
{
	QStringList assoc = QStringList() << "name" << "note" << "lastviewed";
	QString order = assoc[ui->comboOrder->currentIndex()];
	bool reverse = (ui->comboAsc->currentIndex() == 1);

	if (order == "note")
	{ qSort(m_favorites.begin(), m_favorites.end(), sortByNote); }
	else if (order == "lastviewed")
	{ qSort(m_favorites.begin(), m_favorites.end(), sortByLastviewed); }
	else
	{ qSort(m_favorites.begin(), m_favorites.end(), sortByName); }
	if (reverse)
	{ m_favorites = reversed(m_favorites); }

	QString format = tr("MM/dd/yyyy");
	clearLayout(ui->layoutFavorites);

	QString display = m_settings->value("favorites_display", "ind").toString();
	int i = 0;
	for (Favorite fav : m_favorites)
	{
		QString xt = tr("<b>Name:</b> %1<br/><b>Note:</b> %2 %%<br/><b>Last view:</b> %3").arg(fav.getName(), QString::number(fav.getNote()), fav.getLastViewed().toString(format));
		QWidget *w = new QWidget(ui->scrollAreaWidgetContents);
		QVBoxLayout *l = new QVBoxLayout(w);

		if (display.contains("i"))
		{
			QPixmap img = fav.getImage();
			QBouton *image = new QBouton(fav.getName(), false, false, 0, QColor(), this);
				image->setIcon(img);
				image->setIconSize(img.size());
				image->setFlat(true);
				image->setToolTip(xt);
				connect(image, SIGNAL(rightClick(QString)), this, SLOT(favoriteProperties(QString)));
				connect(image, SIGNAL(middleClick(QString)), this, SLOT(addTabFavorite(QString)));
				connect(image, SIGNAL(appui(QString)), this, SLOT(loadFavorite(QString)));
			l->addWidget(image);
		}

		QAffiche *caption = new QAffiche(fav.getName(), 0 ,QColor(), this);
			caption->setText((display.contains("n") ? fav.getName() : "") + (display.contains("d") ? "<br/>("+QString::number(fav.getNote())+" % - "+fav.getLastViewed().toString(format)+")" : ""));
			caption->setTextFormat(Qt::RichText);
			caption->setAlignment(Qt::AlignCenter);
			caption->setToolTip(xt);
		if (!caption->text().isEmpty())
		{
			connect(caption, SIGNAL(clicked(QString)), this, SLOT(loadFavorite(QString)));
			l->addWidget(caption);
		}

		ui->layoutFavorites->addWidget(w, i / 8, i % 8);
		++i;
	}
}
Example #9
0
void LongestPathRanking::call(const Graph &G, const EdgeArray<int> &length, NodeArray<int> &rank)
{
	List<edge> R;

	m_subgraph.get().call(G,R);

	EdgeArray<bool> reversed(G,false);
	for (ListConstIterator<edge> it = R.begin(); it.valid(); ++it)
		reversed[*it] = true;
	R.clear();

	doCall(G, rank, reversed, length);
}
Example #10
0
DiGraph DiGraph::getReversed() const
{
	DiGraph reversed(this->getVertexCount());
	for (std::vector<EdgesList>::const_iterator i = vertecies.begin(); i != vertecies.end(); ++i)
	{
		int index = i - vertecies.begin();
		for (auto j = i->begin(); j != i->end(); ++j)
		{
			reversed.addEdge(*j, index);
		}
	}
	return reversed;
}
Example #11
0
static bool referenceRestack(const T &subset,
                     Window **childrenp=NULL, unsigned *nchildrenp=NULL)
{
    int n = subset.count();
    WindowVec reversed(n);
    for (int i = 0; i < n; i++)
        reversed[n-1-i] = subset[i];

    Q_ASSERT(Dpy != NULL);
    if (!XRestackWindows(Dpy,
                        (Window*)reversed.constData(), reversed.count()))
        qFatal("XRestackWindows() failed");
    return verifyTree(subset, childrenp, nchildrenp);
}
Example #12
0
static void cmd_beep2 (SLOT *dst_slot, char *id)
{
  char beep_code[] = "\a";

  if (!squelched (dst_slot, cur_slot) && !reversed (cur_slot, dst_slot)) {
    sprintf (msg_buf, " * You are being *beeped* by %s/%s",
             cur_slot->acct.id, cur_slot->acct.handle);
    if (dst_slot->acct.beeping) {
      writestr (dst_slot, beep_code);
    } else
      strcat (msg_buf, "\n * BEEEEEEEEEEEEEEEEP!!!");
    writeaction (dst_slot, msg_buf);
  }
  writestr (cur_slot, "Beep sent.\n");
  setproc (sendpub, MAXMSG, 0);
}
Example #13
0
const std::string Reverse(const std::string &encoded)
{
	std::string reversed("");
	reversed.reserve(encoded.size());

	if(encoded.size()%2==0 && encoded.size()>0)
	{
		for(std::string::size_type i=0; i<=(encoded.size()-2); i+=2)
		{
			reversed+=encoded.substr(encoded.size()-i,2);
		}
	}

	return reversed;

}
Example #14
0
void OptimalRanking::call(
	const Graph &G,
	const EdgeArray<int> &length,
	const EdgeArray<int> &cost,
	NodeArray<int> &rank)
{
	List<edge> R;

	m_subgraph.get().call(G,R);

	EdgeArray<bool> reversed(G,false);
	for (edge e : R)
		reversed[e] = true;
	R.clear();

	doCall(G, rank, reversed, length, cost);
}
Example #15
0
int main(void)
{
	scanf("%u", &tests);
	for(unsigned int t = 0; t < tests; ++ t)
	{
		scanf("%u", &number);
		steps = 0;
		while(!isPalindrome(number))
		{
			number += reversed(number);
			++ steps;
		}

		printf("%u %u\n", number, steps);
	}

	return 0;
}
Example #16
0
//Returns new vector, with elements ordered from largest to smallest
int64_t* descending(int64_t* vector) 
{
	int64_t* result = cloned(vector);

	if (g_vec_properties[arg1][0] == DOWN || g_vec_properties[arg1][0] == UNIFORM || g_vec_properties[arg1][0] == SEQDOWN)
	{
		return result;
	}
	else if (g_vec_properties[arg1][0] == UP || g_vec_properties[arg1][0] == SEQUP ||
			g_vec_properties[arg1][0] == PRIME)
	{
		free(result);
		return reversed(vector);
	}

	qsort(result, g_length, sizeof(int64_t), int64Descend);
	return result;
}
Example #17
0
static SearchQuery* createRevComplQuery(SearchQuery* query, DNATranslation* transl) {
    SAFE_POINT(query != NULL, "Query is null", NULL);
    SAFE_POINT(transl != NULL, "Transl is null", NULL);

    QByteArray reversed(query->constSequence());
    TextUtils::reverse(reversed.data(), reversed.count());

    DNASequence dnaSeq(QString("%1_rev").arg(query->getName()), reversed, NULL);
    SearchQuery *rQu = new SearchQuery(&dnaSeq, query);
    transl->translate(const_cast<char*>(rQu->constData()), rQu->length());

    if (rQu->constSequence() == query->constSequence()) {
        delete rQu; rQu = NULL;
        return NULL;
    }

    query->setRevCompl(rQu);
    return rQu;
}
Example #18
0
int main()
{
    std::vector<int> data{};

    // read integers into vector
    std::copy(std::istream_iterator<int>(std::cin),
            std::istream_iterator<int>(),
            std::back_inserter(data));

    std::vector<int> reversed(data.size());

    std::vector<int>::iterator it{reversed.end()};
    for (int i : data) {
        --it;
        *it = i;
    }

    std::copy(reversed.begin(), reversed.end(),
            std::ostream_iterator<int>(std::cout));

}
Example #19
0
void cmd_typing (void)
{
  SLOT *sp;
  int i;
  int nobody = 1;

  for (i = 0; i <= slots_used; i++) {
    sp = slotbase[i];
    if (!sp || sp == cur_slot || !sp->flags.on || !sp->flags.stopped)
      continue;
    if ((squelched (cur_slot, sp) || reversed (sp, cur_slot)) &&
        cur_slot->acct.level != TOPLEVEL)
      continue;
    if (nobody) {
      writestr (cur_slot, "Users currently typing:\n");
      nobody = 0;
    }
    print_typing (sp);
  }
  if (nobody)
    writestr (cur_slot, "Nobody is currently typing.\n");
}
Example #20
0
void OptimalRanking::call (const Graph& G, NodeArray<int> &rank)
{
	List<edge> R;

	m_subgraph.get().call(G,R);

	EdgeArray<bool> reversed(G,false);
	for (edge e : R)
		reversed[e] = true;
	R.clear();

	EdgeArray<int> length(G,1);

	if(m_separateMultiEdges) {
		SListPure<edge> edges;
		EdgeArray<int> minIndex(G), maxIndex(G);
		parallelFreeSortUndirected(G, edges, minIndex, maxIndex);

		SListConstIterator<edge> it = edges.begin();
		if(it.valid())
		{
			int prevSrc = minIndex[*it];
			int prevTgt = maxIndex[*it];

			for(it = it.succ(); it.valid(); ++it) {
				edge e = *it;
				if (minIndex[e] == prevSrc && maxIndex[e] == prevTgt)
					length[e] = 2;
				else {
					prevSrc = minIndex[e];
					prevTgt = maxIndex[e];
				}
			}
		}
	}

	EdgeArray<int> cost(G,1);
	doCall(G, rank, reversed, length, cost);
}
Example #21
0
/* reverses through the y-axis (just the x coordinates */
static Area reverseBox(const Area & area){
    Area reversed(area);
    reversed.x1 = -reversed.x1;
    reversed.x2 = -reversed.x2;
    return reversed;
}
int GraphicsZone::myself() const
{
    return reversed() ? 1 : 0;
}
Example #23
0
Json::Value doSubscribe (RPC::Context& context)
{
    InfoSub::pointer ispSub;
    Json::Value jvResult (Json::objectValue);

    if (!context.infoSub && !context.params.isMember (jss::url))
    {
        // Must be a JSON-RPC call.
        WriteLog (lsINFO, RPCHandler)
            << "doSubscribe: RPC subscribe requires a url";

        return rpcError (rpcINVALID_PARAMS);
    }

    if (context.params.isMember (jss::url))
    {
        if (context.role != Role::ADMIN)
            return rpcError (rpcNO_PERMISSION);

        std::string strUrl      = context.params[jss::url].asString ();
        std::string strUsername = context.params.isMember (jss::url_username) ?
                context.params[jss::url_username].asString () : "";
        std::string strPassword = context.params.isMember (jss::url_password) ?
                context.params[jss::url_password].asString () : "";

        // DEPRECATED
        if (context.params.isMember (jss::username))
            strUsername = context.params[jss::username].asString ();

        // DEPRECATED
        if (context.params.isMember (jss::password))
            strPassword = context.params[jss::password].asString ();

        ispSub  = context.netOps.findRpcSub (strUrl);

        if (!ispSub)
        {
            WriteLog (lsDEBUG, RPCHandler)
                << "doSubscribe: building: " << strUrl;

            RPCSub::pointer rspSub = RPCSub::New (getApp ().getOPs (),
                getApp ().getIOService (), getApp ().getJobQueue (),
                    strUrl, strUsername, strPassword);
            ispSub  = context.netOps.addRpcSub (
                strUrl, std::dynamic_pointer_cast<InfoSub> (rspSub));
        }
        else
        {
            WriteLog (lsTRACE, RPCHandler)
                << "doSubscribe: reusing: " << strUrl;

            if (context.params.isMember (jss::username))
                dynamic_cast<RPCSub*> (&*ispSub)->setUsername (strUsername);

            if (context.params.isMember (jss::password))
                dynamic_cast<RPCSub*> (&*ispSub)->setPassword (strPassword);
        }
    }
    else
    {
        ispSub  = context.infoSub;
    }

    if (!context.params.isMember (jss::streams))
    {
    }
    else if (!context.params[jss::streams].isArray ())
    {
        WriteLog (lsINFO, RPCHandler)
            << "doSubscribe: streams requires an array.";

        return rpcError (rpcINVALID_PARAMS);
    }
    else
    {
        for (auto& it: context.params[jss::streams])
        {
            if (it.isString ())
            {
                std::string streamName = it.asString ();

                if (streamName == "server")
                {
                    context.netOps.subServer (ispSub, jvResult,
                        context.role == Role::ADMIN);
                }
                else if (streamName == "ledger")
                {
                    context.netOps.subLedger (ispSub, jvResult);
                }
                else if (streamName == "transactions")
                {
                    context.netOps.subTransactions (ispSub);
                }
                else if (streamName == "transactions_proposed"
                         || streamName == "rt_transactions") // DEPRECATED
                {
                    context.netOps.subRTTransactions (ispSub);
                }
                else
                {
                    jvResult[jss::error]   = "unknownStream";
                }
            }
            else
            {
                jvResult[jss::error]   = "malformedStream";
            }
        }
    }

    auto strAccountsProposed =
               context.params.isMember (jss::accounts_proposed)
               ? jss::accounts_proposed : jss::rt_accounts;  // DEPRECATED

    if (!context.params.isMember (strAccountsProposed))
    {
    }
    else if (!context.params[strAccountsProposed].isArray ())
    {
        return rpcError (rpcINVALID_PARAMS);
    }
    else
    {
        auto ids  = RPC::parseAccountIds (context.params[strAccountsProposed]);

        if (ids.empty ())
            jvResult[jss::error] = "malformedAccount";
        else
            context.netOps.subAccount (ispSub, ids, true);
    }

    if (!context.params.isMember (jss::accounts))
    {
    }
    else if (!context.params[jss::accounts].isArray ())
    {
        return rpcError (rpcINVALID_PARAMS);
    }
    else
    {
        auto ids  = RPC::parseAccountIds (context.params[jss::accounts]);

        if (ids.empty ())
        {
            jvResult[jss::error]   = "malformedAccount";
        }
        else
        {
            context.netOps.subAccount (ispSub, ids, false);
            WriteLog (lsDEBUG, RPCHandler)
                << "doSubscribe: accounts: " << ids.size ();
        }
    }

    if (!context.params.isMember (jss::books))
    {
    }
    else if (!context.params[jss::books].isArray ())
    {
        return rpcError (rpcINVALID_PARAMS);
    }
    else
    {
        for (auto& j: context.params[jss::books])
        {
            if (!j.isObject ()
                    || !j.isMember (jss::taker_pays)
                    || !j.isMember (jss::taker_gets)
                    || !j[jss::taker_pays].isObject ()
                    || !j[jss::taker_gets].isObject ())
                return rpcError (rpcINVALID_PARAMS);

            Book book;
            bool bBoth =
                    (j.isMember (jss::both) && j[jss::both].asBool ()) ||
                    (j.isMember (jss::both_sides) && j[jss::both_sides].asBool ());
            bool bSnapshot =
                    (j.isMember (jss::snapshot) && j[jss::snapshot].asBool ()) ||
                    (j.isMember (jss::state_now) && j[jss::state_now].asBool ());
            // TODO(tom): both_sides and state_now are apparently deprecated...
            // where is this documented?

            Json::Value taker_pays = j[jss::taker_pays];
            Json::Value taker_gets = j[jss::taker_gets];

            // Parse mandatory currency.
            if (!taker_pays.isMember (jss::currency)
                    || !to_currency (book.in.currency,
                                     taker_pays[jss::currency].asString ()))
            {
                WriteLog (lsINFO, RPCHandler) << "Bad taker_pays currency.";

                return rpcError (rpcSRC_CUR_MALFORMED);
            }
            // Parse optional issuer.
            else if (((taker_pays.isMember (jss::issuer))
                      && (!taker_pays[jss::issuer].isString ()
                          || !to_issuer (book.in.account,
                                         taker_pays[jss::issuer].asString ())))
                     // Don't allow illegal issuers.
                     || (!book.in.currency != !book.in.account)
                     || noAccount() == book.in.account)
            {
                WriteLog (lsINFO, RPCHandler) << "Bad taker_pays issuer.";

                return rpcError (rpcSRC_ISR_MALFORMED);
            }

            // Parse mandatory currency.
            if (!taker_gets.isMember (jss::currency)
                    || !to_currency (book.out.currency,
                                     taker_gets[jss::currency].asString ()))
            {
                WriteLog (lsINFO, RPCHandler) << "Bad taker_pays currency.";

                return rpcError (rpcSRC_CUR_MALFORMED);
            }
            // Parse optional issuer.
            else if (((taker_gets.isMember (jss::issuer))
                      && (!taker_gets[jss::issuer].isString ()
                          || !to_issuer (book.out.account,
                                         taker_gets[jss::issuer].asString ())))
                     // Don't allow illegal issuers.
                     || (!book.out.currency != !book.out.account)
                     || noAccount() == book.out.account)
            {
                WriteLog (lsINFO, RPCHandler) << "Bad taker_gets issuer.";

                return rpcError (rpcDST_ISR_MALFORMED);
            }

            if (book.in.currency == book.out.currency
                    && book.in.account == book.out.account)
            {
                WriteLog (lsINFO, RPCHandler)
                    << "taker_gets same as taker_pays.";
                return rpcError (rpcBAD_MARKET);
            }

            RippleAddress   raTakerID;

            if (!j.isMember (jss::taker))
                raTakerID.setAccountID (noAccount());
            else if (!raTakerID.setAccountID (j[jss::taker].asString ()))
                return rpcError (rpcBAD_ISSUER);

            if (!isConsistent (book))
            {
                WriteLog (lsWARNING, RPCHandler) << "Bad market: " << book;
                return rpcError (rpcBAD_MARKET);
            }

            context.netOps.subBook (ispSub, book);

            if (bBoth)
                context.netOps.subBook (ispSub, reversed (book));

            if (bSnapshot)
            {
                context.loadType = Resource::feeMediumBurdenRPC;
                auto lpLedger = getApp().getLedgerMaster ().
                        getPublishedLedger ();
                if (lpLedger)
                {
                    const Json::Value jvMarker = Json::Value (Json::nullValue);
                    Json::Value jvOffers (Json::objectValue);

                    auto add = [&](Json::StaticString field)
                    {
                        context.netOps.getBookPage (context.role == Role::ADMIN,
                            lpLedger, field == jss::asks ? reversed (book) : book,
                            raTakerID.getAccountID(), false, 0, jvMarker,
                            jvOffers);

                        if (jvResult.isMember (field))
                        {
                            Json::Value& results (jvResult[field]);
                            for (auto const& e : jvOffers[jss::offers])
                                results.append (e);
                        }
                        else
                        {
                            jvResult[field] = jvOffers[jss::offers];
                        }
                    };

                    if (bBoth)
                    {
                        add (jss::bids);
                        add (jss::asks);
                    }
                    else
                    {
                        add (jss::offers);
                    }
                }
            }
        }
    }

    return jvResult;
}
int RegularBattleScene::myself() const
{
    return reversed() ? 1 : 0;
}
int GraphicsZone::opponent() const
{
    return reversed() ? 0 : 1;
}
int RegularBattleScene::opponent() const
{
    return reversed() ? 0 : 1;
}
void DfsAcyclicSubgraph::callUML (
	const GraphAttributes &AG,
	List<edge> &arcSet)
{
	const Graph &G = AG.constGraph();

	// identify hierarchies
	NodeArray<int> hierarchy(G,-1);
	int count = 0;
	int treeNum = -1;

	node v;
	forall_nodes(v,G)
	{
		if(hierarchy[v] == -1) {
			int n = dfsFindHierarchies(AG,hierarchy,count,v);
			if(n > 1) treeNum = count;
			++count;
		}
	}

	arcSet.clear();

	// perform DFS on the directed graph formed by generalizations
	NodeArray<int> number(G,0), completion(G);
	int nNumber = 0, nCompletion = 0;

	forall_nodes(v,G) {
		if(number[v] == 0)
			dfsBackedgesHierarchies(AG,v,number,completion,nNumber,nCompletion);
	}

	// collect all backedges within a hierarchy
	// and compute outdeg of each vertex within its hierarchy
	EdgeArray<bool> reversed(G,false);
	NodeArray<int> outdeg(G,0);

	edge e;
	forall_edges(e,G) {
		if(AG.type(e) != Graph::generalization || e->isSelfLoop())
			continue;

		node src = e->source(), tgt = e->target();

		outdeg[src]++;

		if (hierarchy[src] == hierarchy[tgt] &&
			number[src] >= number[tgt] && completion[src] <= completion[tgt])
			reversed[e] = true;
	}

	// topologial numbering of nodes within a hierarchy (for each hierarchy)
	NodeArray<int> numV(G);
	Queue<node> Q;
	int countV = 0;

	forall_nodes(v,G)
		if(outdeg[v] == 0)
			Q.append(v);

	while(!Q.empty()) {
		v = Q.pop();

		numV[v] = countV++;

		forall_adj_edges(e,v) {
			node w = e->source();
			if(w != v) {
				if(--outdeg[w] == 0)
					Q.append(w);
			}
		}
	}
Example #28
0
Json::Value doSubscribe (RPC::Context& context)
{
    InfoSub::pointer ispSub;
    Json::Value jvResult (Json::objectValue);

    if (! context.infoSub && ! context.params.isMember(jss::url))
    {
        // Must be a JSON-RPC call.
        JLOG(context.j.info) << "doSubscribe: RPC subscribe requires a url";
        return rpcError (rpcINVALID_PARAMS);
    }

    if (context.params.isMember(jss::url))
    {
        if (context.role != Role::ADMIN)
            return rpcError(rpcNO_PERMISSION);

        std::string strUrl = context.params[jss::url].asString ();
        std::string strUsername = context.params.isMember (jss::url_username) ?
                context.params[jss::url_username].asString () : "";
        std::string strPassword = context.params.isMember (jss::url_password) ?
                context.params[jss::url_password].asString () : "";

        // DEPRECATED
        if (context.params.isMember (jss::username))
            strUsername = context.params[jss::username].asString ();

        // DEPRECATED
        if (context.params.isMember (jss::password))
            strPassword = context.params[jss::password].asString ();

        ispSub = context.netOps.findRpcSub(strUrl);
        if (! ispSub)
        {
            JLOG (context.j.debug)
                << "doSubscribe: building: " << strUrl;

            auto rspSub = make_RPCSub (context.app.getOPs (),
                context.app.getIOService (), context.app.getJobQueue (),
                    strUrl, strUsername, strPassword, context.app.logs ());
            ispSub  = context.netOps.addRpcSub (
                strUrl, std::dynamic_pointer_cast<InfoSub> (rspSub));
        }
        else
        {
            JLOG (context.j.trace)
                << "doSubscribe: reusing: " << strUrl;

            if (auto rpcSub = std::dynamic_pointer_cast<RPCSub> (ispSub))
            {
                // Why do we need to check isMember against jss::username and
                // jss::password here instead of just setting the username and
                // the password? What about url_username and url_password?
                if (context.params.isMember (jss::username))
                    rpcSub->setUsername (strUsername);

                if (context.params.isMember (jss::password))
                    rpcSub->setPassword (strPassword);
            }
        }
    }
    else
    {
        ispSub  = context.infoSub;
    }

    if (context.params.isMember (jss::streams))
    {
        if (! context.params[jss::streams].isArray ())
        {
            JLOG (context.j.info)
                << "doSubscribe: streams requires an array.";
            return rpcError (rpcINVALID_PARAMS);
        }

        for (auto const& it: context.params[jss::streams])
        {
            if (! it.isString())
                return rpcError(rpcSTREAM_MALFORMED);

            std::string streamName = it.asString ();
            if (streamName == "server")
            {
                context.netOps.subServer (ispSub, jvResult,
                    context.role == Role::ADMIN);
            }
            else if (streamName == "ledger")
            {
                context.netOps.subLedger (ispSub, jvResult);
            }
            else if (streamName == "transactions")
            {
                context.netOps.subTransactions (ispSub);
            }
            else if (streamName == "transactions_proposed" ||
                streamName == "rt_transactions") // DEPRECATED
            {
                context.netOps.subRTTransactions (ispSub);
            }
            else if (streamName == "validations")
            {
                context.netOps.subValidations (ispSub);
            }
            else if (streamName == "peer_status")
            {
                if (context.role != Role::ADMIN)
                    return rpcError(rpcNO_PERMISSION);
                context.netOps.subPeerStatus (ispSub);
            }
            else
            {
                return rpcError(rpcSTREAM_MALFORMED);
            }
        }
    }

    auto accountsProposed = context.params.isMember(jss::accounts_proposed)
        ? jss::accounts_proposed : jss::rt_accounts;  // DEPRECATED
    if (context.params.isMember(accountsProposed))
    {
        if (! context.params[accountsProposed].isArray())
            return rpcError(rpcINVALID_PARAMS);

        auto ids = RPC::parseAccountIds(context.params[accountsProposed]);
        if (ids.empty())
            return rpcError(rpcACT_MALFORMED);
        context.netOps.subAccount(ispSub, ids, true);
    }

    if (context.params.isMember(jss::accounts))
    {
        if (! context.params[jss::accounts].isArray())
            return rpcError(rpcINVALID_PARAMS);

        auto ids = RPC::parseAccountIds(context.params[jss::accounts]);
        if (ids.empty())
            return rpcError(rpcACT_MALFORMED);
        context.netOps.subAccount(ispSub, ids, false);
        JLOG(context.j.debug) << "doSubscribe: accounts: " << ids.size();
    }

    if (context.params.isMember(jss::books))
    {
        if (! context.params[jss::books].isArray())
            return rpcError (rpcINVALID_PARAMS);

        for (auto& j: context.params[jss::books])
        {
            if (!j.isObject ()
                    || !j.isMember (jss::taker_pays)
                    || !j.isMember (jss::taker_gets)
                    || !j[jss::taker_pays].isObject ()
                    || !j[jss::taker_gets].isObject ())
                return rpcError (rpcINVALID_PARAMS);

            Book book;
            bool bBoth =
                    (j.isMember (jss::both) && j[jss::both].asBool ()) ||
                    (j.isMember (jss::both_sides) && j[jss::both_sides].asBool ());
            bool bSnapshot =
                    (j.isMember (jss::snapshot) && j[jss::snapshot].asBool ()) ||
                    (j.isMember (jss::state_now) && j[jss::state_now].asBool ());
            // TODO(tom): both_sides and state_now are apparently deprecated...
            // where is this documented?

            Json::Value taker_pays = j[jss::taker_pays];
            Json::Value taker_gets = j[jss::taker_gets];

            // Parse mandatory currency.
            if (!taker_pays.isMember (jss::currency)
                    || !to_currency (book.in.currency,
                                     taker_pays[jss::currency].asString ()))
            {
                JLOG (context.j.info) << "Bad taker_pays currency.";

                return rpcError (rpcSRC_CUR_MALFORMED);
            }
            // Parse optional issuer.
            else if (((taker_pays.isMember (jss::issuer))
                      && (!taker_pays[jss::issuer].isString ()
                          || !to_issuer (book.in.account,
                                         taker_pays[jss::issuer].asString ())))
                     // Don't allow illegal issuers.
                     || (!book.in.currency != !book.in.account)
                     || noAccount() == book.in.account)
            {
                JLOG (context.j.info) << "Bad taker_pays issuer.";

                return rpcError (rpcSRC_ISR_MALFORMED);
            }

            // Parse mandatory currency.
            if (!taker_gets.isMember (jss::currency)
                    || !to_currency (book.out.currency,
                                     taker_gets[jss::currency].asString ()))
            {
                JLOG (context.j.info) << "Bad taker_pays currency.";

                return rpcError (rpcSRC_CUR_MALFORMED);
            }
            // Parse optional issuer.
            else if (((taker_gets.isMember (jss::issuer))
                      && (!taker_gets[jss::issuer].isString ()
                          || !to_issuer (book.out.account,
                                         taker_gets[jss::issuer].asString ())))
                     // Don't allow illegal issuers.
                     || (!book.out.currency != !book.out.account)
                     || noAccount() == book.out.account)
            {
                JLOG (context.j.info) << "Bad taker_gets issuer.";

                return rpcError (rpcDST_ISR_MALFORMED);
            }

            if (book.in.currency == book.out.currency
                    && book.in.account == book.out.account)
            {
                JLOG (context.j.info)
                    << "taker_gets same as taker_pays.";
                return rpcError (rpcBAD_MARKET);
            }

            boost::optional<AccountID> takerID;

            if (j.isMember (jss::taker))
            {
                takerID = parseBase58<AccountID>(
                    j[jss::taker].asString());
                if (! takerID)
                    return rpcError (rpcBAD_ISSUER);
            }

            if (!isConsistent (book))
            {
                JLOG (context.j.warning) << "Bad market: " << book;
                return rpcError (rpcBAD_MARKET);
            }

            context.netOps.subBook (ispSub, book);

            if (bBoth)
                context.netOps.subBook (ispSub, book);

            if (bSnapshot)
            {
                context.loadType = Resource::feeMediumBurdenRPC;
                std::shared_ptr<ReadView const> lpLedger
                        = context.app.getLedgerMaster().getPublishedLedger();
                if (lpLedger)
                {
                    const Json::Value jvMarker = Json::Value (Json::nullValue);
                    Json::Value jvOffers (Json::objectValue);

                    auto add = [&](Json::StaticString field)
                    {
                        context.netOps.getBookPage (isUnlimited (context.role),
                            lpLedger, field == jss::asks ? reversed (book) : book,
                            takerID ? *takerID : noAccount(), false, 0, jvMarker,
                            jvOffers);

                        if (jvResult.isMember (field))
                        {
                            Json::Value& results (jvResult[field]);
                            for (auto const& e : jvOffers[jss::offers])
                                results.append (e);
                        }
                        else
                        {
                            jvResult[field] = jvOffers[jss::offers];
                        }
                    };

                    if (bBoth)
                    {
                        add (jss::bids);
                        add (jss::asks);
                    }
                    else
                    {
                        add (jss::offers);
                    }
                }
            }
        }
    }

    return jvResult;
}
Example #29
0
/**
 * Set command
 */
void command_set(const char* line) {

    char cmd[MAX_BUFFER];
    char key[MAX_BUFFER];
    char func[MAX_BUFFER];
    char arg1[MAX_BUFFER];
    char arg2[MAX_BUFFER];

    int argc = sscanf(line, "%s %s = %s %s %s", cmd, key, func, arg1, arg2);
    if (argc < 3) {
        puts("invalid arguments");
        return;
    }

    uint32_t* matrix = NULL;

    switch (argc) {
        case 3:
            if (strcasecmp(func, "identity") == 0) {
                matrix = identity_matrix();
            } else {
                goto invalid;
            }
            break;

        case 4:
            if (strcasecmp(func, "random") == 0) {
                uint32_t seed = atoll(arg1);
                matrix = random_matrix(seed);
            } else if (strcasecmp(func, "uniform") == 0) {
                uint32_t value = atoll(arg1);
                matrix = uniform_matrix(value);
            } else if (strcasecmp(func, "cloned") == 0) {
                MATRIX_GUARD(arg1);
                matrix = cloned(m);
            } else if (strcasecmp(func, "reversed") == 0) {
                MATRIX_GUARD(arg1);
                matrix = reversed(m);
            } else if (strcasecmp(func, "transposed") == 0) {
                MATRIX_GUARD(arg1);
                matrix = transposed(m);
            } else {
                goto invalid;
            }
            break;

        case 5:
            if (strcasecmp(func, "sequence") == 0) {
                uint32_t start = atoll(arg1);
                uint32_t step = atoll(arg2);
                matrix = sequence_matrix(start, step);
            } else if (strcasecmp(func, "scalar#add") == 0) {
                MATRIX_GUARD(arg1);
                uint32_t value = atoll(arg2);
                matrix = scalar_add(m, value);
            } else if (strcasecmp(func, "scalar#mul") == 0) {
                MATRIX_GUARD(arg1);
                uint32_t value = atoll(arg2);
                matrix = scalar_mul(m, value);
            } else if (strcasecmp(func, "matrix#add") == 0) {
                MATRIX_GUARD_PAIR(arg1, arg2);
                matrix = matrix_add(m1, m2);
            } else if (strcasecmp(func, "matrix#mul") == 0) {
                MATRIX_GUARD_PAIR(arg1, arg2);
                matrix = matrix_mul(m1, m2);
            } else if (strcasecmp(func, "matrix#pow") == 0) {
                MATRIX_GUARD(arg1);
                uint32_t exponent = atoll(arg2);
                matrix = matrix_pow(m, exponent);
            } else {
                goto invalid;
            }
            break;
    }

    entry* e = find_entry(key);
    if (e == NULL) {
        e = add_entry(key);
    } else {
        free(e->matrix);
    }

    e->matrix = matrix;

    puts("ok");
    return;

invalid:
    puts("invalid arguments");
}
Example #30
0
YString YString::reverse() const {
	YString reversed(*this);
	std::reverse(reversed.unicode.begin(), reversed.unicode.end());
	return YString(reversed);
}