Exemplo n.º 1
0
Arquivo: main.cpp Projeto: CCJY/coliru
int main()
{
    int x=4,y=3;
    std::cout << modeString(Mode::plus)  << "\t:" << compute( Mode::plus , x, y ) <<"\n";
    std::cout << modeString(Mode::minus) << "\t:" << compute( Mode::minus, x, y ) <<"\n";
    std::cout << modeString(Mode::mul)   << "\t:" << compute( Mode::mul  , x, y ) <<"\n";
    std::cout << modeString(Mode::div)   << "\t:" << compute( Mode::div  , x, y ) <<"\n";

    return 0;
}
    void onDrawContent(SkCanvas* canvas) override {
        SkPaint paint;
        SkSafeUnref(paint.setTypeface(SkTypeface::CreateFromFile("/skimages/samplefont.ttf")));
        paint.setAntiAlias(true);
        paint.setFilterQuality(kMedium_SkFilterQuality);

        SkString outString("fps: ");
        fTimer.end();

        // TODO: generalize this timing code in utils
        fTimes[fCurrentTime] = (float)(fTimer.fWall);
        fCurrentTime = (fCurrentTime + 1) & 0x1f;

        float meanTime = 0.0f;
        for (int i = 0; i < 32; ++i) {
            meanTime += fTimes[i];
        }
        meanTime /= 32.f;
        SkScalar fps = 1000.f / meanTime;
        outString.appendScalar(fps);
        outString.append(" ms: ");
        outString.appendScalar(meanTime);

        SkString modeString("Text scale: ");
        modeString.appendU32(fSizeScale);
        modeString.append("x");

        fTimer.start();

        canvas->save();

#if SK_SUPPORT_GPU
        SkBaseDevice* device = canvas->getDevice_just_for_deprecated_compatibility_testing();
        GrContext* grContext = canvas->getGrContext();
        if (grContext) {
            GrTexture* tex = grContext->getFontAtlasTexture(GrMaskFormat::kA8_GrMaskFormat);
            reinterpret_cast<SkGpuDevice*>(device)->drawTexture(tex,
                                                       SkRect::MakeXYWH(512, 10, 512, 512), paint);
        }
#endif
        canvas->translate(180, 180);
        canvas->rotate(fRotation);
        canvas->scale(fScale, fScale);
        canvas->translate(-180, -180);

        const char* text = "Hamburgefons";
        size_t length = strlen(text);

        SkScalar y = SkIntToScalar(0);
        for (int i = 12; i <= 26; i++) {
            paint.setTextSize(SkIntToScalar(i*fSizeScale));
            y += paint.getFontSpacing();
            DrawTheText(canvas, text, length, SkIntToScalar(110), y, paint);
        }
        canvas->restore();

        paint.setTextSize(16);
//        canvas->drawText(outString.c_str(), outString.size(), 512.f, 540.f, paint);
        canvas->drawText(modeString.c_str(), modeString.size(), 768.f, 540.f, paint);
    }
Exemplo n.º 3
0
/*
 * Print one line listing the information about the specified archive member.
 */
