Esempio n. 1
0
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine(int argc, char* argv[])
{
    bool fResult = false;

    for (int i = 1; i < argc; i++)
    {
        QString arg(argv[i]);
        if (arg.startsWith("-"))
            continue;

        if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
        {
            savedPaymentRequests.append(arg);

            SendCoinsRecipient r;
            if (GUIUtil::parseBitcoinURI(arg, &r))
            {
                CBitcoinAddress address(r.address.toStdString());

                SelectParams(CChainParams::MAIN);
                if (!address.IsValid())
                {
                    SelectParams(CChainParams::TESTNET);
                }
            }
        }
        else if (QFile::exists(arg)) // Filename
        {
            savedPaymentRequests.append(arg);

            PaymentRequestPlus request;
            if (readPaymentRequest(arg, request))
            {
                if (request.getDetails().network() == "main")
                    SelectParams(CChainParams::MAIN);
                else
                    SelectParams(CChainParams::TESTNET);
            }
        }
        else
        {
            // Printing to debug.log is about the best we can do here, the
            // GUI hasn't started yet so we can't pop up a message box.
            qDebug() << "PaymentServer::ipcSendCommandLine : Payment request file does not exist: " << arg;
        }
    }

    foreach (const QString& r, savedPaymentRequests)
    {
        QLocalSocket* socket = new QLocalSocket();
        socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
        if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
            return false;

        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_0);
        out << r;
        out.device()->seek(0);
        socket->write(block);
        socket->flush();

        socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
        socket->disconnectFromServer();
        delete socket;
        fResult = true;
    }
Esempio n. 2
0
/* (once x) = x, but x is evaluated only once. */
value type_once(value f)
	{
	if (!f->L) return 0;
	return reduce(f,arg(f->R));
	}
Esempio n. 3
0
File: syscalls.c Progetto: 5kg/gdb
int
rx_syscall (int id)
{
  static char buf[256];
  int rv;

  argp = 0;
  stackp = 4;
  if (trace)
    printf ("\033[31m/* SYSCALL(%d) = %s */\033[0m\n", id, id <= SYS_link ? callnames[id] : "unknown");
  switch (id)
    {
    case SYS_exit:
      {
	int ec = arg ();
	if (verbose)
	  printf ("[exit %d]\n", ec);
	return RX_MAKE_EXITED (ec);
      }
      break;

    case SYS_open:
      {
	int path = arg ();
	/* The open function is defined as taking a variable number of arguments
	   because the third parameter to it is optional:
	     open (const char * filename, int flags, ...);
	   Hence the oflags and cflags arguments will be on the stack and we need
	   to skip the (empty) argument registers r3 and r4.  */
	argp = 4;
	int oflags = arg ();
	int cflags = arg ();

	read_target (buf, path, 256, 1);
	if (trace)
	  printf ("open(\"%s\",0x%x,%#o) = ", buf, oflags, cflags);

	if (callbacks)
	  /* The callback vector ignores CFLAGS.  */
	  rv = callbacks->open (callbacks, buf, oflags);
	else
	  {
	    int h_oflags = 0;

	    if (oflags & 0x0001)
	      h_oflags |= O_WRONLY;
	    if (oflags & 0x0002)
	      h_oflags |= O_RDWR;
	    if (oflags & 0x0200)
	      h_oflags |= O_CREAT;
	    if (oflags & 0x0008)
	      h_oflags |= O_APPEND;
	    if (oflags & 0x0400)
	      h_oflags |= O_TRUNC;
	    rv = open (buf, h_oflags, cflags);
	  }
	if (trace)
	  printf ("%d\n", rv);
	put_reg (1, rv);
      }
      break;

    case SYS_close:
      {
	int fd = arg ();

	if (callbacks)
	  rv = callbacks->close (callbacks, fd);
	else if (fd > 2)
	  rv = close (fd);
	else
	  rv = 0;
	if (trace)
	  printf ("close(%d) = %d\n", fd, rv);
	put_reg (1, rv);
      }
      break;

    case SYS_read:
      {
	int fd = arg ();
	int addr = arg ();
	int count = arg ();

	if (count > sizeof (buf))
	  count = sizeof (buf);
	if (callbacks)
	  rv = callbacks->read (callbacks, fd, buf, count);
	else
	  rv = read (fd, buf, count);
	if (trace)
	  printf ("read(%d,%d) = %d\n", fd, count, rv);
	if (rv > 0)
	  write_target (buf, addr, rv, 0);
	put_reg (1, rv);
      }
      break;

    case SYS_write:
      {
	int fd = arg ();
	int addr = arg ();
	int count = arg ();

	if (count > sizeof (buf))
	  count = sizeof (buf);
	if (trace)
	  printf ("write(%d,0x%x,%d)\n", fd, addr, count);
	read_target (buf, addr, count, 0);
	if (trace)
	  fflush (stdout);
	if (callbacks)
	  rv = callbacks->write (callbacks, fd, buf, count);
	else
	  rv = write (fd, buf, count);
	if (trace)
	  printf ("write(%d,%d) = %d\n", fd, count, rv);
	put_reg (1, rv);
      }
      break;

    case SYS_getpid:
      put_reg (1, 42);
      break;

    case SYS_gettimeofday:
      {
	int tvaddr = arg ();
	struct timeval tv;

	rv = gettimeofday (&tv, 0);
	if (trace)
	  printf ("gettimeofday: %ld sec %ld usec to 0x%x\n", tv.tv_sec,
		  tv.tv_usec, tvaddr);
	mem_put_si (tvaddr, tv.tv_sec);
	mem_put_si (tvaddr + 4, tv.tv_usec);
	put_reg (1, rv);
      }
      break;

    case SYS_kill:
      {
	int pid = arg ();
	int sig = arg ();
	if (pid == 42)
	  {
	    if (verbose)
	      printf ("[signal %d]\n", sig);
	    return RX_MAKE_STOPPED (sig);
	  }
      }
      break;

    case 11:
      {
	int heaptop_arg = arg ();
	if (trace)
	  printf ("sbrk: heap top set to %x\n", heaptop_arg);
	heaptop = heaptop_arg;
	if (heapbottom == 0)
	  heapbottom = heaptop_arg;
      }
      break;

    case 255:
      {
	int addr = arg ();
	mem_put_si (addr, rx_cycles + mem_usage_cycles());
      }
      break;

    }
  return RX_MAKE_STEPPED ();
}
Esempio n. 4
0
// 
// Handle command line arguments
//
void parseIndexOptions(int argc, char** argv)
{
    bool die = false;
    for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) 
    {
        std::istringstream arg(optarg != NULL ? optarg : "");
        switch (c) 
        {
            case 'p': arg >> opt::prefix; break;
            case '?': die = true; break;
            case 'c': opt::validate = true; break;
            case 'd': opt::bDiskAlgo = true; arg >> opt::numReadsPerBatch; break;
            case 't': arg >> opt::numThreads; break;
            case 'g': arg >> opt::gapArrayStorage; break;
            case 'a': arg >> opt::algorithm; break;
            case 'v': opt::verbose++; break;
            case OPT_NO_REVERSE: opt::bBuildReverse = false; break;
            case OPT_NO_FWD: opt::bBuildForward = false; break;
            case OPT_NO_SAI: opt::bBuildSAI = false; break;
            case OPT_HELP:
                std::cout << INDEX_USAGE_MESSAGE;
                exit(EXIT_SUCCESS);
            case OPT_VERSION:
                std::cout << INDEX_VERSION_MESSAGE;
                exit(EXIT_SUCCESS);
        }
    }

    // Transform algorithm parameter to lower case
    std::transform(opt::algorithm.begin(), opt::algorithm.end(), opt::algorithm.begin(), ::tolower);
    
    if (argc - optind < 1) 
    {
        std::cerr << SUBPROGRAM ": missing arguments\n";
        die = true;
    } 
    else if (argc - optind > 1) 
    {
        std::cerr << SUBPROGRAM ": too many arguments\n";
        die = true;
    }

    if(opt::gapArrayStorage != 4 && opt::gapArrayStorage != 8 &&
       opt::gapArrayStorage != 16 && opt::gapArrayStorage != 32)
    {
        std::cerr << SUBPROGRAM ": invalid argument, --gap-array,-g must be one of 4,8,16,32 (found: " << opt::gapArrayStorage << ")\n";
        die = true;
    }

    if(opt::numThreads <= 0)
    {
        std::cerr << SUBPROGRAM ": invalid number of threads: " << opt::numThreads << "\n";
        die = true;
    }

    if(opt::algorithm != "sais" && opt::algorithm != "bcr" && opt::algorithm != "ropebwt")
    {
        std::cerr << SUBPROGRAM ": unrecognized algorithm string " << opt::algorithm << ". --algorithm must be sais, bcr or ropebwt\n";
        die = true;
    }

    if(opt::algorithm == "ropebwt" && opt::bDiskAlgo)
    {
        std::cerr << SUBPROGRAM ": the options -a ropebwt and -d are not compatible, please only use one.\n";
        die = true;
    }

    if (die) 
    {
        std::cout << "\n" << INDEX_USAGE_MESSAGE;
        exit(EXIT_FAILURE);
    }

    // Parse the input filenames
    opt::readsFile = argv[optind++];
    if(opt::prefix.empty())
        opt::prefix = stripFilename(opt::readsFile);

    // Check if input file is empty
    size_t filesize = getFilesize(opt::readsFile);
    if(filesize == 0)
    {
        std::cerr << SUBPROGRAM ": input file is empty\n";
        exit(EXIT_FAILURE);
    }
}
string query_owner(){
   return (string) arg();
}/*query_owner()*/
Esempio n. 6
0
int cmd_opt::parse(int argc, char **argv)
{
    auto mode = CMD_OPT;
    for (auto i = 1; i < argc; i++) {
        std::string arg(argv[i]);
        switch (mode) {
        case CMD_OPT:
            if (arg == "-o" || arg == "--output") {
                mode = CMD_OUTPUT_ARG;
            }
            else if (arg == "-h" || arg == "--help") {
                return 1;
            }
            else if (arg == "-t" || arg == "--threshold") {
                mode = CMD_THRESHOLD_ARG;
            }
            else if (arg == "-n" || arg == "--node") {
                mode = CMD_NODE_ARG;
            }
            else if (arg == "-l" || arg == "--l") {
                mode = CMD_LABEL_ARG;
            }
            else if (arg == "-d" || arg == "--depth") {
                mode = CMD_DEPTH_ARG;
            }
            else if (arg == "-m" || arg == "--max-subnodes") {
                mode = CMD_MAX_SUBNODES_ARG;
            }
            else if (arg == "-e" || arg == "--export") {
                mode = CMD_EXPORT_ARG;
            }
            else if (arg == "-c" || arg == "--critical") {
                critical_only = true;
            }
            else {
                if (!ifile.empty()) {
                    return -3;
                }
                ifile = arg;
            }

            break;
        case CMD_OUTPUT_ARG:
            ofile = arg;
            mode = CMD_OPT;
            break;
        case CMD_THRESHOLD_ARG:
        {
            char *p = argv[i];
            threshold = std::strtod(argv[i], &p);
            if (p == argv[i]) {
                return -2;
            }
        }
        mode = CMD_OPT;
        break;
        case CMD_MAX_SUBNODES_ARG:
            try {
                max_subnodes = std::stoi(argv[i]);
            }
            catch (...) {
                return -10;
            }
            mode = CMD_OPT;
            break;
        case CMD_DEPTH_ARG:
            try {
                depth = std::stoi(argv[i]);
            }
            catch (...) {
                return -3;
            }
            mode = CMD_OPT;
            break;
        case CMD_EXPORT_ARG:
            if (!strcasecmp("DOT", argv[i])) {
                export_type = EXPORT_DOT;
            }
            else if (!strcasecmp("GML", argv[i])) {
                export_type = EXPORT_GML;
            }
            else if (!strcasecmp("GRAPHML", argv[i])) {
                export_type = EXPORT_GRAPHML;
            }
            else {
                return -4;
            }
            mode = CMD_OPT;
            break;
        case CMD_NODE_ARG:
            parse_node(argv[i]);
            mode = CMD_OPT;
            break;
        case CMD_LABEL_ARG:
        {
            std::string s((argv[i][1] == 'x' || argv[i][1] == 'X')? &argv[i][2] : argv[i]);
            auto i = std::stoll(s, NULL, 16);
            labels.push_back(i);
        }
            mode = CMD_OPT;
            break;
        default:
            return -1;
        }
    }

    return 0;
}
Esempio n. 7
0
void test_edges()
{
    const double pi = std::atan2(+0., -0.);
    const unsigned N = sizeof(x) / sizeof(x[0]);
    for (unsigned i = 0; i < N; ++i)
    {
        double r = arg(x[i]);
        if (std::isnan(x[i].real()) || std::isnan(x[i].imag()))
            assert(std::isnan(r));
        else
        {
            switch (classify(x[i]))
            {
            case zero:
                if (std::signbit(x[i].real()))
                {
                    if (std::signbit(x[i].imag()))
                        is_about(r, -pi);
                    else
                        is_about(r, pi);
                }
                else
                {
                    assert(std::signbit(x[i].imag()) == std::signbit(r));
                }
                break;
            case non_zero:
                if (x[i].real() == 0)
                {
                    if (x[i].imag() < 0)
                        is_about(r, -pi/2);
                    else
                        is_about(r, pi/2);
                }
                else if (x[i].imag() == 0)
                {
                    if (x[i].real() < 0)
                    {
                        if (std::signbit(x[i].imag()))
                            is_about(r, -pi);
                        else
                            is_about(r, pi);
                    }
                    else
                    {
                        assert(r == 0);
                        assert(std::signbit(x[i].imag()) == std::signbit(r));
                    }
                }
                else if (x[i].imag() > 0)
                    assert(r > 0);
                else
                    assert(r < 0);
                break;
            case inf:
                if (std::isinf(x[i].real()) && std::isinf(x[i].imag()))
                {
                    if (x[i].real() < 0)
                    {
                        if (x[i].imag() > 0)
                            is_about(r, 0.75 * pi);
                        else
                            is_about(r, -0.75 * pi);
                    }
                    else
                    {
                        if (x[i].imag() > 0)
                            is_about(r, 0.25 * pi);
                        else
                            is_about(r, -0.25 * pi);
                    }
                }
                else if (std::isinf(x[i].real()))
                {
                    if (x[i].real() < 0)
                    {
                        if (std::signbit(x[i].imag()))
                            is_about(r, -pi);
                        else
                            is_about(r, pi);
                    }
                    else
                    {
                        assert(r == 0);
                        assert(std::signbit(r) == std::signbit(x[i].imag()));
                    }
                }
                else
                {
                    if (x[i].imag() < 0)
                        is_about(r, -pi/2);
                    else
                        is_about(r, pi/2);
                }
                break;
            }
        }
    }
}
Esempio n. 8
0
  bool Inliner::inline_primitive(Class* klass, CompiledMethod* cm, executor prim) {
    const char* inlined_prim = 0;

    if(prim == Primitives::tuple_at && count_ == 1) {
      inlined_prim = "tuple_at";
      call_tuple_at(ops_, *this);
    } else if(prim == Primitives::tuple_put && count_ == 2) {
      inlined_prim = "tuple_put";
      call_tuple_put(ops_, *this);
    } else if(prim == Primitives::fixnum_and && count_ == 1) {
      inlined_prim = "fixnum_and";
      fixnum_and(ops_, *this);
    } else if(prim == Primitives::fixnum_or && count_ == 1) {
      inlined_prim = "fixnum_or";
      fixnum_or(ops_, *this);
    } else if(prim == Primitives::fixnum_neg && count_ == 0) {
      inlined_prim = "fixnum_neg";
      fixnum_neg(ops_, *this);
    } else if(prim == Primitives::object_equal && count_ == 1) {
      inlined_prim = "object_equal";
      object_equal(klass, ops_, *this);
    } else if(prim == Primitives::float_add && count_ == 1) {
      inlined_prim = "float_add";
      float_op(cAdd, klass, ops_, *this);
    } else if(prim == Primitives::float_sub && count_ == 1) {
      inlined_prim = "float_sub";
      float_op(cSub, klass, ops_, *this);
    } else if(prim == Primitives::float_mul && count_ == 1) {
      inlined_prim = "float_mul";
      float_op(cMultiply, klass, ops_, *this);
    } else if(prim == Primitives::float_div && count_ == 1) {
      inlined_prim = "float_div";
      float_op(cDivide, klass, ops_, *this);
    } else if(prim == Primitives::float_mod && count_ == 1) {
      inlined_prim = "float_mod";
      float_op(cMod, klass, ops_, *this);
      /*
    } else if(prim == Primitives::object_class && count_ == 0) {
      inlined_prim = "object_class";
      object_class(klass, ops_, *this);
      */
    } else {
      JITStubResults stub_res;

      if(Primitives::get_jit_stub(cm->prim_index(), stub_res)) {
        if(stub_res.arg_count() == count_) {
          Value* self = recv();
          ops_.check_class(self, klass, failure());

          std::vector<Value*> call_args;

          Signature sig(ops_.state(), "Object");
          sig << "VM";
          call_args.push_back(ops_.vm());

          if(stub_res.pass_callframe()) {
            sig << "CallFrame";
            call_args.push_back(ops_.call_frame());
          }

          sig << "Object";
          call_args.push_back(self);

          for(int i = 0; i < stub_res.arg_count(); i++) {
            sig << "Object";
            call_args.push_back(arg(i));
          }

          Function* func = sig.function(stub_res.name());
          func->setDoesNotCapture(1, true);

          if(stub_res.pass_callframe()) {
            func->setDoesNotCapture(2, true);
          }

          Value* res = sig.call(stub_res.name(), call_args, "prim_value", ops_.b());

          // Only doing this when stub_res.can_fail() causes an exception
          // to be thrown when running the ci specs, need to investigate.
          BasicBlock* cont = ops_.new_block("continue");

          Value* as_i = ops_.ptrtoint(res);
          Value* icmp = ops_.b().CreateICmpEQ(as_i,
              ConstantInt::get(ops_.state()->IntPtrTy, reinterpret_cast<intptr_t>(Qundef)));

          ops_.b().CreateCondBr(icmp, failure(), cont);
          ops_.set_block(cont);

          set_result(res);

          if(ops_.state()->config().jit_inline_debug) {
            std::cerr << "inlining: "
              << ops_.state()->symbol_cstr(cm->scope()->module()->name())
              << "#"
              << ops_.state()->symbol_cstr(cm->name())
              << " into "
              << ops_.state()->symbol_cstr(ops_.vmmethod()->original->name())
              << ". generic primitive: " << stub_res.name() << "\n";
          }
          return true;

        }
      }

    }

    if(inlined_prim) {
      if(ops_.state()->config().jit_inline_debug) {
        std::cerr << "inlining: "
          << ops_.state()->symbol_cstr(cm->scope()->module()->name())
          << "#"
          << ops_.state()->symbol_cstr(cm->name())
          << " into "
          << ops_.state()->symbol_cstr(ops_.vmmethod()->original->name())
          << ". primitive " << inlined_prim << "\n";
      }

      return true;
    }

    // Add more primitive inlining!
    if(ops_.state()->config().jit_inline_debug) {
      std::cerr << "NOT inlining: "
        << ops_.state()->symbol_cstr(cm->scope()->module()->name())
        << "#"
        << ops_.state()->symbol_cstr(cm->name())
        << " into "
        << ops_.state()->symbol_cstr(ops_.vmmethod()->original->name())
        << ". primitive: "
        << ops_.state()->symbol_cstr(cm->primitive())
        << "\n";
    }
    return false;
  }
