Example #1
0
	void write_argument_value(tstring const& data)
	{
		// http://www.w3.org/TR/REC-xml/#NT-AttValue
		// says that in att value, we escape " ' < and &
		static const tstring patterns = "\"'<&";
		static const tstring replacements[] = {
			"&quot;", "&apos;", "&lt;", "&amp;"
		};
		xml_content_encoder encoder(data, patterns, replacements);
		while( encoder.has_next() ) {
			tinfra::tstring chunk = encoder.next();
			out_->write(chunk.data(), chunk.size());
		}
	}
Example #2
0
    const std::string createHeader()
    {
        // TODO: Some sane code to represent JSON objects
        std::string header = "{\"alg\":\""+_alg+"\",\"typ\":\""+_typ+"\"}";

        Log::info("JWT Header: " + header);
        std::ostringstream ostr;
        Poco::OutputLineEndingConverter lineEndingConv(ostr, "");
        Poco::Base64Encoder encoder(lineEndingConv);
        encoder << header;
        encoder.close();

        return ostr.str();
    }
Example #3
0
void ArchExecutor::EncodeFiles(Options* options)
{
	int filesCount = options->Files->GetCount();
	if (options->Stdin || filesCount == 0)
	{
		LzwEncoder encoder(stdin, stdout);
		encoder.Encode("");
		return;
	}

	for(int i = 0; i < filesCount; i++)
	{
		char* path = options->Files->GetElement(i);

		FILE* inputFile = fopen(path, "rb");
		if (IsCompressedFile(inputFile))
		{
			fclose(inputFile);
			continue;
		}

		char* compressedPath = new char[PATH_MAX];
		int pathLength = sprintf (compressedPath, "%s.ar", path);
		if (pathLength >= PATH_MAX) 
		{
			printf ("Path length has got too long.\n");
			continue;
		}

		FILE* outputFile = fopen(compressedPath, "wb");

		LzwEncoder encoder(inputFile, outputFile);
		encoder.Encode(GetName(path));
		fclose(inputFile);
		remove(path);
	}
}
Example #4
0
void VlrCompressor::done()
{
    // Close and clear the point encoder.
    m_encoder->done();
    m_encoder.reset();

    newChunk();

    // Save our current position.  Go to the location where we need
    // to write the chunk table offset at the beginning of the point data.

    uint64_t chunkTablePos = htole64((uint64_t) m_stream.m_buf.size());
    // We need to add the offset given a construction time since
    // we did not use a stream to write the header and vlrs
    uint64_t trueChunkTablePos = htole64((uint64_t) m_stream.m_buf.size() +  m_offsetToData);

    // Equivalent of stream.seekp(m_chunkInfoPos); stream << chunkTablePos
    memcpy(&m_stream.m_buf[m_chunkInfoPos], (char*) &trueChunkTablePos, sizeof(uint64_t));

    // Move to the start of the chunk table.
    // Which in our case is the end of the m_stream vector

    // Write the chunk table header in two steps
    // 1. Push bytes into the stream
    // 2. memcpy the data into the pushed bytes
    unsigned char skip[2 * sizeof(uint32_t)] = {0};
    m_stream.putBytes(skip, sizeof(skip));
    uint32_t version = htole32(0);
    uint32_t chunkTableSize = htole32((uint32_t) m_chunkTable.size());

    memcpy(&m_stream.m_buf[chunkTablePos], &version, sizeof(uint32_t));
    memcpy(&m_stream.m_buf[chunkTablePos + sizeof(uint32_t)], &chunkTableSize, sizeof(uint32_t));

    // Encode and write the chunk table.
    // OutputStream outputStream(m_stream);
    TypedLazPerfBuf<uint8_t> outputStream(m_stream);
    Encoder encoder(outputStream);
    laszip::compressors::integer compressor(32, 2);
    compressor.init();

    uint32_t predictor = 0;
    for (uint32_t chunkSize : m_chunkTable)
    {
        chunkSize = htole32(chunkSize);
        compressor.compress(encoder, predictor, chunkSize, 1);
        predictor = chunkSize;
    }
    encoder.done();
}
// -----------------------------------------------------------------------------
// CWimCertHandler::ParseCertPublicKeyL
// Parse public key from certificate.
// -----------------------------------------------------------------------------
//
void CWimCertHandler::ParseCertPublicKeyL(
    const TDesC8& aCertData,
    TDes8& aPublicKey,
    const TUint8 aCertType ) const
    {
    _WIMTRACE2(_L("WIM | WIMServer | CWimPublicKeyHandler::ParseCertPublicKeyL | Begin, type %d"), aCertType);
    CCertificate* certificate = NULL;
    CRSAPublicKey* publicKey = NULL;

    switch ( aCertType )
        {
        case WIMI_CT_WTLS:
            {
            certificate = CWTLSCertificate::NewLC( aCertData );
            publicKey = CWTLSRSAPublicKey::NewLC( certificate->PublicKey().KeyData() );
            break;
            }

        case WIMI_CT_X509:
            {
            certificate = CX509Certificate::NewLC( aCertData );
            publicKey = CX509RSAPublicKey::NewLC( certificate->PublicKey().KeyData() );
            break;
            }
        default:
            {
            _WIMTRACE2(_L("WIM|WIMServer|CWimCertHandler::ParseCertPublicKeyL, type %d not supported"), aCertType);
            User::Leave( KErrNotSupported );
            break;
            }
        }

    TX509RSAKeyEncoder encoder( *publicKey, ESHA1 );
    CASN1EncBase* encoded = encoder.EncodeKeyLC();

    TUint pos = 0;
    aPublicKey.SetLength( KPublicKeyLength );
    // Check that Max. length is not exceeded
    if ( encoded->LengthDER() > static_cast< TUint >( KPublicKeyLength ) )
        {
        _WIMTRACE(_L("WIM|WIMServer|CWimCertHandler::ParseCertPublicKeyL, too long public key"));
        User::Leave( KErrBadDescriptor );
        }
    // Write encoded key to prealloced buffer
    encoded->WriteDERL( aPublicKey, pos );

    CleanupStack::PopAndDestroy( 3, certificate );  // encoded, publicKey, certificate
    _WIMTRACE(_L("WIM | WIMServer | CWimPublicKeyHandler::ParseCertPublicKeyL | End"));
    }