static void
listMember(const Archive * arch)
{
	printf("%s %6ld/%-6ld %8lu %s %s\n",
	       modeString(arch->mode) + 1,
	       (long) arch->uid,
	       (long) arch->gid,
	       (unsigned long) arch->size,
	       timeString(arch->date),
	       arch->name);
}
Exemplo n.º 4
0
void WG021::diagnostics(diagnostic_updater::DiagnosticStatusWrapper &d, unsigned char *buffer)
{
  WG021Status *status = (WG021Status *)(buffer + command_size_);

  stringstream str;
  str << "EtherCAT Device (" << actuator_info_.name_ << ")";
  d.name = str.str();
  char serial[32];
  snprintf(serial, sizeof(serial), "%d-%05d-%05d", config_info_.product_id_ / 100000 , config_info_.product_id_ % 100000, config_info_.device_serial_number_);
  d.hardware_id = serial;

  d.summary(d.OK, "OK");

  d.clear();
  d.add("Configuration", config_info_.configuration_status_ ? "good" : "error loading configuration");
  d.add("Name", actuator_info_.name_);
  d.addf("Position", "%02d", sh_->get_ring_position());
  d.addf("Product code",
        "WG021 (%d) Firmware Revision %d.%02d, PCB Revision %c.%02d",
        sh_->get_product_code(), fw_major_, fw_minor_,
        'A' + board_major_, board_minor_);

  d.add("Robot", actuator_info_.robot_name_);
  d.add("Serial Number", serial);
  d.addf("Nominal Current Scale", "%f",  config_info_.nominal_current_scale_);
  d.addf("Nominal Voltage Scale",  "%f", config_info_.nominal_voltage_scale_);
  d.addf("HW Max Current", "%f", config_info_.absolute_current_limit_ * config_info_.nominal_current_scale_);
  d.addf("SW Max Current", "%f", actuator_info_.max_current_);

  publishGeneralDiagnostics(d);
  mailbox_.publishMailboxDiagnostics(d);

  d.add("Mode", modeString(status->mode_));
  d.addf("Digital out", "%d", status->digital_out_);
  d.addf("Programmed current", "%f", status->programmed_current_ * config_info_.nominal_current_scale_);
  d.addf("Measured current", "%f", status->measured_current_ * config_info_.nominal_current_scale_);
  d.addf("Timestamp", "%u", status->timestamp_);
  d.addf("Config 0", "%#02x", status->config0_);
  d.addf("Config 1", "%#02x", status->config1_);
  d.addf("Config 2", "%#02x", status->config2_);
  d.addf("Output Status", "%#02x", status->output_status_);
  d.addf("Output Start Timestamp", "%u", status->output_start_timestamp_);
  d.addf("Output Stop Timestamp", "%u", status->output_stop_timestamp_);
  d.addf("Board temperature", "%f", 0.0078125 * status->board_temperature_);
  d.addf("Max board temperature", "%f", 0.0078125 * max_board_temperature_);
  d.addf("Bridge temperature", "%f", 0.0078125 * status->bridge_temperature_);
  d.addf("Max bridge temperature", "%f", 0.0078125 * max_bridge_temperature_);
  d.addf("Supply voltage", "%f", status->supply_voltage_ * config_info_.nominal_voltage_scale_);
  d.addf("LED voltage", "%f", status->led_voltage_ * config_info_.nominal_voltage_scale_);
  d.addf("Packet count", "%d", status->packet_count_);

  EthercatDevice::ethercatDiagnostics(d, 2); 
}
Exemplo n.º 5
0
/**
 * Expected input:
 * {
 * 	alg: "aes",
 * 	mode: "cbc",
 * 	key: key data,
 * 	iv: iv data (16 bytes),
 * 	input: data to encrypt or decrypt
 * }
 *
 * Good output:
 * {
 * 	output: data
 * }
 */
Json::Value AES::crypt(const std::string & algorithm, Json::Value & args,
		bool isEncrypt) {
	if (!args.isMember("key")) {
		throw std::string("key missing");
	}
	if (!args.isMember("input")) {
		throw std::string("input missing");
	}
	if (!args.isMember("iv")) {
		throw std::string("iv missing");
	}
	if (!args.isMember("mode")) {
		throw std::string("mode missing");
	}

	std::string modeString(
			gsecrypto::util::lowerCaseRemoveDashes(args["mode"].asString()));
	if ("cbc" != modeString) {
		throw std::string("Only CBC currently supported");
	}

	DataTracker input;
	getData(args["input"], input);

	DataTracker result(input.dataLen);

	if (input.dataLen == 0) {
		Json::Value toReturn;
		toReturn["output"] = toJson(result);
		return toReturn;
	}

	DataTracker keyBytes;
	getData(args["key"], keyBytes);

	DataTracker iv;
	getData(args["iv"], iv);

	int mode = SB_AES_CBC;

	AESParams params(*this, SB_AES_CBC, SB_AES_128_BLOCK_BITS, false);
	AESKey key(params, keyBytes);
	AESContext context(params, key, mode, iv);
	context.crypt(input, result, isEncrypt);

	Json::Value toReturn;
	toReturn["output"] = toJson(result);
	return toReturn;
}
Exemplo n.º 6
0
/*
 * Examine the header block that was just read.
 * This can specify the information for another file, or it can mark
 * the end of the tar file.
 */