Esempio n. 9
0
bool Screen::dropCallbackEvent(int count, const char **filenames) {
    std::vector<std::string> arg(count);
    for (int i = 0; i < count; ++i)
        arg[i] = filenames[i];
    return dropEvent(arg);
}
Esempio n. 10
0
int
main(int argc, char *argv[])
{
  QTextStream error(stderr);
  QString errorMessage;
  char *infile, *outfile;
  QTextCodec *codec = QTextCodec::codecForName("utf-8");
  bool quiet = false;

  /* Check for the correct number of input parameters. */
  if (argc < 5 || argc > 8)
    print_usage_and_exit();
  for (int i = 1; i < argc; i++) {
    QString arg(argv[i]);
    if (!arg.compare("-q", Qt::CaseInsensitive))
      quiet = true;
    else if (!arg.compare("-i", Qt::CaseInsensitive) && ++i < argc)
      infile = argv[i];
    else if (!arg.compare("-o", Qt::CaseInsensitive) && ++i < argc)
      outfile = argv[i];
    else if (!arg.compare("-c", Qt::CaseInsensitive) && ++i < argc) {
      codec = QTextCodec::codecForName(argv[i]);
      if (!codec) {
        error << "Invalid text encoding specified\n";
        return 1;
      }
    } else
      print_usage_and_exit(); 
  }

  /* Open the input PO file for reading. */
  QFile poFile(infile);
  if (!poFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
    error << QString("Unable to open '%1' for reading: %2\n").arg(infile)
                                                .arg(poFile.errorString());
    return 2;
  }

  QDomDocument ts;
  QTextStream po(&poFile);
  po.setCodec(codec);
  int n_strings = po2ts(&po, &ts, &errorMessage);
  if (n_strings < 0) {
    error << QString("Unable to convert '%1': %2\n").arg(infile)
                                                    .arg(errorMessage);
    return 3;
  }

  /* Open the TS file for writing. */
  QFile tsFile(outfile);
  if (!tsFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
    error << QString("Unable to open '%1' for writing: %2\n").arg(outfile)
                                                .arg(tsFile.errorString());
    return 4;
  }

  /* Write the .ts output. */
  QTextStream out(&tsFile);
  out.setCodec(codec);
  out << QString("<?xml version=\"1.0\" encoding=\"%1\"?>\n")
                                                  .arg(QString(codec->name()));
  out << ts.toString(4);

  if (!quiet) {
    QTextStream results(stdout);
    results << QString("Converted %1 strings from %2 to %3.\n").arg(n_strings)
                                                               .arg(infile)
                                                               .arg(outfile);
  }
  return 0;
}
Esempio n. 11
0
void CalculateShift(
    std::complex<double> c1, std::complex<double> g1, std::complex<double> m1,
    std::complex<double> c2, std::complex<double> g2, std::complex<double> m2,
    std::complex<double>& c3, std::complex<double>& g3, 
    std::complex<double>& m3)
{
    // The first set (c1,g1,m1) effect a transformation:
    //
    // z' = exp(-m1)/sqrt(1-|g1|^2) ( z-c1 - g1 (z-c1)* )
    //
    // Now execute a second transformation (c2,g2,m2):
    //
    // z'' = exp(-m2)/sqrt(1-|g2|^2) * 
    //    [ ( exp(-m1)/sqrt(1-|g1|^2) ( z-c1 - g1 (z-c1)* ) - c2 ) -
    //      g2 * ( exp(-m1)/sqrt(1-|g1|^2) ( z-c1 - g1 (z-c1)* ) - c2 )* ]
    //
    // We need to figure out what this corresponds to in terms of an 
    // effective:
    // z'' = exp(-m3)/sqrt(1-|g3|^2) ( z-c3 - g3 (z-c3)* )
    //
    // This is pretty complicated, but we can do it in steps.
    //
    // First, just take the terms with z or z*:
    //
    // z'' = exp(-m2)/sqrt(1-|g2|^2)/sqrt(1-|g1|^2) * 
    //       ( exp(-m1) (z - g1 z*) - g2 exp(-m1*) (z* - g1* z) )
    //     = exp(-m2)/sqrt(1-|g2|^2)/sqrt(1-|g1|^2) * 
    //       ( (exp(-m1) + exp(-m1*) g1* g2) z - 
    //         (exp(-m1) g1 + exp(-m1*) g2) z* )
    //     = exp(-m1-m2)/sqrt(1-|g2|^2)/sqrt(1-|g1|^2)
    //       ( (1 + R g1* g2) z - (g1 + R g2) z* )
    // where R == exp(2i imag(m1))
    //
    // So, 
    //
    // g3 = (g1 + R g2) / (1 + R g1* g2)
    // exp(-m3) = exp(-m1-m2) (1+R g1* g2) sqrt(1-|g3|^2)/
    //                   sqrt(1-|g1|^2) / sqrt(1-|g2|^2)
    // 
    // The g terms simplify (after a bit of algebra):
    // exp(-m3) = exp(-m1-m2) (1+R g1* g2)/|1+R g1* g2|
    // 
    // Finally, the translation terms are a bit messy.
    // The translation terms in the equation for z'' are:
    //
    // exp(-m2)/sqrt(1-|g2|^2) * 
    //    [ ( exp(-m1)/sqrt(1-|g1|^2) ( -c1 - g1 (-c1)* ) - c2 ) -
    //      g2 * ( exp(-m1)/sqrt(1-|g1|^2) ( -c1 - g1 (-c1)* ) - c2 )* ]
    // 
    // This is some value, which we set equal to:
    //
    // exp(-m3)/sqrt(1-|g3|^2) (-c3 - g3(-c3)* )
    //
    // So solving for c3 - g3 c3* is straightforward.
    // c3 - g3 c3* = X
    // c3* - g3* c3 = X*
    // g3 c3* - |g3|^2 c3 = g3 X*
    // c3 - |g3|^2 c3 = X + g3 X*
    // c3 = (X + g3 X*) / (1-|g3|^2)
    //

    xdbg<<"Start CalculateShift\n";
    xdbg<<"c1,g1,m1 = "<<c1<<"  "<<g1<<"  "<<m1<<std::endl;
    xdbg<<"c2,g2,m2 = "<<c2<<"  "<<g2<<"  "<<m2<<std::endl;

    std::complex<double> Rg2 = std::polar(1.,2*imag(m1)) * g2;
    double normg1 = norm(g1);
    double normg2 = norm(g2);
    std::complex<double> denom = 1.+conj(g1)*Rg2;
    g3 = (g1+Rg2) / denom;
    xdbg<<"g3 = "<<g3<<std::endl;

    //xdbg<<"Miralda-Escude formula gives g3 = "<<addShears(g1,g2)<<std::endl;

    m3 = m1 + m2 - std::complex<double>(0.,1.)*arg(denom);
    xdbg<<"m3 = "<<m3<<std::endl;

    std::complex<double> X = -c1 - g1 * conj(-c1);
    X = exp(-m1)/sqrt(1.-normg1) * X - c2;
    X = exp(-m2)/sqrt(1.-normg2) * (X - g2 * conj(X));
    double normg3 = norm(g3);
    X /= -exp(-m3)/sqrt(1.-normg3);
    c3 = (X + g3*conj(X)) / (1.-normg3);
    xdbg<<"c3 = "<<c3<<std::endl;
}
Esempio n. 12
0
QVariant DataFilesModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    EsmFile *file = item(index.row());

    if (!file)
        return QVariant();

    const int column = index.column();

    switch (role) {
    case Qt::DisplayRole: {

        switch (column) {
        case 0:
            return file->fileName();
        case 1:
            return file->author();
        case 2:
            return QString("%1 kB").arg(int((file->size() + 1023) / 1024));
        case 3:
            //return file->modified().toString(Qt::TextDate);
            return file->modified().toString(Qt::ISODate);
        case 4:
            return file->accessed().toString(Qt::TextDate);
        case 5:
            return file->version();
        case 6:
            return file->path();
        case 7:
            return file->masters().join(", ");
        case 8:
            return file->description();
        }
    }

    case Qt::TextAlignmentRole: {
        switch (column) {
        case 0:
        case 1:
            return Qt::AlignLeft + Qt::AlignVCenter;
        case 2:
        case 3:
        case 4:
        case 5:
            return Qt::AlignRight + Qt::AlignVCenter;
        default:
            return Qt::AlignLeft + Qt::AlignVCenter;
        }
    }

    case Qt::CheckStateRole: {
        if (column != 0)
            return QVariant();
        return mCheckStates[file->fileName()];
    }
    case Qt::ToolTipRole:
    {
        if (column != 0)
            return QVariant();

        if (file->version() == 0.0f)
            return QVariant(); // Data not set

        QString tooltip =
                QString("<b>Author:</b> %1<br/> \
                        <b>Version:</b> %2<br/> \
                        <br/><b>Description:</b><br/>%3<br/> \
                        <br/><b>Dependencies: </b>%4<br/>")
                        .arg(file->author())
                        .arg(QString::number(file->version()))
                        .arg(file->description())
                        .arg(file->masters().join(", "));


        return tooltip;

    }
    default:
        return QVariant();
    }

}
Esempio n. 13
0
        return;
    }

    FilterName = filterName();
    bool filter = AllFilter || Criteria.contains(FilterName);
    filterAct->setChecked(filter);

    toConnection &conn = connection();
    QList<QString> priKeys = conn.getTraits().primaryKeys(conn, toCache::ObjectRef(Owner, Table, Owner));
    SQL = "SELECT ";
    Q_FOREACH(QString c, priKeys)
    {
        SQL += c + ",";
    }
    SQL = SQL + " t.* FROM %1.%2 t ";
    SQL = SQL.arg(conn.getTraits().quote(Owner)).arg(conn.getTraits().quote(Table));

    bool where = false;
    if (filter && !Criteria[FilterName].isEmpty())
    {
        SQL += " WHERE ";
        SQL += Criteria[FilterName];
        SQL += " ";
        where = true;
    }

    if (filter && !Order[FilterName].isEmpty())
    {
        SQL += " ORDER BY ";
        SQL += Order[FilterName];
    }