Example #6
0
/*
encoder - decoder
cbr or cq
ppinloop
rebuild.yuv size.txt ssim.txt
*/
void run_codec_test(char argc, char** argv)
{
	CX264Encoder e;

	set_default_cmd();    
	parse_cmd_enc( argc, argv);
	if(1==verfy_cmd())
	{
		cmd_help();
	}

	init_encoder( &e );

    encoder( &e, &gCmd);
}
Example #7
0
	std::string lzwTest(const std::string& str) {
		std::ostringstream oss;
		LzwEncoder encoder(std::make_shared<Writer>(&oss));
		for (auto c : str) {
			encoder.encode(c);
		}
		encoder.flush();

		std::istringstream iss(oss.str());
		LzwDecoder decoder(std::make_shared<Reader>(&iss));
		std::ostringstream result;
		decoder.decode(result);

		return result.str();
	}
void URLEncoderTest::DecodeTest()
{
	URLEncoder encoder("encoder");
	String Request = "Dies%20ist%0A%20%22%25%26%3F%2F%5C%23%7B%7DeinTestString";
	String Answer, expected;
	encoder.DoDecode(Answer, Request);
	expected = "Dies ist\n ";
	expected.Append('"').Append("%&?/\\#{}einTestString");
	assertEqual( expected, Answer );
	Request = "Dies+ist%0A+%22%25%26%3F%2F%5C%23%7B%7Dein+Test+String";
	encoder.DoDecode(Answer, Request);
	expected = "Dies ist\n ";
	expected.Append('"').Append("%&?/\\#{}ein Test String");
	assertEqual( expected, Answer );
}
Example #9
0
	void write_content_bytes(tstring const& data)
	{
		// http://www.w3.org/TR/REC-xml/#dt-chardata
		// says that only < and & are escaped 
		// in normal text
		static const tstring patterns = "<&";
		static const tstring replacements[] = {
			"&lt;", "&amp;"
		};
		xml_content_encoder encoder(data, patterns, replacements); 
		while( encoder.has_next() ) {
			tinfra::tstring chunk = encoder.next();
			out_->write(chunk.data(), chunk.size());
		}
	}