static void
readHeader(const TarHeader * hp, int fileCount, const char ** fileTable)
{
	int		mode;
	int		uid;
	int		gid;
	//int		checkSum;
	long		size;
	time_t		mtime;
	const char *	name;
	int		cc;
	BOOL		hardLink;
	BOOL		softLink;

	/*
	 * If the block is completely empty, then this is the end of the
	 * archive file.  If the name is null, then just skip this header.
	 */
	name = hp->name;

	if (*name == '\0')
	{
		for (cc = TAR_BLOCK_SIZE; cc > 0; cc--)
		{
			if (*name++)
				return;
		}

		eofFlag = TRUE;

		return;
	}

	/*
	 * There is another file in the archive to examine.
	 * Extract the encoded information and check it.
	 */
	mode = getOctal(hp->mode, sizeof(hp->mode));
	uid = getOctal(hp->uid, sizeof(hp->uid));
	gid = getOctal(hp->gid, sizeof(hp->gid));
	size = getOctal(hp->size, sizeof(hp->size));
	mtime = getOctal(hp->mtime, sizeof(hp->mtime));
	//checkSum = getOctal(hp->checkSum, sizeof(hp->checkSum));

	if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0))
	{
		if (!badHeader)
			fprintf(stderr, "Bad tar header, skipping\n");

		badHeader = TRUE;

		return;
	}

	badHeader = FALSE;
	skipFileFlag = FALSE;

	/*
	 * Check for the file modes.
	 */
	hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
		(hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));

	softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
		(hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));

	/*
	 * Check for a directory or a regular file.
	 */
	if (name[strlen(name) - 1] == '/')
		mode |= S_IFDIR;
	else if ((mode & S_IFMT) == 0)
		mode |= S_IFREG;

	/*
	 * Check for absolute paths in the file.
	 * If we find any, then warn the user and make them relative.
	 */
	if (*name == '/')
	{
		while (*name == '/')
			name++;

		if (!warnedRoot)
		{
			fprintf(stderr,
			"Absolute path detected, removing leading slashes\n");
		}

		warnedRoot = TRUE;
	}

	/*
	 * See if we want this file to be restored.
	 * If not, then set up to skip it.
	 */
	if (!wantFileName(name, fileCount, fileTable))
	{
		if (!hardLink && !softLink && S_ISREG(mode))
		{
			inHeader = (size == 0);
			dataCc = size;
		}

		skipFileFlag = TRUE;

		return;
	}

	/*
	 * This file is to be handled.
	 * If we aren't extracting then just list information about the file.
	 */
	if (!extractFlag)
	{
		if (verboseFlag)
		{
			printf("%s %3d/%-d %9ld %s %s", modeString(mode),
				uid, gid, size, timeString(mtime), name);
		}
		else
			printf("%s", name);

		if (hardLink)
			printf(" (link to \"%s\")", hp->linkName);
		else if (softLink)
			printf(" (symlink to \"%s\")", hp->linkName);
		else if (S_ISREG(mode))
		{
			inHeader = (size == 0);
			dataCc = size;
		}

		printf("\n");

		return;
	}

	/*
	 * We really want to extract the file.
	 */
	if (verboseFlag)
		printf("x %s\n", name);

	if (hardLink)
	{
		if (link(hp->linkName, name) < 0)
			perror(name);

		return;
	}

	if (softLink)
	{
#ifdef	S_ISLNK
		if (symlink(hp->linkName, name) < 0)
			perror(name);
#else
		fprintf(stderr, "Cannot create symbolic links\n");
#endif
		return;
	}

	/*
	 * If the file is a directory, then just create the path.
	 */
	if (S_ISDIR(mode))
	{
		createPath(name, mode);

		return;
	}

	/*
	 * There is a file to write.
	 * First create the path to it if necessary with a default permission.
	 */
	createPath(name, 0777);

	inHeader = (size == 0);
	dataCc = size;

	/*
	 * Start the output file.
	 */
	outFd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode);

	if (outFd < 0)
	{
		perror(name);
		skipFileFlag = TRUE;

		return;
	}

	/*
	 * If the file is empty, then that's all we need to do.
	 */
	if (size == 0)
	{
		(void) close(outFd);
		outFd = -1;
	}
}
Exemplo n.º 7
0
//
// Save settings to file
//
void VCDockSlider::saveToFile(QFile &file, t_vc_id parentID)
{
  QString s;
  QString t;
  
  // Comment
  s = QString("# Virtual Console Slider Entry\n");
  file.writeBlock((const char*) s, s.length());

  // Entry type
  s = QString("Entry = Slider") + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Name
  s = QString("Name = ") + caption() + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Parent ID
  t.setNum(parentID);
  s = QString("Parent = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // X
  t.setNum(x());
  s = QString("X = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Y
  t.setNum(y());
  s = QString("Y = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // W
  t.setNum(width());
  s = QString("Width = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // H
  t.setNum(height());
  s = QString("Height = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Text color
  if (ownPalette())
    {
      t.setNum(qRgb(paletteForegroundColor().red(),
		    paletteForegroundColor().green(),
		    paletteForegroundColor().blue()));
      s = QString("Textcolor = ") + t + QString("\n");
      file.writeBlock((const char*) s, s.length());
      
      t.setNum(qRgb(paletteBackgroundColor().red(),
		    paletteBackgroundColor().green(),
		    paletteBackgroundColor().blue()));
      s = QString("Backgroundcolor = ") + t + QString("\n");
      file.writeBlock((const char*) s, s.length());
    }

  // Background pixmap
  if (paletteBackgroundPixmap())
    {
      s = QString("Pixmap = " + iconText() + QString("\n"));
      file.writeBlock((const char*) s, s.length());
    }

  // Frame
  if (frameStyle() & KFrameStyle)
    {
      s = QString("Frame = ") + Settings::trueValue() + QString("\n");
    }
  else
    {
      s = QString("Frame = ") + Settings::falseValue() + QString("\n");
    }
  file.writeBlock((const char*) s, s.length());

  // Font
  s = QString("Font = ") + font().toString() + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Bus
  t.setNum(m_busID);
  s = QString("Bus = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Bus Lo
  t.setNum(m_busLowLimit);
  s = QString("BusLowLimit = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Bus Hi
  t.setNum(m_busHighLimit);
  s = QString("BusHighLimit = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Channels
  if (m_channels.count())
    {
      s = QString("Channels = ");
      QValueList<t_channel>::Iterator it;
      for (it = m_channels.begin(); it != m_channels.end(); ++it)
	{
	  t.sprintf("%.3d", *it);
	  s += t + QString(" ");
	}

      s += QString("\n");
      file.writeBlock((const char*) s, s.length());      
    }

  // Level Lo
  t.setNum(m_levelLowLimit);
  s = QString("LevelLowLimit = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Level Hi
  t.setNum(m_levelHighLimit);
  s = QString("LevelHighLimit = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Mode (must be written after bus & channel settings)
  s = QString("Mode = ") + modeString(m_mode) + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Value
  t.setNum(m_slider->value());
  s = QString("Value = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());
}
Exemplo n.º 8
0
//
// Create this slider's contents from list
//
void VCDockSlider::createContents(QPtrList <QString> &list)
{
  QRect rect(0, 0, 60, 200);

  for (QString* s = list.next(); s != NULL; s = list.next())
    {
      if (*s == QString("Entry"))
	{
	  s = list.prev();
	  break;
	}
      else if (*s == QString("Name"))
	{
	  setCaption(*(list.next()));
	}
      else if (*s == QString("Parent"))
	{
	  VCFrame* parent =
	    _app->virtualConsole()->getFrame(list.next()->toInt());

	  if (parent != NULL)
	    {
	      reparent((QFrame*)parent, 0, QPoint(0, 0), true);
	    }
	}
      else if (*s == QString("X"))
	{
	  rect.setX(list.next()->toInt());
	}
      else if (*s == QString("Y"))
	{
	  rect.setY(list.next()->toInt());
	}
      else if (*s == QString("Width"))
	{
	  rect.setWidth(list.next()->toInt());
	}
      else if (*s == QString("Height"))
	{
	  rect.setHeight(list.next()->toInt());
	}
      else if (*s == QString("Textcolor"))
	{
	  QColor qc;
	  qc.setRgb(list.next()->toUInt());
	  setPaletteForegroundColor(qc);
	}
      else if (*s == QString("Backgroundcolor"))
	{
	  QColor qc;
	  qc.setRgb(list.next()->toUInt());
	  setPaletteBackgroundColor(qc);
	}
      else if (*s == QString("Color"))
	{
	  // Backwards compatibility for slider background color
	  QString t = *(list.next());
	  int i = t.find(QString(","));
	  int r = t.left(i).toInt();
	  int j = t.find(QString(","), i + 1);
	  int g = t.mid(i+1, j-i-1).toInt();
	  int b = t.mid(j+1).toInt();
	  QColor qc(r, g, b);
	  setPaletteBackgroundColor(qc);
	}
      else if (*s == QString("Pixmap"))
	{
	  QString t;
	  t = *(list.next());
	  
	  QPixmap pm(t);
	  if (pm.isNull() == false)
	    {
	      setIconText(t);
	      unsetPalette();
	      setPaletteBackgroundPixmap(pm);
	      m_valueLabel->setBackgroundOrigin(ParentOrigin);
	      m_slider->setBackgroundOrigin(ParentOrigin);
	    }
	}
      else if (*s == QString("Frame"))
	{
	  if (*(list.next()) == Settings::trueValue())
	    {
	      setFrameStyle(KFrameStyle);
	    }
	  else
	    {
	      setFrameStyle(NoFrame);
	    }
	}
      else if (*s == QString("Font"))
	{
	  QFont f = font();
	  QString q = *(list.next());
	  f.fromString(q);
	  setFont(f);
	}
      else if (*s == QString("Bus"))
	{
	  QString t = *(list.next());
	  t_bus_value value;
	  if (Bus::value(t.toInt(), value))
	    {
	      setBusID(t.toInt());
	    }
	}
      else if (*s == QString("BusLowLimit"))
	{
	  m_busLowLimit = list.next()->toInt();
	}
      else if (*s == QString("BusHighLimit"))
	{
	  m_busHighLimit = list.next()->toInt();
	}
      else if (*s == QString("Channels"))
	{
	  QString t;

	  unsigned int i = 0;
	  int j = 0;

	  s = list.next();

	  while (i < s->length())
	    {
	      j = s->find(QChar(' '), i, false);
	      if (j == -1)
		{
		  j = s->length();
		}

	      t = s->mid(i, j-i);
	      
	      // Check for duplicates
	      if (m_channels.find(t.toInt()) == m_channels.end())
		{
		  m_channels.append(t.toInt());
		}
	      
	      i = j + 1;
	    }
	}
      else if (*s == QString("LevelLowLimit"))
	{
	  m_levelLowLimit = list.next()->toInt();
	}
      else if (*s == QString("LevelHighLimit"))
	{
	  m_levelHighLimit = list.next()->toInt();
	}
      else if (*s == QString("Mode"))
	{
	  QString t = *list.next();
	  if (t == modeString(Speed))
	    {
	      m_mode = Speed;
	    }
	  else if (t == modeString(Level))
	    {
	      m_mode = Level;
	    }
	  else
	    {
	      m_mode = Submaster;
	    }
	}
      else if (*s == QString("Value"))
	{
	  m_slider->setValue(list.next()->toInt());
	}
      else
	{
	  // Unknown keyword, ignore
	  *list.next();
	}
    }

  setLevelRange(m_levelLowLimit, m_levelHighLimit);
  setBusRange(m_busLowLimit, m_busHighLimit);
  setGeometry(rect);

  if (m_mode == Submaster)
    {
      assignSubmasters(true);
    }

  setMode(m_mode);
}
Exemplo n.º 9
0
/**
 * @brief Read in a list of array and check for each of the arrays whether they are in LMC form or not
 * @param argc
 * @param argv[]
 * @return
 */
int main (int argc, char *argv[]) {
        char *fname;
        int correct = 0, wrong = 0;

        /* parse command line options */
        AnyOption opt;
        opt.setFlag ("help", 'h'); /* a flag (takes no argument), supporting long and short form */
        opt.setOption ("loglevel", 'l');
        opt.setOption ("oaconfig", 'c');
        opt.setOption ("check");
        opt.setOption ("strength", 's');
        opt.setOption ("prune", 'p');
        opt.setOption ("output", 'o');
        opt.setOption ("mode", 'm');

        opt.addUsage ("oacheck: Check arrays for LMC form or reduce to LMC form");
        opt.addUsage ("Usage: oacheck [OPTIONS] [ARRAYFILE]");
        opt.addUsage ("");
        opt.addUsage (" -h  --help  			Prints this help");
        opt.addUsage (" -l [LEVEL]  --loglevel [LEVEL]	Set loglevel to number");
        opt.addUsage (" -s [STRENGTH]  --strength [STRENGTH] Set strength to use in checking");
        std::string ss = " --check [MODE]			Select mode: ";
        ss +=
            printfstring ("%d (default: check ), %d (reduce to LMC form), %d (apply random transformation and reduce)",
                          MODE_CHECK, MODE_REDUCE, MODE_REDUCERANDOM); //
        for (int i = 3; i < ncheckopts; ++i)
                ss += printfstring (", %d (%s)", static_cast< checkmode_t > (i), modeString ((checkmode_t)i).c_str ());
        opt.addUsage (ss.c_str ());
        opt.addUsage (" -o [OUTPUTFILE] Output file for LMC reduction");

        opt.processCommandArgs (argc, argv);

        algorithm_t algmethod = (algorithm_t)opt.getIntValue ("mode", MODE_AUTOSELECT);

        int loglevel = NORMAL;
        if (opt.getValue ("loglevel") != NULL || opt.getValue ('l') != NULL)
                loglevel = atoi (opt.getValue ('l')); // set custom loglevel
        setloglevel (loglevel);

        if (checkloglevel (QUIET)) {
                print_copyright ();
        }

        if (opt.getFlag ("help") || opt.getFlag ('h') || opt.getArgc () == 0) {
                opt.printUsage ();
                return 0;
        }

        checkmode_t mode = MODE_CHECK;
        if (opt.getValue ("check") != NULL)
                mode = (checkmode_t)atoi (opt.getValue ("check")); // set custom loglevel
        if (mode >= ncheckopts)
                mode = MODE_CHECK;

        logstream (QUIET) << "#time start: " << currenttime () << std::endl;

        double t = get_time_ms ();
        t = 1e3 * (t - floor (t));
        srand (t);

        int prune = opt.getIntValue ('p', 0);

        fname = opt.getArgv (0);
        setloglevel (loglevel);

        int strength = opt.getIntValue ('s', 2);
        if (strength < 1 || strength > 10) {
                printf ("Strength specfied (t=%d) is invalid\n", strength);
                exit (1);
        } else {
                log_print (NORMAL, "Using strength %d to increase speed of checking arrays\n", strength);
        }

        arraylist_t outputlist;
        char *outputfile = 0;
        bool writeoutput = false;
        if (opt.getValue ("output") != NULL) {
                writeoutput = true;
                outputfile = opt.getValue ('o');
        }

        arrayfile_t *afile = new arrayfile_t (fname);
        if (!afile->isopen ()) {
                printf ("Problem opening %s\n", fname);
                exit (1);
        }

        logstream (NORMAL) << "Check mode: " << mode << " (" << modeString (mode) << ")" << endl;

        /* start checking */
        double Tstart = get_time_ms (), dt;

        int index;
        array_link al (afile->nrows, afile->ncols, -1);
        for (int i = 0; i < afile->narrays; i++) {

                index = afile->read_array (al);
                array_t *array = al.array;

                arraydata_t arrayclass = arraylink2arraydata (al, 0, strength);
                arrayclass.lmc_overflow_check ();

                OAextend oaextend;

                lmc_t result = LMC_NONSENSE;

                LMCreduction_t *reduction = new LMCreduction_t (&arrayclass);
                LMCreduction_t *randtest = new LMCreduction_t (&arrayclass);
				array_link test_arraylink = al.clone();
				array_t *testarray = test_arraylink.array;
                randtest->transformation->randomize ();
                reduction->setArray ( al); 
                /* variables needed within the switch statement */
                switch (mode) {
                case MODE_CHECK:
				{
					/* LMC test with reduction code */
					reduction->mode = OA_TEST;
					result = LMCcheck(al, arrayclass, oaextend, *reduction);
					break;
				}
                case MODE_CHECKJ4: {
                        /* LMC test with special code */
                        reduction->mode = OA_TEST;
                        reduction->init_state = COPY;
                        oaextend.setAlgorithm (MODE_J4, &arrayclass);
                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }
                case MODE_REDUCEJ4: {
                        /* LMC test with special code */
                        reduction->mode = OA_REDUCE;
                        reduction->setArray (al);
                        result = LMCcheckj4 (al, arrayclass, *reduction, oaextend);
                        break;
                }
                case MODE_CHECK_SYMMETRY: {
					myprintf("MODE_CHECK_SYMMETRY not supported any more");
					exit(1);
                }
                case MODE_CHECKJ5X: {
                        oaextend.setAlgorithm (MODE_J5ORDERX, &arrayclass);

                        /* LMC test with special code */
                        reduction->mode = OA_TEST;
                        reduction->init_state = COPY;

                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }
                case MODE_CHECKJ5XFAST: {
                        oaextend.setAlgorithm (MODE_J5ORDERX, &arrayclass);

                        /* LMC test with special code */
                        reduction->mode = OA_TEST;
                        reduction->init_state = COPY;
                        if (1) {
                                array_link al (array, arrayclass.N, arrayclass.ncols, al.INDEX_NONE);
                                reduction->updateSDpointer (al);
                        }
                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }
                case MODE_REDUCEJ5X: {
                        OAextend oaextend;
                        oaextend.setAlgorithm (MODE_J5ORDERX, &arrayclass);

                        /* LMC test with special code */
                        printf ("oacheck: WARNING: MODE_CHECKJ5X: untested code, not complete\n");
                        reduction->mode = OA_REDUCE;
                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }

                case MODE_REDUCE:
                        /* LMC reduction */
				{
					reduction->mode = OA_REDUCE;
					copy_array(array, reduction->array, arrayclass.N, arrayclass.ncols);
					dyndata_t dynd = dyndata_t(arrayclass.N);

					result = LMCreduction(array, array, &arrayclass, &dynd, reduction, oaextend);
					break;
				}
				case MODE_REDUCERANDOM: 
					{
						/* random LMC reduction */
						oaextend.setAlgorithm(MODE_ORIGINAL, &arrayclass);
						reduction->mode = OA_REDUCE;
						randtest->transformation->apply(array, testarray);
						copy_array(testarray, reduction->array, arrayclass.N, arrayclass.ncols);
						reduction->init_state = INIT;
						array_link alp = arrayclass.create_root(arrayclass.ncols, 1000);
						reduction->setArray(alp);
						dyndata_t dynd = dyndata_t(arrayclass.N);

						result = LMCreduction(testarray, testarray, &arrayclass, &dynd, reduction, oaextend);

						if (log_print(NORMAL, "")) {
							reduction->transformation->show();
						}
					} break;
				
                case MODE_REDUCETRAIN:
                        /* LMC reduction with train*/
                        reduction->mode = OA_REDUCE;
                        result = LMCreduction_train (al, &arrayclass, reduction, oaextend);
                        break;
                case MODE_REDUCETRAINRANDOM:
                        /* random LMC reduction with train*/
                        reduction->mode = OA_REDUCE;

                        randtest->transformation->apply (array, testarray);
                        result = LMCreduction_train (test_arraylink, &arrayclass, reduction, oaextend);
                        break;
                case MODE_HADAMARD:
						myprintf("MODE_HADAMARD not supported any more\n");
						exit(1);
                default:
                        result = LMC_NONSENSE;
                        std::cout << "function " << __FUNCTION__ << "line " << __LINE__ << "Unknown mode" << std::endl;
                        exit (1);
                        break;
                }

                bool aequal;
                switch (mode) {
                case MODE_CHECK:
                        if (result == LMC_LESS) {
                                ++wrong;
                                log_print (NORMAL, "Found array nr %i/%i NOT in lmc form:\n", i, afile->narrays);
                        } else {
                                ++correct;
                                log_print (NORMAL, "Found array nr %i/%i in lmc form.\n", i, afile->narrays);
                        }

                        break;
                case MODE_CHECKJ4:
                case MODE_CHECKJ5X:
                case MODE_CHECKJ5XFAST:
                case MODE_CHECK_SYMMETRY:
                        if (result == LMC_LESS) {
                                ++wrong;
                                log_print (NORMAL, "Found array nr %i/%i NOT in minimal form:\n", i, afile->narrays);
                        } else {
                                ++correct;
                                log_print (NORMAL, "Found array nr %i/%i in minimal form.\n", i, afile->narrays);
                        }

                        break;
                case MODE_REDUCE:
                case MODE_REDUCEJ4:
                case MODE_REDUCEJ5X:
                case MODE_REDUCETRAIN:
                        aequal = std::equal (array, array + arrayclass.N * arrayclass.ncols, reduction->array);

                        if ((!aequal) || reduction->state == REDUCTION_CHANGED) {
                                ++wrong;
                                log_print (QUIET, "Reduced array %i/%i to lmc form.\n", i, afile->narrays);
                                if (checkloglevel (NORMAL)) {
                                        log_print (QUIET, "Original:\n");
										
                                        print_array (array, afile->nrows, afile->ncols);
                                        print_array ("Reduction:\n", reduction->array, afile->nrows, afile->ncols);
                                        printf ("---------------\n");
                                }
                                if (checkloglevel (DEBUG)) {
                                        cout << "Transformation: " << endl;
                                        reduction->transformation->show (cout);

                                        rowindex_t row;
                                        colindex_t column;
                                        array_diff (array, reduction->array, arrayclass.N, arrayclass.ncols, row, column);
                                        cout << "Difference at: ";
                                        printf (" row %d, col %d\n", row, column);
                                }
                        } else {
                                ++correct;
                                log_print (QUIET, "Array %i/%i was already in lmc form:\n", i, afile->narrays);
                        }
                        break;
                case MODE_REDUCETRAINRANDOM:
                case MODE_REDUCERANDOM:
                case MODE_REDUCEJ4RANDOM:
                        aequal = std::equal (array, array + arrayclass.N * arrayclass.ncols, reduction->array);

                        if (!aequal) {
                                ++wrong;
                                log_print (SYSTEM,
                                           "Array %i/%i: reduced random transformation not equal to original (BUG!)\n",
                                           i, afile->narrays);
                                if (checkloglevel (NORMAL)) {
                                        print_array ("Original:\n", array, afile->nrows, afile->ncols);
                                        print_array ("Randomized:\n", testarray, afile->nrows, afile->ncols);
                                        print_array ("Reduction:\n", reduction->array, afile->nrows, afile->ncols);
                                        printf ("---------------\n");
                                }
                        } else {
                                ++correct;
                                log_print (QUIET, "Array %i/%i: reduced random transformation to original\n", i,
                                           afile->narrays);
                        }

                        break;
                case MODE_HADAMARD:
                        break;
                default:
                        std::cout << "function " << __FUNCTION__ << "line " << __LINE__ << "unknown mode" << std::endl;
                        break;
                }

                array_link al = array_link ((carray_t *)reduction->array, afile->nrows, afile->ncols, -1);
                if (result == LMC_MORE || !prune) {
                        outputlist.push_back (al);
                }
                delete randtest;
                delete reduction;
                destroy_array (testarray);
        }

        afile->closefile ();
        delete afile;

        if (writeoutput) {
                logstream (NORMAL) << "Writing output (" << outputlist.size () << " arrays)" << endl;
                writearrayfile (outputfile, outputlist);
        }

        logstream (QUIET) << "#time end: " << currenttime () << std::endl;

        return 0;
}
Exemplo n.º 10
0
/**
 * Expected input:
 * {
 * 	alg: "des", [or "3des"]
 * 	mode: "cbc", [or "ecb"]
 * 	key1: key1 data,
 * 	key2: key2 data, [if 3des]
 * 	key3: key3 data, [if 3des]
 * 	iv: iv data (16 bytes), [if cbc mode]
 * 	input: data to encrypt or decrypt
 * }
 *
 * Good output:
 * {
 * 	output: data
 * }
 */
Json::Value DES::crypt(const std::string & algorithm, Json::Value & args,
		bool isEncrypt) {

    int mode;

	if (!args.isMember("key1")) {
		throw std::string("key1 missing");
	}
	if("3des" == algorithm) {
	    if (!args.isMember("key2")) {
            throw std::string("key2 missing");
        }
        if (!args.isMember("key3")) {
            throw std::string("key3 missing");
        }
	}

	if (!args.isMember("input")) {
		throw std::string("input missing");
	}
	if (!args.isMember("mode")) {
		throw std::string("mode missing");
	}

	std::string modeString(
			gsecrypto::util::lowerCaseRemoveDashes(args["mode"].asString()));
	if ("cbc" == modeString) {
	    mode = SB_DES_CBC;
	    if (!args.isMember("iv")) {
		    throw std::string("iv required for CBC mode");
	    }
	} else if("ecb" == modeString) {
	    mode = SB_DES_ECB;
	} else {
	    throw std::string("Only CBC and ECB currently supported");
	}

	DataTracker input;
	getData(args["input"], input);

	DataTracker result(input.dataLen);

	if (input.dataLen == 0) {
		Json::Value toReturn;
		toReturn["output"] = toJson(result);
		return toReturn;
	}

	DataTracker keyBytes1;
	DataTracker keyBytes2(SB_DES_KEY_SIZE);
	DataTracker keyBytes3(SB_DES_KEY_SIZE);
	getData(args["key1"], keyBytes1);

	if("3des" == algorithm) {
	    getData(args["key2"], keyBytes2);
	    getData(args["key3"], keyBytes3);
	}

	if(   keyBytes1.dataLen != SB_DES_KEY_SIZE
       || keyBytes2.dataLen != SB_DES_KEY_SIZE
       || keyBytes3.dataLen != SB_DES_KEY_SIZE ) {
	    std::stringstream stream;
        stream << "Key length must be " << SB_DES_KEY_SIZE << " bytes.";
        throw stream.str();
	}

	if( (input.dataLen % SB_DES_BLOCK_SIZE) != 0 ) {
	    std::stringstream stream;
        stream << "Input not multiple of " << SB_DES_BLOCK_SIZE << " bytes. Use padding.";
        throw stream.str();
	}

    DESParams params(*this, ("3des" == algorithm) ? SB_DES_TDES : SB_DES_DES,
                     mode, SB_DES_BLOCK_SIZE, false);
    DESKey key(params, keyBytes1, keyBytes2, keyBytes3);
    DataTracker iv(SB_DES_IV_SIZE);

    if( mode == SB_DES_CBC ) {
        getData(args["iv"], iv);
        if( iv.dataLen != SB_DES_IV_SIZE ) {
            std::stringstream stream;
            stream << "IV not " << SB_DES_IV_SIZE << " bytes.";
            throw stream.str();
        }
    }

    DESContext context(params, key, mode, iv);
	context.crypt(input, result, isEncrypt);

	Json::Value toReturn;
	toReturn["output"] = toJson(result);
	return toReturn;
}
/**
 * Expected input:
 * {
 * 	alg: "aes",
 * 	mode: "cbc",
 * 	key: key data,
 * 	iv: iv data (16 bytes),
 * 	input: data to encrypt or decrypt
 * }
 *
 * Good output:
 * {
 * 	output: data
 * }
 */
Json::Value AES::crypt(const std::string & algorithm, Json::Value & args,
                       bool isEncrypt) {
    if (!args.isMember("key")) {
        throw std::string("key missing");
    }
    if (!args.isMember("input")) {
        throw std::string("input missing");
    }
    if (!args.isMember("iv")) {
        throw std::string("iv missing");
    }
    if (!args.isMember("mode")) {
        throw std::string("mode missing");
    }

    std::string modeString(
        gsecrypto::util::lowerCaseRemoveDashes(args["mode"].asString()));
    if ("cbc" != modeString) {
        throw std::string("Only CBC currently supported");
    }

    DataTracker input;
    getData(args["input"], input);

    DataTracker result(input.dataLen);

    if (input.dataLen == 0) {
        Json::Value toReturn;
        toReturn["output"] = toJson(result);
        return toReturn;
    }

    DataTracker keyBytes;
    getData(args["key"], keyBytes);

    switch( keyBytes.dataLen*8 ) {
    case 128:
    case 192:
    case 256:
        break;
    default:
        std::stringstream stream;
        stream << "Key Size: " << (keyBytes.dataLen*8) << " bits not supported.";
        throw stream.str();
    }

    if( (input.dataLen % 16) != 0 ) {
        throw std::string("Input not multiple of 128 bits. Use padding.");
    }

    DataTracker iv;
    getData(args["iv"], iv);

    if( iv.dataLen != 16 ) {
        throw std::string("IV not 128 bits.");
    }

    int mode = SB_AES_CBC;

    AESParams params(*this, SB_AES_CBC, SB_AES_128_BLOCK_BITS, false);
    AESKey key(params, keyBytes);
    AESContext context(params, key, mode, iv);
    context.crypt(input, result, isEncrypt);

    Json::Value toReturn;
    toReturn["output"] = toJson(result);
    return toReturn;
}