Esempio n. 14
0
dual MGL_LOCAL_CONST argc(dual x)	{	return arg(x);	}
Esempio n. 15
0
UtlBoolean Listener::handleMessage(OsMsg& rMsg)
{
   // React to telephony events
   if(rMsg.getMsgSubType()== TaoMessage::EVENT)
   {
      TaoMessage* taoMessage = (TaoMessage*)&rMsg;

      int taoEventId = taoMessage->getTaoObjHandle();
      UtlString argList(taoMessage->getArgList());
      TaoString arg(argList, TAOMESSAGE_DELIMITER);

#ifdef DEBUGGING
      dumpTaoMessageArgs(taoEventId, arg) ;
#endif        
      UtlBoolean localConnection = atoi(arg[TAO_OFFER_PARAM_LOCAL_CONNECTION]);
      UtlString  callId = arg[TAO_OFFER_PARAM_CALLID] ;
      UtlString  address = arg[TAO_OFFER_PARAM_ADDRESS] ;

      switch (taoEventId) 
      {
         case PtEvent::CONNECTION_OFFERED:
            OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Call arrived: callId %s address %s\n", 
                          callId.data(), address.data());

            mpCallManager->acceptConnection(callId, address);
            mpCallManager->answerTerminalConnection(callId, address, "*");

            break;
         case PtEvent::CONNECTION_ESTABLISHED:
            if (localConnection) 
            {
               OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Call connected: callId %s\n", callId.data());

               CallObject* pThisCall = new CallObject(mpCallManager, callId, mPlayfile);

               // Create a player and start to play out the file
               if (pThisCall->playAudio() == OS_SUCCESS)
               {
                  // Put it in a sorted list
                  insertEntry(callId, pThisCall);
               }
               else
               {
                  // Drop the call
                  mpCallManager->drop(callId);
                  OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_WARNING, "Listener::handleMessage - drop callId %s due to failure of playing audio\n",
                                callId.data());

                  delete pThisCall;
               }
            }

            break;
            
         case PtEvent::CONNECTION_DISCONNECTED:
            if (!localConnection) 
            {
               OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Call Dropped: %s\n", callId.data());

               // Remove the call from the pool and clean up the call
               CallObject* pDroppedCall = removeEntry(callId);
               if (pDroppedCall)
               {
                  pDroppedCall->cleanUp();
                  delete pDroppedCall;

                  // Drop the call
                  mpCallManager->drop(callId);
               }
               else
               {
                  OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Lisenter::handleMessage - no callId %s founded in the active call list\n",
                                callId.data());
               }
            }

            break;
            
         case PtEvent::CONNECTION_FAILED:
            OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_WARNING, "Dropping call: %s\n", callId.data());

            mpCallManager->drop(callId);

            break;
      }
   }
   return(TRUE);
}
Esempio n. 16
0
/**
 * Parse command line arguments
 *
 * @param argc Number of arguments in array argv
 * @param argv Arguments array
 *
 * @return true to continue with application launch; otherwise false
 */