Example #10
0
void MailMessage::writeEncoded(std::istream& istr, std::ostream& ostr, ContentTransferEncoding encoding) const
{
	switch (encoding)
	{
	case ENCODING_7BIT:
	case ENCODING_8BIT:
		StreamCopier::copyStream(istr, ostr);
		break;
	case ENCODING_QUOTED_PRINTABLE:
		{
			QuotedPrintableEncoder encoder(ostr);
			StreamCopier::copyStream(istr, encoder);
			encoder.close();
		}
		break;
	case ENCODING_BASE64:
		{
			Base64Encoder encoder(ostr);
			StreamCopier::copyStream(istr, encoder);
			encoder.close();
		}
		break;
	}
}
Example #11
0
void compressAdaptive(std::istream& in, std::ostream& out) {
	const char* header = "AC\x00";
	out.write(header, 3);

	ArithmeticEncoder encoder(std::make_shared<BitStreamWriter>(&out));
	AdaptiveDataModel dataModel(NUM_SYMBOLS);
	for (;;) {
		int c = in.get();
		if (c == std::char_traits<char>::eof()) {
			encoder.encode(NUM_SYMBOLS - 1, &dataModel);
			break;
		}

		encoder.encode(c, &dataModel);
	}
}
Example #12
0
  static Block
  makeBlock(uint32_t type, Iterator first, Iterator last)
  {
    EncodingEstimator estimator;
    size_t valueLength = last - first;
    size_t totalLength = valueLength;
    totalLength += estimator.prependVarNumber(valueLength);
    totalLength += estimator.prependVarNumber(type);

    EncodingBuffer encoder(totalLength, 0);
    encoder.prependRange(first, last);
    encoder.prependVarNumber(valueLength);
    encoder.prependVarNumber(type);

    return encoder.block();
  }
Example #13
0
void main(int argc, char *argv[])
{
    void encoder();
    static void usage(char*);
    
    if (argc != 3)
	usage(argv[0]);
#ifdef __ADSP21000__
    initx();
#else
    ifile_name = argv[1];
    xfile_name = argv[2];
#endif
    ffase = -4;
    encoder();
}
Example #14
0
void		saveImage (const unsigned char* pixels,const unsigned char* palette,size_t width,size_t height,size_t channels,const std::string& strFile)
{
    std::auto_ptr<ImageEncoder> encoder ( getImageEncoder (strFile) );
    if (!encoder.get())
            throw std::runtime_error("Unsupported file format "+strFile);

    encoder->setWidth (width);
    encoder->setHeight (height);
    encoder->setChannels (channels);
    encoder->setPalette (palette);

    encoder->write_open(strFile);
    encoder->write_header();
    encoder->write_data (pixels,palette);
    encoder->write_close ();
}
Example #15
0
    const std::string createPayload()
    {
        std::time_t curtime = Poco::Timestamp().epochTime();
        std::string exptime = std::to_string(curtime + 3600);

        // TODO: Some sane code to represent JSON objects
        std::string payload = "{\"iss\":\""+_iss+"\",\"sub\":\""+_sub+"\",\"aud\":\""+_aud+"\",\"nme\":\""+_name+"\",\"exp\":\""+exptime+"\"}";

        Log::info("JWT Payload: " + payload);
        std::ostringstream ostr;
        Poco::OutputLineEndingConverter lineEndingConv(ostr, "");
        Poco::Base64Encoder encoder(lineEndingConv);
        encoder << payload;
        encoder.close();

        return ostr.str();
    }