bool parseArgs()
{
    QStringListIterator it(QCoreApplication::arguments());
    while (it.hasNext() == true)
    {
        QString arg(it.next());

        if ((arg == "-c" || arg == "--closebutton") && it.hasNext() == true)
        {
            QString str(it.next());
            QStringList parts = str.split(",");
            if (parts.size() == 4)
            {
                QRect rect(parts[0].toInt(), parts[1].toInt(),
                           parts[2].toInt(), parts[3].toInt());
                if (rect.isValid() == true)
                    QLCArgs::closeButtonRect = rect;
            }
        }
        else if (arg == "-d" || arg == "--debug")
        {
            if (it.hasNext() == true)
                QLCArgs::debugLevel = QtMsgType(it.peekNext().toInt());
            else
                QLCArgs::debugLevel = QtMsgType(0);
        }
        else if (arg == "-g" || arg == "--log")
        {
            QLCArgs::logToFile = true;
            QString logFilename = QDir::homePath() + QDir::separator() + "QLC+.log";
            QLCArgs::logFile.setFileName(logFilename);
            QLCArgs::logFile.open(QIODevice::Append);
        }
        else if (arg == "-f" || arg == "--fullscreen")
        {
            QLCArgs::fullScreen = true;
            if (it.hasNext() == true && it.peekNext() == "resize")
                QLCArgs::fullScreenResize = true;
        }
        else if (arg == "-r" || arg == "--overscan")
        {
            QLCArgs::enableOverscan = true;
        }
        else if (arg == "-h" || arg == "--help")
        {
            printUsage();
            return false;
        }
        else if (arg == "-k" || arg == "--kiosk")
        {
            QLCArgs::kioskMode = true;
        }
        else if (arg == "-l" || arg == "--locale")
        {
            if (it.hasNext() == true)
                QLCi18n::setDefaultLocale(it.next());
        }
        else if (arg == "-o" || arg == "--open")
        {
            if (it.hasNext() == true)
                QLCArgs::workspace = it.next();
        }
        else if (arg == "-p" || arg == "--operate")
        {
            QLCArgs::operate = true;
        }
        else if (arg == "-w" || arg == "--web")
        {
            QLCArgs::enableWebAccess = true;
        }
        else if (arg == "-v" || arg == "--version")
        {
            /* Don't print anything, since version is always
               printed before anything else. Just make the app
               exit by returning false. */
            return false;
        }
    }

    return true;
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
   string     cfg_file;
   const char *parsed_file = NULL;
   const char *source_file = NULL;
   const char *output_file = NULL;
   const char *source_list = NULL;
   log_mask_t mask;
   int        idx;
   const char *p_arg;

   /* If ran without options... check keyword sort and show the usage info */
   if (argc == 1)
   {
      keywords_are_sorted();
      usage_exit(NULL, argv[0], EXIT_SUCCESS);
   }

   /* Build options map */
   register_options();

   Args arg(argc, argv);

   if (arg.Present("--version") || arg.Present("-v"))
   {
      version_exit();
   }
   if (arg.Present("--help") || arg.Present("-h") ||
       arg.Present("--usage") || arg.Present("-?"))
   {
      usage_exit(NULL, argv[0], EXIT_SUCCESS);
   }

   if (arg.Present("--show-config"))
   {
      print_options(stdout, true);
      return(0);
   }

#ifdef WIN32
   /* tell windoze not to change what I write to stdout */
   (void)_setmode(_fileno(stdout), _O_BINARY);
#endif

   /* Init logging */
   log_init(stderr);
   if (arg.Present("-q"))
   {
      logmask_from_string("", mask);
      log_set_mask(mask);
   }
   if (((p_arg = arg.Param("-L")) != NULL) ||
       ((p_arg = arg.Param("--log")) != NULL))
   {
      logmask_from_string(p_arg, mask);
      log_set_mask(mask);
   }
   cpd.frag = arg.Present("--frag");

   if ((p_arg = arg.Param("--decode")) != NULL)
   {
      log_pcf_flags(LSYS, strtoul(p_arg, NULL, 16));
      exit(EXIT_SUCCESS);
   }

   /* Get the config file name */
   if (((p_arg = arg.Param("--config")) != NULL) ||
       ((p_arg = arg.Param("-c")) != NULL))
   {
      cfg_file = p_arg;
   }

   /* Try to file a config at an alternate location */
   if (cfg_file.empty())
   {
      if (!unc_getenv("UNCRUSTIFY_CONFIG", cfg_file))
      {
         string home;

         if (unc_homedir(home))
         {
            struct stat tmp_stat;
            string      path;

            path = home + "/uncrustify.cfg";
            if (stat(path.c_str(), &tmp_stat) == 0)
            {
               cfg_file = path;
            }
            else
            {
               path = home + "/.uncrustify.cfg";
               if (stat(path.c_str(), &tmp_stat) == 0)
               {
                  cfg_file = path;
               }
            }
         }
      }
   }

   /* Get the parsed file name */
   if (((parsed_file = arg.Param("--parsed")) != NULL) ||
       ((parsed_file = arg.Param("-p")) != NULL))
   {
      LOG_FMT(LNOTE, "Will export parsed data to: %s\n", parsed_file);
   }

   /* Enable log sevs? */
   if (arg.Present("-s") || arg.Present("--show"))
   {
      log_show_sev(true);
   }

   /* Load the config file */
   set_option_defaults();

   /* Load type files */
   idx = 0;
   while ((p_arg = arg.Params("-t", idx)) != NULL)
   {
      load_keyword_file(p_arg);
   }

   /* add types */
   idx = 0;
   while ((p_arg = arg.Params("--type", idx)) != NULL)
   {
      add_keyword(p_arg, CT_TYPE);
   }

   /* Load define files */
   idx = 0;
   while ((p_arg = arg.Params("-d", idx)) != NULL)
   {
      load_define_file(p_arg);
   }

   /* add defines */
   idx = 0;
   while ((p_arg = arg.Params("--define", idx)) != NULL)
   {
      add_define(p_arg, NULL);
   }

   /* Check for a language override */
   if ((p_arg = arg.Param("-l")) != NULL)
   {
      cpd.lang_flags = language_from_tag(p_arg);
      if (cpd.lang_flags == 0)
      {
         LOG_FMT(LWARN, "Ignoring unknown language: %s\n", p_arg);
      }
      else
      {
         cpd.lang_forced = true;
      }
   }

   /* Get the source file name */
   if (((source_file = arg.Param("--file")) == NULL) &&
       ((source_file = arg.Param("-f")) == NULL))
   {
      // not using a single file, source_file is NULL
   }

   if (((source_list = arg.Param("--files")) == NULL) &&
       ((source_list = arg.Param("-F")) == NULL))
   {
      // not using a file list, source_list is NULL
   }

   const char *prefix = arg.Param("--prefix");
   const char *suffix = arg.Param("--suffix");

   bool no_backup        = arg.Present("--no-backup");
   bool replace          = arg.Present("--replace");
   bool keep_mtime       = arg.Present("--mtime");
   bool update_config    = arg.Present("--update-config");
   bool update_config_wd = arg.Present("--update-config-with-doc");
   bool detect           = arg.Present("--detect");

   /* Grab the output override */
   output_file = arg.Param("-o");

   LOG_FMT(LDATA, "config_file = %s\n", cfg_file.c_str());
   LOG_FMT(LDATA, "output_file = %s\n", (output_file != NULL) ? output_file : "null");
   LOG_FMT(LDATA, "source_file = %s\n", (source_file != NULL) ? source_file : "null");
   LOG_FMT(LDATA, "source_list = %s\n", (source_list != NULL) ? source_list : "null");
   LOG_FMT(LDATA, "prefix      = %s\n", (prefix != NULL) ? prefix : "null");
   LOG_FMT(LDATA, "suffix      = %s\n", (suffix != NULL) ? suffix : "null");
   LOG_FMT(LDATA, "replace     = %d\n", replace);
   LOG_FMT(LDATA, "no_backup   = %d\n", no_backup);
   LOG_FMT(LDATA, "detect      = %d\n", detect);

   if (replace || no_backup)
   {
      if ((prefix != NULL) || (suffix != NULL))
      {
         usage_exit("Cannot use --replace with --prefix or --suffix", argv[0], 66);
      }
      if ((source_file != NULL) || (output_file != NULL))
      {
         usage_exit("Cannot use --replace or --no-backup with -f or -o", argv[0], 66);
      }
   }
   else
   {
      if ((prefix == NULL) && (suffix == NULL))
      {
         suffix = ".uncrustify";
      }
   }

   /* Try to load the config file, if available.
    * It is optional for "--universalindent" and "--detect", but required for
    * everything else.
    */
   if (!cfg_file.empty())
   {
      cpd.filename = cfg_file.c_str();
      if (load_option_file(cpd.filename) < 0)
      {
         usage_exit("Unable to load the config file", argv[0], 56);
      }
   }

   if (arg.Present("--universalindent"))
   {
      FILE *pfile = stdout;

      if (output_file != NULL)
      {
         pfile = fopen(output_file, "w");
         if (pfile == NULL)
         {
            fprintf(stderr, "Unable to open %s for write: %s (%d)\n",
                    output_file, strerror(errno), errno);
            return(EXIT_FAILURE);
         }
      }

      print_universal_indent_cfg(pfile);

      return(EXIT_SUCCESS);
   }

   if (detect)
   {
      file_mem fm;

      if ((source_file == NULL) || (source_list != NULL))
      {
         fprintf(stderr, "The --detect option requires a single input file\n");
         return(EXIT_FAILURE);
      }

      /* Do some simple language detection based on the filename extension */
      if (!cpd.lang_forced || (cpd.lang_flags == 0))
      {
         cpd.lang_flags = language_from_filename(source_file);
      }

      /* Try to read in the source file */
      if (load_mem_file(source_file, fm) < 0)
      {
         LOG_FMT(LERR, "Failed to load (%s)\n", source_file);
         cpd.error_count++;
         return(EXIT_FAILURE);
      }

      uncrustify_start(fm.data);
      detect_options();
      uncrustify_end();

      redir_stdout(output_file);
      save_option_file(stdout, update_config_wd);
      return(EXIT_SUCCESS);
   }

   /* Everything beyond this point requires a config file, so complain and
    * bail if we don't have one.
    */
   if (cfg_file.empty())
   {
      usage_exit("Specify the config file with '-c file' or set UNCRUSTIFY_CONFIG",
                 argv[0], 58);
   }

   /*
    *  Done parsing args
    */

   if (update_config || update_config_wd)
   {
      redir_stdout(output_file);
      save_option_file(stdout, update_config_wd);
      return(0);
   }

   /* Check for unused args (ignore them) */
   idx   = 1;
   p_arg = arg.Unused(idx);

   /* Check args - for multifile options */
   if ((source_list != NULL) || (p_arg != NULL))
   {
      if (source_file != NULL)
      {
         usage_exit("Cannot specify both the single file option and a multi-file option.",
                    argv[0], 67);
      }

      if (output_file != NULL)
      {
         usage_exit("Cannot specify -o with a multi-file option.",
                    argv[0], 68);
      }
   }

   /* This relies on cpd.filename being the config file name */
   load_header_files();

   if ((source_file == NULL) && (source_list == NULL) && (p_arg == NULL))
   {
      /* no input specified, so use stdin */
      if (cpd.lang_flags == 0)
      {
         cpd.lang_flags = LANG_C;
      }

      redir_stdout(output_file);

      file_mem fm;
      if (!read_stdin(fm))
      {
         LOG_FMT(LERR, "Failed to read stdin\n");
         return(100);
      }

      cpd.filename = "stdin";

      /* Done reading from stdin */
      LOG_FMT(LSYS, "Parsing: %d bytes (%d chars) from stdin as language %s\n",
              (int)fm.raw.size(), (int)fm.data.size(),
              language_to_string(cpd.lang_flags));

      uncrustify_file(fm, stdout, parsed_file);
   }
   else if (source_file != NULL)
   {
      /* Doing a single file */
      do_source_file(source_file, output_file, parsed_file, no_backup, keep_mtime);
   }
   else
   {
      /* Doing multiple files */
      if (prefix != NULL)
      {
         LOG_FMT(LSYS, "Output prefix: %s/\n", prefix);
      }
      if (suffix != NULL)
      {
         LOG_FMT(LSYS, "Output suffix: %s\n", suffix);
      }

      /* Do the files on the command line first */
      idx = 1;
      while ((p_arg = arg.Unused(idx)) != NULL)
      {
         char outbuf[1024];
         do_source_file(p_arg,
                        make_output_filename(outbuf, sizeof(outbuf), p_arg, prefix, suffix),
                        NULL, no_backup, keep_mtime);
      }

      if (source_list != NULL)
      {
         process_source_list(source_list, prefix, suffix, no_backup, keep_mtime);
      }
   }

   clear_keyword_file();
   clear_defines();

   return((cpd.error_count != 0) ? 1 : 0);
}
Esempio n. 18
0
File: main.cpp Progetto: digirea/KVS
/*===========================================================================*/
int main( int argc, char** argv )
{
    Argument arg( argc, argv );
    if ( !arg.parse() ) exit( EXIT_FAILURE );

    // Volume resolution.
    kvs::Vector3ui resolution( 64, 64, 64 );
    if ( arg.hasOption("r") )
    {
        const kvs::UInt32 rx = arg.optionValue<kvs::UInt32>("r",0);
        const kvs::UInt32 ry = arg.optionValue<kvs::UInt32>("r",1);
        const kvs::UInt32 rz = arg.optionValue<kvs::UInt32>("r",2);
        resolution = kvs::Vector3ui( rx, ry, rz );
    }

    // Output filename.
    std::string filename("hydrogen.kvsml");
    if ( arg.hasValues() )
    {
        filename = arg.value<std::string>();
    }

    // Generate hydrogen volume.
    kvs::StructuredVolumeObject* volume = new Hydrogen( resolution );
    if ( !volume )
    {
        kvsMessageError( "Cannot create a hydrogen volume." );
        return( false );
    }

    if ( arg.hasOption("verbose") )
    {
        std::cout << "> Structured volume object" << std::endl;
        volume->print( std::cout );
    }

    // Output the hydrogen volume to the file.
    const kvs::File file( filename );
    const std::string extension( file.extension() );
    if ( extension == "fld" )
    {
        kvs::AVSField* field = new kvs::StructuredVolumeExporter<kvs::AVSField>( volume );
        if ( !field )
        {
            kvsMessageError( "Cannot export hydrogen volume." );
            delete volume;
            return( false );
        }

        if ( !field->write( filename ) )
        {
            kvsMessageError( "Cannot write to the file as AVS field format." );
            delete volume;
            return( false );
        }

        if ( arg.hasOption("verbose") )
        {
            std::cout << "AVS field data format" << std::endl;
            field->print( std::cout );
        }

        delete field;
    }
    else if ( extension == "kvsml" )
    {
        kvs::KVSMLObjectStructuredVolume* kvsml =
            new kvs::StructuredVolumeExporter<kvs::KVSMLObjectStructuredVolume>( volume );
        if ( !kvsml )
        {
            kvsMessageError( "Cannot export hydrogen volume." );
            delete volume;
            return( false );
        }

        if ( arg.hasOption("a") )
        {
            kvsml->setWritingDataType( kvs::KVSMLObjectStructuredVolume::ExternalAscii );
        }

        if ( arg.hasOption("b") )
        {
            kvsml->setWritingDataType( kvs::KVSMLObjectStructuredVolume::ExternalBinary );
        }

        if ( !kvsml->write( filename ) )
        {
            kvsMessageError( "Cannot write to the file as KVSML format." );
            delete volume;
            return( false );
        }

        if ( arg.hasOption("verbose") )
        {
            std::cout << "KVS XML data format" << std::endl;
            kvsml->print( std::cout );
        }

        delete kvsml;
    }

    std::cout << "Output >> " << filename << std::endl;

    delete volume;

    return( 0 );
}
Esempio n. 19
0
void
test()
{
    std::complex<T> z(1, 0);
    assert(arg(z) == 0);
}
Esempio n. 20
0
int
main(int argc, char** argv)
{
	int exitCode = EXIT_SUCCESS;
	const char* openWith = NULL;

	char* progName = argv[0];
	if (strrchr(progName, '/'))
		progName = strrchr(progName, '/') + 1;

	if (argc < 2) {
		fprintf(stderr,"usage: %s <file[:line[:column]] or url or application "
			"signature> ...\n", progName);
	}

	while (*++argv) {
		status_t result = B_OK;
		argc--;

		BEntry entry(*argv);
		if ((result = entry.InitCheck()) == B_OK && entry.Exists()) {
			result = open_file(openWith, entry);
		} else if (!strncasecmp("application/", *argv, 12)) {
			// maybe it's an application-mimetype?

			// subsequent files are open with that app
			openWith = *argv;

			// in the case the app is already started, 
			// don't start it twice if we have other args
			BList teams;
			if (argc > 1)
				be_roster->GetAppList(*argv, &teams);

			if (teams.IsEmpty())
				result = be_roster->Launch(*argv);
			else
				result = B_OK;
		} else if (strchr(*argv, ':')) {
			// try to open it as an URI
			BUrl url(*argv);
			if (url.OpenWithPreferredApplication() == B_OK) {
				result = B_OK;
				continue;
			}

			// maybe it's "file:line" or "file:line:col"
			int line = 0, col = 0, i;
			result = B_ENTRY_NOT_FOUND;
			// remove gcc error's last :
			BString arg(*argv);
			if (arg[arg.Length() - 1] == ':')
				arg.Truncate(arg.Length() - 1);

			i = arg.FindLast(':');
			if (i > 0) {
				line = atoi(arg.String() + i + 1);
				arg.Truncate(i);

				result = entry.SetTo(arg.String());
				if (result == B_OK && entry.Exists()) {
					result = open_file(openWith, entry, line);
					if (result == B_OK)
						continue;
				}

				// get the column
				col = line;
				i = arg.FindLast(':');
				line = atoi(arg.String() + i + 1);
				arg.Truncate(i);

				result = entry.SetTo(arg.String());
				if (result == B_OK && entry.Exists())
					result = open_file(openWith, entry, line, col);
			}
		} else
			result = B_ENTRY_NOT_FOUND;

		if (result != B_OK && result != B_ALREADY_RUNNING) {
			fprintf(stderr, "%s: \"%s\": %s\n", progName, *argv,
				strerror(result));
			// make sure the shell knows this
			exitCode = EXIT_FAILURE;
		}
	}

	return exitCode;
}
Esempio n. 21
0
method_id("add");
  ret(ieval(begin_splat(),
     arg(1), op("+"), arg(2), 
  end_splat()));
  

comment("see http://jsfiddle.net/4MmvW/1/");
int main(int argc, char* argv[])
{

  FORMAT format = TEXT_OUT;
  int target = 0;
  std::string xsl;
  std::string ns;
  std::string fname;
  std::ofstream ofs;

  int i(1);
  while (i < argc)
    {
      std::string arg(argv[i]);
      std::string next_arg;
      if (i + 1 < argc) next_arg = argv[i + 1];
      else              next_arg = "";

      if (arg == "--text") { format = TEXT_OUT; break; }
      if (arg == "--xml")
	{
	  if (next_arg == "")
	    {
	      fname = argv[0];
	      fname += ".xml";
	    }
	  else
	    {
	      fname = next_arg;
	    }
	  format = XML_OUT;
	  ofs.open(fname.c_str());
	}
      if ( arg == "--compiler"  ) { format = COMPILER_OUT; break; }
      if ( arg == "--cerr"      ) { target = 1; break; }
      if ( arg == "--xsl"       )
	{
	  if (next_arg == "") xsl = "default.xsl"; 
	  else                xsl = next_arg;
	}
      if ( arg == "--namespace" )
	{
	  if (next_arg == "")
	    {
	      std::cerr << "no namespace specified" << std::endl;
	      exit(1); 
	    }
	  else
	    {
	      xsl = next_arg;
	    }
	}
      ++i;
    }
  CppUnit::TextUi::TestRunner runner;
  if ( ns.empty() )
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
  else
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry(ns).makeTest());
  CppUnit::Outputter* outputter = 0;
  std::ostream* stream = target ? &std::cerr : &std::cout;
  switch ( format )
    {
    case TEXT_OUT :
      outputter = new CppUnit::TextOutputter(&runner.result(),*stream);
      break;
    case XML_OUT :
      std::cout << "XML_OUT" << std::endl;
      outputter = new CppUnit::XmlOutputter(&runner.result(),
					    ofs, "shift_jis");
      static_cast<CppUnit::XmlOutputter*>(outputter)->setStyleSheet(xsl);
      break;
    case COMPILER_OUT :
      outputter = new CppUnit::CompilerOutputter(&runner.result(),*stream);
      break;
    }
  runner.setOutputter(outputter);
  runner.run();
  return 0; // runner.run() ? 0 : 1;
}
Esempio n. 23
0
/*===========================================================================*/
const bool Main::exec( void )
{
    // Parse specified arguments.
    ucd2kvsml::Argument arg( m_argc, m_argv );
    if( !arg.parse() ) return( false );

    // Set a input filename and a output filename.
    m_input_name = arg.inputFilename();
    m_output_name = arg.outputFilename( m_input_name );

    kvs::File file( m_input_name );
    if ( !file.isExisted() )
    {
        kvsMessageError("Input data file '%s' is not existed.",m_input_name.c_str());
        return( false );
    }

    // Read AVS UCD data file.
    kvs::AVSUcd* input = new kvs::AVSUcd( m_input_name );
    if ( !input )
    {
        kvsMessageError("Cannot allocate for the AVS UCD class.");
        return( false );
    }

    if ( input->isFailure() )
    {
        kvsMessageError("Cannot read a file %s.", m_input_name.c_str() );
        delete input;
        return( false );
    }

    // Import AVS UCD data as unstructured volume object.
    kvs::UnstructuredVolumeObject* object = new kvs::UnstructuredVolumeImporter( input );
    if ( !object )
    {
        kvsMessageError("Cannot import AVS UCD data.");
        delete input;
        return( false );
    }

    delete input;

    // Export the unstructured volume object to KVSML data (unstructured volume).
    kvs::KVSMLObjectUnstructuredVolume* output =
        new kvs::UnstructuredVolumeExporter<kvs::KVSMLObjectUnstructuredVolume>( object );
    if ( !output )
    {
        kvsMessageError("Cannot export unstructured volume object.");
        delete object;
        return( false );
    }

    delete object;

    // Set the writing data type.
    output->setWritingDataType( arg.writingDataType() );

    // Write to KVSML data file.
    if ( !output->write( m_output_name ) )
    {
        kvsMessageError("Cannot write to KVSML data file %s.", m_output_name.c_str() );
        delete output;
        return( false );
    }

    delete output;

    return( true );
}
Esempio n. 24
0
// 
// Handle command line arguments
//
void parseCorrectOptions(int argc, char** argv)
{
    std::string algo_str;
    bool bDiscardReads = false;
    bool die = false;
    for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) 
    {
        std::istringstream arg(optarg != NULL ? optarg : "");
        switch (c) 
        {
            case 'm': arg >> opt::minOverlap; break;
            case 'p': arg >> opt::prefix; break;
            case 'o': arg >> opt::outFile; break;
            case 'e': arg >> opt::errorRate; break;
            case 't': arg >> opt::numThreads; break;
            case 'l': arg >> opt::seedLength; break;
            case 's': arg >> opt::seedStride; break;
            case 'r': arg >> opt::numOverlapRounds; break;
            case 'a': arg >> algo_str; break;
            case 'd': arg >> opt::sampleRate; break;
            case 'c': arg >> opt::conflictCutoff; break;
            case 'k': arg >> opt::kmerLength; break;
            case 'x': arg >> opt::kmerThreshold; break;
            case '?': die = true; break;
            case 'v': opt::verbose++; break;
            case 'b': arg >> opt::branchCutoff; break;
            case 'i': arg >> opt::numKmerRounds; break;
            case OPT_LEARN: opt::bLearnKmerParams = true; break;
            case OPT_DISCARD: bDiscardReads = true; break;
            case OPT_METRICS: arg >> opt::metricsFile; break;
            case OPT_HELP:
                std::cout << CORRECT_USAGE_MESSAGE;
                exit(EXIT_SUCCESS);
            case OPT_VERSION:
                std::cout << CORRECT_VERSION_MESSAGE;
                exit(EXIT_SUCCESS);
        }
    }

    if (argc - optind < 1) 
    {
        std::cerr << SUBPROGRAM ": missing arguments\n";
        die = true;
    } 
    else if (argc - optind > 1) 
    {
        std::cerr << SUBPROGRAM ": too many arguments\n";
        die = true;
    }

    if(opt::numThreads <= 0)
    {
        std::cerr << SUBPROGRAM ": invalid number of threads: " << opt::numThreads << "\n";
        die = true;
    }

    if(opt::numOverlapRounds <= 0)
    {
        std::cerr << SUBPROGRAM ": invalid number of overlap rounds: " << opt::numOverlapRounds << ", must be at least 1\n";
        die = true;
    }
    
    if(opt::numKmerRounds <= 0)
    {
        std::cerr << SUBPROGRAM ": invalid number of kmer rounds: " << opt::numKmerRounds << ", must be at least 1\n";
        die = true;
    }

    if(opt::kmerLength <= 0)
    {
        std::cerr << SUBPROGRAM ": invalid kmer length: " << opt::kmerLength << ", must be greater than zero\n";
        die = true;
    }

    if(opt::kmerThreshold <= 0)
    {
        std::cerr << SUBPROGRAM ": invalid kmer threshold: " << opt::kmerThreshold << ", must be greater than zero\n";
        die = true;
    }

    // Determine the correction algorithm to use
    if(!algo_str.empty())
    {
        if(algo_str == "hybrid")
            opt::algorithm = ECA_HYBRID;
        else if(algo_str == "kmer")
            opt::algorithm = ECA_KMER;
        else if(algo_str == "overlap")
            opt::algorithm = ECA_OVERLAP;
        else
        {
            std::cerr << SUBPROGRAM << ": unrecognized -a,--algorithm parameter: " << algo_str << "\n";
            die = true;
        }
    }

    if (die) 
    {
        std::cout << "\n" << CORRECT_USAGE_MESSAGE;
        exit(EXIT_FAILURE);
    }

    // Validate parameters
    if(opt::errorRate <= 0)
        opt::errorRate = 0.0f;

    if(opt::errorRate > 1.0f)
    {
        std::cerr << "Invalid error-rate parameter: " << opt::errorRate << "\n";
        exit(EXIT_FAILURE);
    }

    if(opt::seedLength < 0)
        opt::seedLength = 0;

    if(opt::seedLength > 0 && opt::seedStride <= 0)
        opt::seedStride = opt::seedLength;

    // Parse the input filenames
    opt::readsFile = argv[optind++];

    if(opt::prefix.empty())
    {
        opt::prefix = stripFilename(opt::readsFile);
    }

    // Set the correction threshold
    if(opt::kmerThreshold <= 0)
    {
        std::cerr << "Invalid kmer support threshold: " << opt::kmerThreshold << "\n";
        exit(EXIT_FAILURE);
    }
    CorrectionThresholds::Instance().setBaseMinSupport(opt::kmerThreshold);

    std::string out_prefix = stripFilename(opt::readsFile);
    if(opt::outFile.empty())
    {
        opt::outFile = out_prefix + ".ec.fa";
    }

    if(bDiscardReads)
    {
        opt::discardFile = out_prefix + ".discard.fa";
    }
    else
    {
        opt::discardFile.clear();
    }
}
bool GrStrokePathRenderer::onDrawPath(const SkPath& origPath,
                                      const SkStrokeRec& stroke,
                                      GrDrawTarget* target,
                                      bool antiAlias) {
    if (origPath.isEmpty()) {
        return true;
    }

    SkScalar width = stroke.getWidth();
    if (width <= 0) {
        return false;
    }

    // Get the join type
    SkPaint::Join join = stroke.getJoin();
    SkScalar miterLimit = stroke.getMiter();
    SkScalar sqMiterLimit = SkScalarMul(miterLimit, miterLimit);
    if ((join == SkPaint::kMiter_Join) && (miterLimit <= SK_Scalar1)) {
        // If the miter limit is small, treat it as a bevel join
        join = SkPaint::kBevel_Join;
    }
    const bool isMiter       = (join == SkPaint::kMiter_Join);
    const bool isBevel       = (join == SkPaint::kBevel_Join);
    SkScalar invMiterLimit   = isMiter ? SK_Scalar1 / miterLimit : 0;
    SkScalar invMiterLimitSq = SkScalarMul(invMiterLimit, invMiterLimit);

    // Allocate vertices
    const int nbQuads     = origPath.countPoints() + 1; // Could be "-1" if path is not closed
    const int extraVerts  = isMiter || isBevel ? 1 : 0;
    const int maxVertexCount = nbQuads * (4 + extraVerts);
    const int maxIndexCount  = nbQuads * (6 + extraVerts * 3); // Each extra vert adds a triangle
    target->drawState()->setDefaultVertexAttribs();
    GrDrawTarget::AutoReleaseGeometry arg(target, maxVertexCount, maxIndexCount);
    if (!arg.succeeded()) {
        return false;
    }
    SkPoint* verts = reinterpret_cast<SkPoint*>(arg.vertices());
    uint16_t* idxs = reinterpret_cast<uint16_t*>(arg.indices());
    int vCount = 0, iCount = 0;

    // Transform the path into a list of triangles
    SkPath::Iter iter(origPath, false);
    SkPoint pts[4];
    const SkScalar radius = SkScalarMul(width, 0.5f);
    SkPoint *firstPt = verts, *lastPt = NULL;
    SkVector firstDir, dir;
    firstDir.set(0, 0);
    dir.set(0, 0);
    bool isOpen = true;
    for(SkPath::Verb v = iter.next(pts); v != SkPath::kDone_Verb; v = iter.next(pts)) {
        switch(v) {
            case SkPath::kMove_Verb:
                // This will already be handled as pts[0] of the 1st line
                break;
            case SkPath::kClose_Verb:
                isOpen = (lastPt == NULL);
                break;
            case SkPath::kLine_Verb:
            {
                SkVector v0 = dir;
                dir = pts[1] - pts[0];
                if (dir.setLength(radius)) {
                    SkVector dirT;
                    dirT.set(dir.fY, -dir.fX); // Get perpendicular direction
                    SkPoint l1a = pts[0]+dirT, l1b = pts[1]+dirT,
                            l2a = pts[0]-dirT, l2b = pts[1]-dirT;
                    SkPoint miterPt[2];
                    bool useMiterPoint = false;
                    int idx0(-1), idx1(-1);
                    if (NULL == lastPt) {
                        firstDir = dir;
                    } else {
                        SkVector v1 = dir;
                        if (v0.normalize() && v1.normalize()) {
                            SkScalar dotProd = v0.dot(v1);
                            // No need for bevel or miter join if the angle
                            // is either 0 or 180 degrees
                            if (!SkScalarNearlyZero(dotProd + SK_Scalar1) &&
                                !SkScalarNearlyZero(dotProd - SK_Scalar1)) {
                                bool ccw = !is_clockwise(v0, v1);
                                int offset = ccw ? 1 : 0;
                                idx0 = vCount-2+offset;
                                idx1 = vCount+offset;
                                const SkPoint* pt0 = &(lastPt[offset]);
                                const SkPoint* pt1 = ccw ? &l2a : &l1a;
                                switch(join) {
                                    case SkPaint::kMiter_Join:
                                    {
                                        // *Note : Logic is from MiterJoiner

                                        // FIXME : Special case if we have a right angle ?
                                        // if (SkScalarNearlyZero(dotProd)) {...}

                                        SkScalar sinHalfAngleSq =
                                                SkScalarHalf(SK_Scalar1 + dotProd);
                                        if (sinHalfAngleSq >= invMiterLimitSq) {
                                            // Find the miter point (or points if it is further
                                            // than the miter limit)
                                            const SkPoint pt2 = *pt0+v0, pt3 = *pt1+v1;
                                            if (intersection(*pt0, pt2, *pt1, pt3, miterPt[0]) !=
                                                kNone_IntersectionType) {
                                                SkPoint miterPt0 = miterPt[0] - *pt0;
                                                SkPoint miterPt1 = miterPt[0] - *pt1;
                                                SkScalar sqDist0 = miterPt0.dot(miterPt0);
                                                SkScalar sqDist1 = miterPt1.dot(miterPt1);
                                                const SkScalar rSq =
                                                        SkScalarDiv(SkScalarMul(radius, radius),
                                                                    sinHalfAngleSq);
                                                const SkScalar sqRLimit =
                                                        SkScalarMul(sqMiterLimit, rSq);
                                                if (sqDist0 > sqRLimit || sqDist1 > sqRLimit) {
                                                    if (sqDist1 > sqRLimit) {
                                                        v1.setLength(SkScalarSqrt(sqRLimit));
                                                        miterPt[1] = *pt1+v1;
                                                    } else {
                                                        miterPt[1] = miterPt[0];
                                                    }
                                                    if (sqDist0 > sqRLimit) {
                                                        v0.setLength(SkScalarSqrt(sqRLimit));
                                                        miterPt[0] = *pt0+v0;
                                                    }
                                                } else {
                                                    miterPt[1] = miterPt[0];
                                                }
                                                useMiterPoint = true;
                                            }
                                        }
                                        if (useMiterPoint && (miterPt[1] == miterPt[0])) {
                                            break;
                                        }
                                    }
                                    default:
                                    case SkPaint::kBevel_Join:
                                    {
                                        // Note : This currently causes some overdraw where both
                                        //        lines initially intersect. We'd need to add
                                        //        another line intersection check here if the
                                        //        overdraw becomes an issue instead of using the
                                        //        current point directly.

                                        // Add center point
                                        *verts++ = pts[0]; // Use current point directly
                                        // This idx is passed the current point so increment it
                                        ++idx1;
                                        // Add center triangle
                                        *idxs++ = idx0;
                                        *idxs++ = vCount;
                                        *idxs++ = idx1;
                                        vCount++;
                                        iCount += 3;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    *verts++ = l1a;
                    *verts++ = l2a;
                    lastPt   = verts;
                    *verts++ = l1b;
                    *verts++ = l2b;

                    if (useMiterPoint && (idx0 >= 0) && (idx1 >= 0)) {
                        firstPt[idx0] = miterPt[0];
                        firstPt[idx1] = miterPt[1];
                    }

                    // 1st triangle
                    *idxs++  = vCount+0;
                    *idxs++  = vCount+2;
                    *idxs++  = vCount+1;
                    // 2nd triangle
                    *idxs++  = vCount+1;
                    *idxs++  = vCount+2;
                    *idxs++  = vCount+3;

                    vCount += 4;
                    iCount += 6;
                }
            }
                break;
            case SkPath::kQuad_Verb:
            case SkPath::kCubic_Verb:
                SkDEBUGFAIL("Curves not supported!");
            default:
                // Unhandled cases
                SkASSERT(false);
        }
    }

    if (isOpen) {
        // Add caps
        switch (stroke.getCap()) {
            case SkPaint::kSquare_Cap:
                firstPt[0] -= firstDir;
                firstPt[1] -= firstDir;
                lastPt [0] += dir;
                lastPt [1] += dir;
                break;
            case SkPaint::kRound_Cap:
                SkDEBUGFAIL("Round caps not supported!");
            default: // No cap
                break;
        }
    }

    SkASSERT(vCount <= maxVertexCount);
    SkASSERT(iCount <= maxIndexCount);

    if (vCount > 0) {
        target->drawIndexed(kTriangles_GrPrimitiveType,
                            0,        // start vertex
                            0,        // start index
                            vCount,
                            iCount);
    }

    return true;
}
Esempio n. 26
0
int main(int argc, const char *argv[])
{
	std::stringstream oss;
	rexjson::value v = rexjson::object();
	g_args.add_specs(g_argspec, sizeof(g_argspec)/sizeof(*g_argspec));

	try {
		g_args.parse_command_line(argc, argv);
	} catch (std::exception& e) {
		std::cout << "Incorect command line, got error: " << e.what() << std::endl;
		return 1;
	}
	if (!g_args.get_value("help").empty()) {
		help(argc, argv);
		return 0;
	}

	try {
		rexjson::value cfg = rexjson::object();
		cfg["bitstamp-key"] = "none";
		cfg["bitstamp-user"] = "none";
		cfg["bitstamp-secret"] = "none";
		if (!g_args.get_value("config").empty()) {
			std::ifstream ifs(g_args.get_value("config"));
			std::stringstream buffer;
			buffer << ifs.rdbuf();
			cfg.read(buffer.str());
		}
		if (!g_args.get_value("bitstamp-key").empty())
			cfg["bitstamp-key"] = g_args.get_value("bitstamp-key");
		if (!g_args.get_value("bitstamp-user").empty())
			cfg["bitstamp-user"] = g_args.get_value("bitstamp-user");
		if (!g_args.get_value("bitstamp-secret").empty())
			cfg["bitstamp-secret"] = g_args.get_value("bitstamp-secret");
		bitstamp::api api(cfg["bitstamp-key"].get_str(), cfg["bitstamp-user"].get_str(), cfg["bitstamp-secret"].get_str());
		for (int i = 1; i < argc; i++) {
			std::string arg(argv[i]);
			if (arg[0] == '-')
				continue;
			if (arg == "ticker") {
				std::cout << rexjson::read(api.ticker()).write(true) << std::endl;
				break;
			}else if (arg == "orderbook") {
				std::cout << rexjson::read(api.order_book()).write(true) << std::endl;
				break;
			}else if (arg == "withdrawals") {
				std::cout << rexjson::read(api.withdrawal_requests()).write(true) << std::endl;
				break;
			} else if (arg == "balance") {
				std::cout << rexjson::read(api.balance()).write(true) << std::endl;
				break;
			} else if (arg == "unconfirmed") {
				std::cout << rexjson::read(api.unconfirmed_btc()).write(true) << std::endl;
				break;
			} else if (arg == "orders") {
				std::cout << rexjson::read(api.orders()).write(true) << std::endl;
				break;
			} else if (arg == "btcaddress") {
				std::cout << rexjson::read(api.bitcoin_deposit_address()).write(true) << std::endl;
				break;
			} else if (arg == "transactions") {
				std::string offset = g_args.get_value("offset", "0");
				std::string limit = g_args.get_value("limit", "1");
				std::string sort = g_args.get_value("sort", "desc");
				std::cout << rexjson::read(api.transactions(offset, limit, sort)).write(true) << std::endl;
				break;
			} else if (arg == "withdrawbtc") {
				std::string amount = g_args.get_value("amount");
				std::string address = g_args.get_value("address");
				if (amount.empty() || address.empty()) {
					std::cout << "Invalid BTC withdrawal parameters" << std::endl;
					return 1;
				}
				std::cout << rexjson::read(api.bitcoin_withdrawal(amount, address)).write(true) << std::endl;
				break;
			} else if (arg == "buy") {
				std::string amount = g_args.get_value("amount");
				std::string price = g_args.get_value("price");
				if (amount.empty() || price.empty()) {
					std::cout << "Invalid order parameters" << std::endl;
					return 1;
				}
				std::cout << rexjson::read(api.buy(amount, price)).write(true) << std::endl;
				break;
			} else if (arg == "sell") {
				std::string amount = g_args.get_value("amount");
				std::string price = g_args.get_value("price");
				if (amount.empty() || price.empty()) {
					std::cout << "Invalid order parameters" << std::endl;
					return 1;
				}
				std::cout << rexjson::read(api.sell(amount, price)).write(true) << std::endl;
				break;
			} else if (arg == "cancel") {
				std::string order = g_args.get_value("order");
				if (order.empty()) {
					std::cout << "Invalid order parameters" << std::endl;
					return 1;
				}
				std::cout << rexjson::read(api.cancel(order)).write(true) << std::endl;
				break;
			} else if (arg == "help") {
				help(argc, argv);
				break;
			} else {
				std::cout << arg << " is invalid command" << std::endl;
				break;
			}
		}
		return 0;
	} catch (std::exception & e) {
		std::cout << e.what() << std::endl;
	}
	return 0;
}
Esempio n. 27
0
// Prepares interpolator instance, e.g. setups spline object.
void interpolator::prepare (int interpol, int repitition, int domain) {
  interpolType = interpol;
  dataType |= (domain & DATA_MASK_DOMAIN);
  repeat = repitition;

  // preparations for cyclic interpolations
  if (repeat & REPEAT_YES) {
    duration = rx[length - 1] - rx[0];
    // set first value to the end of the value vector
    if (cy) cy[length - 1] = cy[0];
    if (ry) ry[length - 1] = ry[0];
  }

  // preparations for polar complex data
  if (cy != NULL && (domain & DATA_POLAR) && length > 1) {
    // unwrap phase of complex data vector
    vector ang = vector (length);
    for (int i = 0; i < length; i++) ang (i) = arg (cy[i]);
    ang = unwrap (ang);
    // store complex data
    for (int i = 0; i < length; i++) {
      cy[i] = nr_complex_t (abs (cy[i]), real (ang (i)));
    }
  }

  // preparations spline interpolations
  if (interpolType & INTERPOL_CUBIC) {

    // prepare complex vector interpolation using splines
    if (cy != NULL) {
      // create splines if necessary
      if (rsp) delete rsp;
      if (isp) delete isp;
      rsp = new spline (SPLINE_BC_NATURAL);
      isp = new spline (SPLINE_BC_NATURAL);
      if (repeat & REPEAT_YES) {
	rsp->setBoundary (SPLINE_BC_PERIODIC);
	isp->setBoundary (SPLINE_BC_PERIODIC);
      }
      // prepare data vectors
      vector rv = vector (length);
      vector iv = vector (length);
      vector rt = vector (length);
      for (int i = 0; i < length; i++) {
	rv (i) = real (cy[i]);
	iv (i) = imag (cy[i]);
	rt (i) = rx[i];
      }
      // pass data vectors to splines and construct these
      rsp->vectors (rv, rt);
      isp->vectors (iv, rt);
      rsp->construct ();
      isp->construct ();
    }

    // prepare real vector interpolation using spline
    else {
      if (rsp) delete rsp;
      rsp = new spline (SPLINE_BC_NATURAL);
      if (repeat & REPEAT_YES) rsp->setBoundary (SPLINE_BC_PERIODIC);
      rsp->vectors (ry, rx, length);
      rsp->construct ();
    }
  }
}
Esempio n. 28
0
File: utils.cpp Progetto: dotse/bbk
bool parseArgs(int argc, char *argv[],
               TaskConfig &client_cfg, TaskConfig &agent_cfg) {

    CliMode mode = CliMode::NONE;

    client_cfg.set("port", "80");
    client_cfg.set("mtype", "ipv4");
    client_cfg.set("listen_addr", "127.0.0.1");

    agent_cfg.add("Measure.Webserver", "frontend.bredbandskollen.se");
    agent_cfg.add("Measure.SettingsUrl", "/api/servers");
    agent_cfg.add("Measure.ContentsUrl", "/api/content");
    agent_cfg.add("Measure.MeasurementsUrl", "/api/measurements");

    for (int i=1; i<argc; ++i) {
        std::string arg(argv[i]);
        if (arg == "--v6")
            client_cfg.set("mtype", "ipv6");
        else if (arg == "--test") {
            mode = (mode == CliMode::NONE) ? CliMode::TEST : CliMode::IN_ERROR;
        } else if (arg == "--live") {
            mode = (mode == CliMode::NONE) ? CliMode::LIVE : CliMode::IN_ERROR;
        } else if (arg == "--version") {
            std::cout << measurement::appName << ' '
                      << measurement::appVersion << '\n';
            return false;
        } else if (arg == "--quiet") {
            client_cfg.set("quiet", "1");
        } else if (arg == "--local") {
            mode = (mode == CliMode::NONE) ? CliMode::LOCAL : CliMode::IN_ERROR;
#if defined(RUN_SERVER)
        } else if (arg == "--run-server") {
            mode = (mode == CliMode::NONE) ? CliMode::SERVER : CliMode::IN_ERROR;
#endif
        } else if (arg.substr(0, 11) == "--duration=")
            agent_cfg.set("Measure.LoadDuration",  argv[i]+11);
        else if (arg.substr(0, 13) == "--speedlimit=")
            agent_cfg.set("Measure.SpeedLimit", argv[i]+13);
        else if (arg.substr(0, 6) == "--out=")
            client_cfg.set("out", argv[i]+6);
        else if (arg.substr(0, 6) == "--dir=")
            client_cfg.set("app_dir", (argv[i]+6) + pathSep);
        else if (arg.substr(0, 6) == "--log=")
            client_cfg.set("logfile", argv[i]+6);
        else if (arg.substr(0, 11) == "--local-ip=")
            agent_cfg.set("Measure.LocalAddress", argv[i]+11);
        else if (arg.substr(0, 9) == "--server=")
            client_cfg.set("server", argv[i]+9);
        else if (arg.substr(0, 7) == "--port=")
            client_cfg.set("port", argv[i]+7);
        else if (arg.substr(0, 9) == "--listen=")
            client_cfg.set("listen", argv[i]+9);
        else if (arg.substr(0, 14) == "--listen-addr=")
            client_cfg.set("listen_addr", argv[i]+14);
        else if (arg.substr(0, 12) == "--listen-pw=") {
            client_cfg.set("listen_pw", argv[i]+12);
#ifdef USE_GNUTLS
        } else if (arg == "--ssl") {
            agent_cfg.set("Measure.TLS", "1");
            client_cfg.set("ssl", "1");
            if (client_cfg.value("port") == "80")
                client_cfg.set("port", "443");
#endif
        } else if (arg.substr(0, 9) == "--fakeip=")
            agent_cfg.set("Client.fakeip", argv[i]+9);
        else if (arg == "--check-servers")
            client_cfg.set("pingsweep", "1");
        else if (arg.substr(0, 14) == "--measurements")
            client_cfg.set("list_measurements",
                (arg.size() > 15 && arg[14] == '=') ? argv[i]+15 : "10");
        else if (arg.substr(0, 10) == "--from-id=") {
            client_cfg.set("list_from", argv[i]+10);
            if (client_cfg.value("list_measurements").empty())
                client_cfg.set("list_measurements", "10");
        } else if (arg == "--browser") {
            client_cfg.set("browser", "1");
            if (client_cfg.value("listen").empty())
                client_cfg.set("listen", "0"); // Use any avaliable port
        } else if (arg.substr(0, 13) == "--proxy-host=")
            agent_cfg.set("Measure.ProxyServerUrl", argv[i]+13);
        else if (arg.substr(0, 13) == "--proxy-port=")
            agent_cfg.set("Measure.ProxyServerPort", argv[i]+13);
        else {
            int status = 0;
            if (arg != "--help") {
                status = 1;
                std::cerr << argv[0] << ": invalid argument -- " << arg << std::endl;
            }
            std::ostream &fh = status ? std::cerr : std::cout;
            fh << "Usage: " << argv[0] << " [OPTION]...\n\nOptions:\n\n"
                  "  --help              Show this help text\n"
                  "  --version           Print version number and exit\n"
               << "\nNetwork related options:\n"
#ifndef BBK_WEBVIEW
               << "  --v6                Prefer IPv6 (default is IPv4)\n"
#endif
#ifdef __linux__
#else
               << "  --local-ip=IP       Measure using existing local ip address IP\n"
               << "                      Note: this will not work on all platforms\n"
#endif
               << "  --proxy-host=HOST   Use HTTP proxy server HOST\n"
               << "  --proxy-port=PORT   Use port PORT on proxy server (default 80)\n"
               << "\nMeasurement configuration:\n"
#ifndef BBK_WEBVIEW
               << "  --server=HOST       Use HOST as measurement server\n"
               << "  --port=N            Port number for measurement server, default 80\n"
#endif
#ifdef USE_GNUTLS
               << "  --ssl               Measure using transport layer security (default port 443)\n"
#endif
               << "  --duration=N        Measure upload/download for N seconds (2-10, default 10)\n"
               << "  --speedlimit=N      Keep upload/download speed below N mbps on average\n"
               << "\nMeasurement type:\n"
               << "  --live              Measure using Bredbandskollen's live servers (default)\n"
               << "  --test              Measure using Bredbandskollen's development servers\n"
#ifndef BBK_WEBVIEW
               << "  --local             Don't fetch configuration (server list) from bredbandskollen.se,\n"
               << "                      communicate only with server given by the --server option.\n"
#endif
#if defined(RUN_SERVER)
               << "  --run-server        Run as a measurement server (requires option --listen=PORT)\n"
#endif
               << "\nLogging:\n"
               << "  --log=FILENAME      Write debug log to FILENAME\n"
               << "                      (log to stderr if FILENAME is -)\n"
#ifndef BBK_WEBVIEW
               << "\nFinding measurement servers:\n"
               << "  --check-servers     Find closest measurement server\n"
               << "\nList previous measurements:\n"
               << "  --measurements      List 10 last measurements\n"
               << "  --measurements=N    List N last measurements\n"
               << "                      If --quiet, output will be JSON. Otherwise\n"
               << "                      output will be lines with tab separated fields.\n"
               << "  --from-id=N         List only measurements before ID N\n"
               << "\nBrowser interface:\n"
               << "  --browser           Use a web browser as interface\n"
               << "  --listen=PORT       Use web browser as interface;\n"
               << "                      the browser must connect to the given PORT\n"
               << "  --listen-addr=IP    When listening, bind socket to ip address IP\n"
               << "                      (default is 127.0.0.1) to use a web browser on\n"
               << "                      a remote host as interface\n"
               << "                      Note: this may not work due to e.g. firewalls.\n"
               << "                      Don't use it unless you know what you are doing.\n"
               << "  --listen-pw=PW      Use PW as a one-time password when connecting from browser\n"
               << "                      Note: DO NOT reuse a sensitive password here!\n"
               << "                      It is better to omit this option because by default\n"
               << "                      a secure one-time password will be generated.\n"
               << "\nCommand line interface:\n"
               << "  --quiet             Write a single line of output\n"
               << "  --out=FILENAME      Append output to FILENAME instead of stdout\n"
#endif
               << std::endl;
            return false;
        }
    }

    client_cfg.set("app_dir", createAndGetAppDir(client_cfg.value("app_dir")));

    if (client_cfg.value("local") == "1" && client_cfg.value("server").empty()) {
        std::cerr << "missing --server option" << std::endl;
        return false;
    }

    std::vector<std::string> pdir = { "listen", "port" };
    for (auto &str : pdir)
        if (!client_cfg.value(str).empty()) {
            auto port = client_cfg.value(str);
            if (port.find_first_not_of("0123456789") != std::string::npos ||
                port.size() > 5 || std::stod(port) > 65535) {
                std::cerr << "invalid port number" << std::endl;
                return false;
            }
        }

    switch (mode) {
    case CliMode::NONE:
    case CliMode::LIVE:
        agent_cfg.set("Measure.Webserver", "frontend.bredbandskollen.se");
        break;
    case CliMode::TEST:
        agent_cfg.set("Measure.Webserver", "beta4.bredbandskollen.se");
        break;
    case CliMode::LOCAL:
        client_cfg.set("local", "1");
        agent_cfg.set("Measure.Webserver", "none");
        break;
#if defined(RUN_SERVER)
    case CliMode::SERVER:
        client_cfg.set("local", "1");
        client_cfg.set("run_server", "1");
        if (client_cfg.value("listen").empty()) {
            std::cerr << "option --listen is required with --run-server"
                      << std::endl;
            return false;
        }
        break;
#endif
    case CliMode::IN_ERROR:
        std::cerr << "can have only one of options --live, --test,";
#if defined(RUN_SERVER)
        std::cerr << " --run-server,";
#endif
        std::cerr << " and --local";
        return false;
    };

    if (!client_cfg.value("listen").empty() &&
        client_cfg.value("listen_pw").empty()) {
        // Generate one-time password
        uint32_t src[2];
        std::random_device rng;
        std::uniform_int_distribution<uint32_t> dist;
        src[0] = dist(rng);
        src[1] = dist(rng);
        char pwd[sizeof(src)*2];
        base64_encode(reinterpret_cast<const unsigned char *>(src),
                      sizeof(src), pwd);
        client_cfg.add("listen_pw", std::string(pwd, sizeof(src)*4/3));
    }
    client_cfg.add("url", "http://" + agent_cfg.value("Measure.Webserver") +
                   "/standalone/dev/index.php");

    if (client_cfg.value("logfile").empty()) {
#if defined(RUN_SERVER)
        if (mode == CliMode::SERVER)
            client_cfg.add("logfile", client_cfg.value("app_dir") + "server_log");
        else
#endif
            client_cfg.add("logfile", client_cfg.value("app_dir") + "last_log");
    }
    client_cfg.set("config_file", client_cfg.value("app_dir") + "config");

    // Default to ipv6 if user wants to use a local ipv6 address
    if (agent_cfg.value("Measure.LocalAddress").find(':') != std::string::npos)
        client_cfg.set("mtype", "ipv6");

    agent_cfg.add("Measure.AutoSaveReport",
                  client_cfg.value("listen").empty() ? "false" : "true");

    agent_cfg.add("Measure.IpType", client_cfg.value("mtype"));

    agent_cfg.add("Client.appname", measurement::appName);
    agent_cfg.add("Client.appver", measurement::appVersion);
    agent_cfg.add("Client.machine", measurement::hw_info);
    agent_cfg.add("Client.system", measurement::os_version);
    agent_cfg.add("Client.language", "en");

    return true;
}
Esempio n. 29
0
void SysConf::GetSiteNf(vector<double> & NSiteCount,vector<double> & Ncount,vector<double> & Ndimer,vector<double> & MeanSublattice,vector<complex<double> >& complexPhaseVector,vector<double>& realPhaseVector,complex<double>& complexPhase,double& realPhase)
{
	// ---> Dimensions
	//      Ncount		: 4
	//	NSiteCount	: L
	//	MeanDimer	: L * NbOfNeights

	int test_Ncount = 0;
	int N3Count = 0;

	int index = 0;

	int spinPos = 0;
	int neighPos = 0;

	int spinValue = 0;
	int neighValue = 0;

	// Reset vectors
	for(int iii = 0; iii < 4; ++iii)
	{
		Ncount[iii] = 0;
	}

	for(int iii = 0; iii < L; ++iii)
	{
		NSiteCount[iii] = 0;
		for(int jjj = 0; jjj < NbOfNeights; ++jjj)
		{
			Ndimer[idxConv(NbOfNeights,iii,jjj)] = 0;
		}
	}

	for(int nnn = 0; nnn < N; ++nnn)
	{
		for(int lll = 0; lll < L; ++lll)
		{
			// Count the number of dimers
			test_Ncount	= 0;
			spinPos 	= idxConv(N,lll,nnn);
			spinValue 	= (int)spinConf[spinPos];

			if(spinValue!=0)
			{
				for(int iii = 0; iii < NbOfNeights;++iii)
				{
					index 		= idxConv(NbOfNeights,lll,iii);
					neighPos	= idxConv(N,neighboursTable[index],nnn);

				#if BORDER_TYPE == 4
				// ANTI-PERIODIC BORDERS
					neighValue	= weightTable[index]*(int)spinConf[neighPos];
				#else
					neighValue	= (int)spinConf[neighPos];
				#endif

					if(neighValue==spinValue)
					{
						++test_Ncount;
						Ndimer[index] += 1./N;
					}
				}

				DimerDensityProfile[spinPos] = test_Ncount;
				Ncount[test_Ncount] 	+= 1./N;
				NSiteCount[lll]		+= (double)test_Ncount/N;

				if(test_Ncount==3)
				{
					N3_Map[N3Count] = spinPos;
					++N3Count;
				}
			}
		}
	}

	if(SimType.compare("Moessner")==0||SimType.compare("Manual")==0)
	{
		GetSublattice(MeanSublattice,NSiteCount);
	}

	// Calculate the plaquette and columnar indexes
	int Sub0Value = 0;
	int Sub1Value = 0;
	int spinNeigh1 = 0;
	int spinNeigh0 = 0;
	int index0 = 0;
	int index1 = 0;

	for(int iii = 0; iii < N; ++iii)
	{
		complexPhaseVector[iii] = 0;
	}
	int chosenSublattice = -1;

	int lll = 0;
	int nnn = 0;
	for(int iii = 0; iii < N3Count; ++iii)
	{
		spinPos = N3_Map[iii];
		lll = spinPos/N;
		nnn = spinPos%N;

		// Complex phase
		chosenSublattice = SublatticePositions[lll];
		complexPhaseVector[nnn] += Jindex[chosenSublattice];
	}

	complexPhase = complexPhase/((double)N*L);
	realPhase = cos(3*arg(complexPhase));

	complexPhase = 0.;
	for(int iii = 0; iii < N; ++iii)
	{
		complexPhaseVector[iii] = complexPhaseVector[iii]/((double)L);
		realPhaseVector[iii] = cos(3*arg(complexPhaseVector[iii]));
		complexPhase += complexPhaseVector[iii];
	}
	complexPhase = complexPhase/((double)N);
	realPhase = cos(3*arg(complexPhase));
}
Esempio n. 30
0
// ----- M A I N ---------------------------------------------------------------
int main(int argc, char** argv) {
  SetWorldSilent(true); // No STDOUT output from cpptraj routines.
  std::string topname, crdname, title, bres, pqr, sybyltype, writeconect;
  std::string aatm(" pdbatom"), ter_opt(" terbyres"), box(" sg \"P 1\"");
  TrajectoryFile::TrajFormatType fmt = TrajectoryFile::PDBFILE;
  bool ctr_origin = false;
  bool useExtendedInfo = false;
  int res_offset = 0;
  int debug = 0;
  int numSoloArgs = 0;
  for (int i = 1; i < argc; ++i) {
    std::string arg( argv[i] );
    if (arg == "-p" && i+1 != argc && topname.empty()) // Topology
      topname = std::string( argv[++i] );
    else if (arg == "-c" && i+1 != argc && crdname.empty()) // Coords
      crdname = std::string( argv[++i] );
    else if (arg == "-tit" && i+1 != argc && title.empty()) // Title
      title = " title " + std::string( argv[++i] );
    else if (arg == "-offset" && i+1 != argc) // Residue # offset
      res_offset = convertToInteger( argv[++i] );
    else if ((arg == "-d" || arg == "--debug") && i+1 != argc) // Debug level
      debug = convertToInteger( argv[++i] );
    else if (arg == "-h" || arg == "--help") { // Help
      Help(argv[0], true);
      return 0;
    } else if (arg == "-v" || arg == "--version") { // Version info
      WriteVersion();
      return 0;
    } else if (arg == "-aatm") // Amber atom names, include extra pts
      aatm.assign(" include_ep");
    else if (arg == "-sybyl") // Amber atom types to SYBYL
      sybyltype.assign(" sybyltype");
    else if (arg == "-conect") // Write CONECT records from bond info
      writeconect.assign(" conect");
    else if (arg == "-ep") // PDB atom names, include extra pts
      aatm.append(" include_ep");
    else if (arg == "-bres") // PDB residue names
      bres.assign(" pdbres");
    else if (arg == "-ext") // Use extended PDB info from Topology
      useExtendedInfo = true;
    else if (arg == "-ctr")  // Center on origin
      ctr_origin = true;
    else if (arg == "-noter") // No TER cards
      ter_opt.assign(" noter");
    else if (arg == "-nobox") // No CRYST1 record
      box.assign(" nobox");
    else if (arg == "-pqr") { // Charge/Radii in occ/bfactor cols
      pqr.assign(" dumpq");
      ++numSoloArgs;
    } else if (arg == "-mol2") { // output as mol2
      fmt = TrajectoryFile::MOL2FILE;
      ++numSoloArgs;
    } else if (Unsupported(arg)) {
      mprinterr("Error: Option '%s' is not yet supported.\n\n", arg.c_str());
      return 1;
    } else {
      mprinterr("Error: Unrecognized option '%s'\n", arg.c_str());
      Help(argv[0], false);
      return 1;
    }
  }
  if (debug > 0) WriteVersion();
  // Check command line for errors.
  if (topname.empty()) topname.assign("prmtop");
  if (debug > 0 && crdname.empty())
    mprinterr("| Reading Amber restart from STDIN\n");
  if (numSoloArgs > 1) {
    mprinterr("Error: Only one alternate output format option may be specified (found %i)\n",
              numSoloArgs);
    Help(argv[0], true);
    return 1;
  }
  if (!sybyltype.empty() && fmt != TrajectoryFile::MOL2FILE) {
    mprinterr("Warning: -sybyl is only valid for MOL2 file output.\n");
    sybyltype.clear();
  }
  if (debug > 0) {
    mprinterr("Warning: debug is %i; debug info will be written to STDOUT.\n", debug);
    SetWorldSilent(false);
  }
  // Topology
  ParmFile pfile;
  Topology parm;
  if (pfile.ReadTopology(parm, topname, debug)) {
    if (topname == "prmtop") Help(argv[0], false);
    return 1;
  }
  if (!useExtendedInfo)
    parm.ResetPDBinfo();
  if (res_offset != 0)
    for (int r = 0; r < parm.Nres(); r++)
      parm.SetRes(r).SetOriginalNum( parm.Res(r).OriginalResNum() + res_offset );
  ArgList trajArgs;
  // Input coords
  Frame TrajFrame;
  CoordinateInfo cInfo;
  if (!crdname.empty()) {
    Trajin_Single trajin;
    if (trajin.SetupTrajRead(crdname, trajArgs, &parm)) return 1;
    cInfo = trajin.TrajCoordInfo();
    TrajFrame.SetupFrameV(parm.Atoms(), cInfo);
    trajin.BeginTraj();
    if (trajin.ReadTrajFrame(0, TrajFrame)) return 1;
    trajin.EndTraj();
  } else {
    // Assume Amber restart from STDIN
    // Check that input is from a redirect.
    if ( isatty(fileno(stdin)) ) {
      mprinterr("Error: No coordinates specified with '-c' and no STDIN '<'.\n");
      return 1;
    }
    Traj_AmberRestart restartIn;
    restartIn.SetDebug( debug );
    //restartIn.processReadArgs( trajArgs );
    int total_frames = restartIn.setupTrajin("", &parm);
    if (total_frames < 1) return 1;
    cInfo = restartIn.CoordInfo();
    TrajFrame.SetupFrameV(parm.Atoms(), cInfo);
    if (restartIn.openTrajin()) return 1;
    if (restartIn.readFrame(0, TrajFrame)) return 1;
    restartIn.closeTraj();
  }
  if (ctr_origin) 
    TrajFrame.CenterOnOrigin(false);
  // Output coords
  Trajout_Single trajout;
  trajArgs.SetList( aatm + bres + pqr + title + ter_opt + box + sybyltype + writeconect, " " );
  if ( trajout.PrepareStdoutTrajWrite(trajArgs, &parm, cInfo, 1, fmt) ) return 1;
  trajout.WriteSingle(0, TrajFrame);
  trajout.EndTraj();
  return 0;
}