Example #16
0
int main(void)
{
  int i, sic, eic;
  U16BIT I;

  reset_encoder();
  reset_decoder();

  sic = __time / 2;
  for (i = 0; i < sizeof(Input) / sizeof(U16BIT); i++)
    decoder(encoder(Input[i]));
  eic = __time / 2;
  printf("\nInstruction cycles for transcoding a sample: %d\n",
	 (eic - sic) / (sizeof(Input) / sizeof(U16BIT)));

  return (0);
}
//获取文件的MD5码
CString CProcessMgr::GetFileMD5(CString sFilePath)
{
	std::string strFilePath = (LPCTSTR)sFilePath;
	CryptoPP::Weak::MD5 md5;
	CryptoPP::HashFilter filter(md5);

	std::auto_ptr<CryptoPP::ChannelSwitch> channelSwitch(new CryptoPP::ChannelSwitch);
	channelSwitch->AddDefaultRoute(filter);
	std::wstring wstr = s2ws_1(strFilePath);
	CryptoPP::FileSource(wstr.c_str(), true, channelSwitch.release());

	std::stringstream result;
	CryptoPP::HexEncoder encoder(new CryptoPP::FileSink(result), false);
	filter.TransferTo(encoder);
	std::string strResult = result.str();
	CString sResult = strResult.c_str();
	return sResult;
}
Example #18
0
QList<MovieFormat> MovieCapture::availableFormats()
{
    Q_D(MovieCapture);
    static QList<MovieFormat> availableFormats;
    if ( availableFormats.isEmpty() && checkToolsAvailability() ) {
        QProcess encoder(this);
        foreach ( MovieFormat format, m_supportedFormats ) {
            QString type = format.type();
            QStringList args;
            args << "-h" << "muxer=" + type;
            encoder.start( d->encoderExec, args );
            encoder.waitForFinished();
            QString output = encoder.readAll();
            bool isFormatAvailable = !output.contains( "Unknown format" );
            if( isFormatAvailable ) {
                availableFormats << format;
            }
        }
TEST(invalidEncoder, CodecLibrary)
{
    HBitmapEncoder encoder(new WindowsBitmapEncoder);

    bool isInvalidEncoder = false;

    try
    {
        std::ostringstream os(std::ios::binary);
        encoder->encodeToStream(os);
    }
    catch (const InvalidEncoder&)
    {
        isInvalidEncoder = true;
    }

    CHECK(isInvalidEncoder);
}
Example #20
0
void KDocumentTextBuffer::localTextInserted( KTextEditor::Document *document,
    const KTextEditor::Range &range )
{
    if ( m_aboutToClose ) return;

    emit localChangedText(range, user(), false);
    Q_UNUSED(document)

    textOpPerformed();
    if( m_user.isNull() ) {
        kDebug() << "Could not insert text: No local user set.";
        return;
    }
    unsigned int offset = cursorToOffset_kte(range.start());
    kDebug() << "local text inserted" << kDocument() << "( range" << range << ")" << m_user << "offset:" << offset;
    QInfinity::TextChunk chunk(encoding());
    QString text = kDocument()->text(range);
#ifdef ENABLE_TAB_HACK
    if ( text.contains('\t') ) {
        text = text.replace('\t', "    ");
        kDocument()->blockSignals(true);
        kDocument()->replaceText(range, text);
        kDocument()->blockSignals(false);
    }
#endif
    Q_ASSERT(encoder());
    if ( text.isEmpty() ) {
        kDebug() << "Skipping empty insert.";
        return;
    }
    QByteArray encodedText = codec()->fromUnicode( text );
    if ( encodedText.size() == 0 ) {
        kDebug() << "Got empty encoded text from non empty string "
                    "Skipping insertion";
    }
    else {
        chunk.insertText( 0, encodedText, countUnicodeCharacters(text), m_user->id() );
        blockRemoteInsert = true;
        kDebug() << "inserting chunk of size" << chunk.length() << "into local buffer" << kDocument()->url();
        insertChunk( offset, chunk, m_user );
        kDebug() << "done inserting chunk";
        checkConsistency();
    }
}
Example #21
0
int encoder_test(u32 k)
{
	CEncoder encoder(k);

	const u32 DATA_LEN = 1000;
	u8 rndData[DATA_LEN];
	
	for (int i = 0; i < 1000000; ++i)
	{
		for (int i = 0; i < DATA_LEN; ++i)
		{
			rndData[i] = rand();
		}
		CData data(rndData,DATA_LEN);
		encoder.AddData(&data);
	}

	return 0;
}
Example #22
0
void InitialState::encodeFile(string fileName){
	if(ofFile::doesFileExist(fileName)){
		ofFile file;
		file.open(fileName, ofFile::ReadOnly);
		ofBuffer buf = file.readToBuffer();

		ostringstream ostr;
		Poco::Base64Encoder encoder(ostr);
		encoder << buf.getText();
		encoder.close();

		string outputStr = ostr.str();
		string output = ofFilePath::getBaseName(fileName) + (ofToLower(ofFilePath::getFileExt(fileName)) == "vert" ? ".v" : ".f");
		ofstream str;
		str.open(output, ios_base::out | ios_base::trunc);
		str << outputStr;		
		str.close();
	}
}
void
WorldInputCmdProcessor::sendAttackCommand(const iXY &world_pos)
{
    TerminalUnitCmdRequest comm_mesg;

    UnitBase *target_ptr;

    size_t id_list_index;
    size_t id_list_size;
    UnitBase *unit_ptr;

    if ( working_list.isSelected() == true ) {
        target_list.selectTarget( world_pos );

        target_ptr = UnitInterface::getUnit( target_list.unit_list[0] );

        id_list_size = working_list.unit_list.size();

        if ( id_list_size == 0 )
            return;

        NetMessageEncoder encoder(true);

        for( id_list_index = 0; id_list_index < id_list_size; id_list_index++ ) {
            unit_ptr = UnitInterface::getUnit( working_list.unit_list[ id_list_index ] );
            if ( unit_ptr != 0 ) {
                if ( unit_ptr->unit_state.select == true ) {
                    comm_mesg.comm_request.setHeader(unit_ptr->id,
                            _umesg_flag_unique);
                    comm_mesg.comm_request.setTargetUnit(target_ptr->id);

                    encoder.encodeMessage(&comm_mesg,
                            sizeof(TerminalUnitCmdRequest));
                }
            }
        }

        encoder.sendEncodedMessage();

        //sfx
        sound->playSound("target");
    }
}
Example #24
0
/** @throw std::exception */
CrawlId LevCrawlDb::putData(const CrawlData& crawlData) {
    CrawlId crawlId = ++mNextCrawlId;
    string crawlId_str = std::to_string(crawlId);

    ParcelAllocator allocator;
    allocator.reserve(crawlData);

    ParcelEncoder encoder(allocator);
    encoder.encode(crawlData);

    string serial(encoder.getData(), encoder.getSize());
    auto ret = mDatabase->Put(leveldb::WriteOptions(), crawlId_str, serial);
    if (!ret.ok()) {
        throw std::runtime_error("Error encountered while inserting: " +
                                 crawlId_str);
    }

    return crawlId;
}
Example #25
0
Component
Component::fromNumberWithMarker(uint8_t marker, uint64_t number)
{
  EncodingEstimator estimator;

  size_t valueLength = estimator.prependNonNegativeInteger(number);
  valueLength += estimator.prependByteArray(&marker, 1);
  size_t totalLength = valueLength;
  totalLength += estimator.prependVarNumber(valueLength);
  totalLength += estimator.prependVarNumber(tlv::GenericNameComponent);

  EncodingBuffer encoder(totalLength, 0);
  encoder.prependNonNegativeInteger(number);
  encoder.prependByteArray(&marker, 1);
  encoder.prependVarNumber(valueLength);
  encoder.prependVarNumber(tlv::GenericNameComponent);

  return encoder.block();
}
void
WorldInputCmdProcessor::sendMoveCommand(const iXY& world_pos)
{
    iXY map_pos;
    PlacementMatrix matrix;

    unsigned long id_list_index;
    size_t id_list_size;
    UnitBase *unit_ptr;

    TerminalUnitCmdRequest comm_mesg;

    id_list_size = working_list.unit_list.size();

    if ( id_list_size == 0 )
        return;

    MapInterface::pointXYtoMapXY( world_pos, &map_pos );
    matrix.reset( map_pos );

    NetMessageEncoder encoder(true);

    for( id_list_index = 0; id_list_index < id_list_size; id_list_index++ ) {
        unit_ptr = UnitInterface::getUnit(working_list.unit_list[ id_list_index ]);
        if ( unit_ptr != 0 ) {
            if ( unit_ptr->unit_state.select == true ) {
                matrix.getNextEmptyLoc( &map_pos );
                comm_mesg.comm_request.setHeader(unit_ptr->id,
                        _umesg_flag_unique );

                comm_mesg.comm_request.setMoveToLoc( map_pos );
                encoder.encodeMessage(&comm_mesg,
                        sizeof(TerminalUnitCmdRequest));
            }
        }
    }

    encoder.sendEncodedMessage();

    //sfx
    sound->playUnitSound(working_list.getHeadUnitType() );
    sound->playSound("move");
}
Example #27
0
std::vector<std::shared_ptr<const X509_Certificate>> Certificate_Store_MacOS::find_all_certs(
         const X509_DN& subject_dn,
         const std::vector<uint8_t>& key_id) const
   {
   std::vector<uint8_t> dn_data;
   DER_Encoder encoder(dn_data);
   normalize(subject_dn).encode_into(encoder);

   scoped_CFType<CFDataRef> dn_cfdata(createCFDataView(dn_data));
   check_notnull(dn_cfdata, "create DN search object");

   Certificate_Store_MacOS_Impl::Query query_params(
      {
         {kSecAttrSubject, dn_cfdata.get()}
      });

   scoped_CFType<CFDataRef> keyid_cfdata(createCFDataView(key_id));
   check_notnull(keyid_cfdata, "create key ID search object");
   if(!key_id.empty())
      {
      query_params.push_back({kSecAttrSubjectKeyID, keyid_cfdata.get()});
      }

   scoped_CFType<CFArrayRef> result(m_impl->search(std::move(query_params)));

   if(!result)
      {
      return {};  // no certificates found
      }

   const auto count = CFArrayGetCount(result.get());
   BOTAN_ASSERT(count > 0, "certificate result list contains data");

   std::vector<std::shared_ptr<const X509_Certificate>> output;
   output.reserve(count);
   for(unsigned int i = 0; i < count; ++i)
      {
      auto cfCert = to_SecCertificateRef(CFArrayGetValueAtIndex(result.get(), i));
      output.emplace_back(readCertificate(cfCert));
      }

   return output;
   }
void *encoder_thread(void *arg) {
    
    encoder_space::Encoder encoder(ENCODER_COM_PORT, ENCODER_BAUD_RATE);
    encoder_space::EncoderData encoderData;
    
    while (ros::ok()) {
        /* Fetch data from Shaft Encoder and load it in local vars */
        encoderData = encoder.fetchEncoderData();

        pthread_mutex_lock(&pose_mutex);

        /* Update the pose_data using the data in local vars */

        pthread_mutex_unlock(&pose_mutex);

        usleep(10);
    }

    return NULL;
}
void CSoundCardRepeaterTXThread::transmitNetworkHeader(CHeaderData& header)
{
	wxLogMessage(wxT("Transmitting to - My: %s/%s  Your: %s  Rpt1: %s  Rpt2: %s  Flags: %02X %02X %02X"), header.getMyCall1().c_str(), header.getMyCall2().c_str(), header.getYourCall().c_str(), header.getRptCall1().c_str(), header.getRptCall2().c_str(), header.getFlag1(), header.getFlag2(), header.getFlag3());

	// Send the bit sync, 700 bits in 4 bit chunks
	for (unsigned int i = 0U; i < 175U; i++)
		m_networkBuffer.addData(BIT_SYNC_BITS, BIT_SYNC_LENGTH_BITS);

	// Send the frame sync
	m_networkBuffer.addData(FRAME_SYNC_BITS, FRAME_SYNC_LENGTH_BITS);

	// Send the header
	bool headerBits[FEC_SECTION_LENGTH_BITS];
	CRadioHeaderEncoder encoder(header);
	encoder.getRadioData(headerBits, FEC_SECTION_LENGTH_BITS);
	m_networkBuffer.addData(headerBits, FEC_SECTION_LENGTH_BITS);

	m_networkStarted = false;
	m_networkRun = 0U;
}
Example #30
0
static void
_json_BEAN_only(GString *gstr, GSList *l, gconstpointer selector,
		gboolean extend, void (*encoder)(GString*,gpointer))
{
	gboolean first = TRUE;

	for (; l ;l=l->next) {
		if (selector && DESCR(l->data) != selector)
			continue;
		if (!first)
			g_string_append_c(gstr, ',');
		first = FALSE;
		g_string_append_c (gstr, '{');
		if (extend)
			g_string_append_printf (gstr, "\"type\":\"%s\",",
					DESCR(l->data)->name);
		encoder(gstr, l->data);
		g_string_append_c (gstr, '}');
	}
}