Example #1
0
int TruncPadBase :: Execute( ALib::CommandLine & cmd ) {

	GetSkipOptions( cmd );
	string ps = cmd.GetValue( FLAG_PAD );
	ALib::CommaList padding( ps );
	unsigned int ncols = padding.Size();

	bool ncolspec = false;	// use explicit size or not

	if ( ncols == 0 || cmd.HasFlag( FLAG_NUM ) ) {
		if ( ! cmd.HasFlag( FLAG_NUM ) ) {
			CSVTHROW( "Need -n flag to specify field count" );
		}
		ncolspec = true;
		string nv = cmd.GetValue( FLAG_NUM );
		if ( ALib::ToInteger( nv, "-n flag needs integer value" ) < 0 ) {
			CSVTHROW( FLAG_NUM << " needs value greater or equal to zero" );
		}
		ncols = ALib::ToInteger( nv );
	}

	IOManager io( cmd );
	CSVRow row;

	while( io.ReadCSV( row ) ) {

		if ( Skip( io, row ) ) {
			continue;
		}

		if ( ! Pass( io, row ) ) {
			unsigned int nc = ncolspec ? ncols : row.size() + padding.Size();
			ProcessRow( row, nc, padding );
		}

		io.WriteRow( row );
	}

	return 0;
}
Example #2
0
int main(int argc,char *argv[])
{
	int opt = 0;
	PsimagLite::String file="";
	PsimagLite::String label="";
	SizeType p = 0;
	while ((opt = getopt(argc, argv,
			"f:p:l:")) != -1) {
		switch (opt) {
		case 'f':
			file = optarg;
			break;
		case 'l':
			label = optarg;
			break;
		case 'p':
			p = atoi(optarg);
			break;
		default:
			usage(argv[0]);
			return 1;
		}
	}
	// sanity checks:
	if (file=="" || label=="" || p==0) {
		usage(argv[0]);
		return 1;
	}

	PsimagLite::IoSimple::In io(file);
	PsimagLite::Vector<FieldType>::Type y;
	io.read(y,label);
	SizeType n = y.size();
	std::cout<<"#Found "<<n<<" points in file "<<file<<"\n";
	LinearPredictionType linearPrediction(y);
	linearPrediction.predict(p);
	for (SizeType i=0;i<p+n;i++) {
		std::cout<<i<<" "<<linearPrediction(i)<<"\n";
	}
}
Example #3
0
bool HHVM_FUNCTION(socket_connect,
                   const Resource& socket,
                   const String& address,
                   int port /* = 0 */) {
  auto sock = cast<Socket>(socket);

  switch (sock->getType()) {
  case AF_INET6:
  case AF_INET:
    if (port == 0) {
      raise_warning("Socket of type AF_INET/6 requires 3 arguments");
      return false;
    }
    break;
  default:
    break;
  }

  const char *addr = address.data();
  sockaddr_storage sa_storage;
  struct sockaddr *sa_ptr;
  size_t sa_size;
  if (!set_sockaddr(sa_storage, sock, addr, port, sa_ptr, sa_size)) {
    return false;
  }

  IOStatusHelper io("socket::connect", address.data(), port);
  int retval = connect(sock->fd(), sa_ptr, sa_size);
  if (retval != 0) {
    std::string msg = "unable to connect to ";
    msg += addr;
    msg += ":";
    msg += folly::to<std::string>(port);
    SOCKET_ERROR(sock, msg.c_str(), errno);
    return false;
  }

  return true;
}
Example #4
0
void	PTUser::User::addServerContact(QByteArray&	array)
{
  QDataStream	io(array);
  quint8	type;
  quint16	sizeData;
  QByteArray	clientId;
  QByteArray	bufferData;
  char		tmp[4];

  io >> type;
  io >> sizeData;

  char data[sizeData];
  io.readRawData(tmp, 4);
  clientId.append(tmp, 4);
  io.readRawData(data, array.count() - 3);
  bufferData.append(data, array.count() - 3);
  QList<QByteArray> token = bufferData.split(';');
  //create contact and Add to the list
  Contact	userFriend(token[1].constData(),token[2].constData(), 1, 1);
  _contact.push_back(userFriend);
}
Example #5
0
static int force_io(Stream_t *Stream,
		    char *buf, mt_off_t start, size_t len,
		    int (*io)(Stream_t *, char *, mt_off_t, size_t))
{
	int ret;
	int done=0;
	
	while(len){
		ret = io(Stream, buf, start, len);
		if ( ret <= 0 ){
			if (done)
				return done;
			else
				return ret;
		}
		start += ret;
		done += ret;
		len -= ret;
		buf += ret;
	}
	return done;
}
Example #6
0
main()
  {
  unsigned char data[32768];
  Scroll *reg;
  Scope *s;
  int x;
  izws();
  reg = new Scroll();
    reg->sth(300);
    reg->stw(400);
    s = new Scope();
      for (x = 0; x != 32768; ++x)
    	data[x] = 128 + 127 * sin(x * M_PI * 256.0 / 32768.0);
      s->st(data);
    reg->st(s);
  root->add(reg);
  for (;;)
    {
    wsflsh();
    io();
    }
  }
Example #7
0
void mode_check()
{ 
   //check if user wants to mod flash vars
   if (! initialise_flash()){
      // set heartbeat_led on permanently symbolise fail
       quan::stm32::module_enable< heartbeat_led_pin::port_type>();
         quan::stm32::apply<
            heartbeat_led_pin
            , quan::stm32::gpio::mode::output
            , quan::stm32::gpio::otype::push_pull
            , quan::stm32::gpio::pupd::none
            , quan::stm32::gpio::ospeed::slow
            , quan::stm32::gpio::ostate::high
         >();
      while (1){;}
   }
  
   flash_menu_sp::init();
   input_output io;
   bool want_menu = false;
   for ( uint32_t i = 0; i < 60 ; ++i){
      // crude method of timing for a  approx 4 sec delay
      // to allow user to press return 3 x
      // after startup
      // causes a bit of flicker but keeps text static
      if ( io("Press return 3 times for Flash Menu"
             "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b") ){
         want_menu = true;
         break;
      }
   }
   if ( want_menu){
      
      do_flash_vars();
   }else{
      flash_menu_sp::write("\n\nTime is up! ... Exiting to Flight mode\n\n");
      return;
   } 
}
Example #8
0
bool MySQL::connect(const String& host, int port, const String& socket,
                    const String& username, const String& password,
                    const String& database, int client_flags,
                    int connect_timeout) {
  if (m_conn == nullptr) {
    m_conn = create_new_conn();
  }
  if (connect_timeout >= 0) {
    MySQLUtil::set_mysql_timeout(m_conn, MySQLUtil::ConnectTimeout,
                                 connect_timeout);
  }
  if (RuntimeOption::EnableStats && RuntimeOption::EnableSQLStats) {
    ServerStats::Log("sql.conn", 1);
  }
  IOStatusHelper io("mysql::connect", host.data(), port);
  m_xaction_count = 0;
  if (m_host.empty()) m_host = static_cast<std::string>(host);
  if (m_username.empty()) m_username = static_cast<std::string>(username);
  if (m_password.empty()) m_password = static_cast<std::string>(password);
  if (m_socket.empty()) m_socket = static_cast<std::string>(socket);
  if (m_database.empty()) m_database = static_cast<std::string>(database);
  if (!m_port) m_port = port;
  bool ret = mysql_real_connect(m_conn, host.data(), username.data(),
                            password.data(),
                            (database.empty() ? nullptr : database.data()),
                            port,
                            socket.empty() ? nullptr : socket.data(),
                            client_flags);
  if (ret && mysqlExtension::WaitTimeout > 0) {
    String query("set session wait_timeout=");
    query += String((int64_t)(mysqlExtension::WaitTimeout / 1000));
    if (mysql_real_query(m_conn, query.data(), query.size())) {
      raise_notice("MySQL::connect: failed setting session wait timeout: %s",
                   mysql_error(m_conn));
    }
  }
  m_state = (ret) ? MySQLState::CONNECTED : MySQLState::CLOSED;
  return ret;
}
void
nsChromeRegistryContent::RegisterOverride(const OverrideMapping& aOverride)
{
  nsCOMPtr<nsIIOService> io (do_GetIOService());
  if (!io)
    return;

  nsCOMPtr<nsIURI> chromeURI, overrideURI;
  nsresult rv = NS_NewURI(getter_AddRefs(chromeURI),
                          aOverride.originalURI.spec,
                          aOverride.originalURI.charset.get(),
                          nullptr, io);
  if (NS_FAILED(rv))
    return;

  rv = NS_NewURI(getter_AddRefs(overrideURI), aOverride.overrideURI.spec,
                 aOverride.overrideURI.charset.get(), nullptr, io);
  if (NS_FAILED(rv))
    return;
  
  mOverrideTable.Put(chromeURI, overrideURI);
}
Example #10
0
int WriteFixedCommand :: Execute( ALib::CommandLine & cmd ) {

	GetSkipOptions( cmd );
	BuildFields( cmd );

	IOManager io( cmd );

	if ( cmd.HasFlag( FLAG_RULER ) ) {
		io.Out() << Ruler() << "\n";
	}

	CSVRow row;
	while( io.ReadCSV( row ) ) {
		if ( Skip( row ) ) {
			continue;
		}
		string line = MakeFixedOutput( row );
		io.Out() << line << "\n";
	}

	return 0;
}
bool CGMSKModemWinUSB::open()
{
	wxASSERT(m_handle == INVALID_HANDLE_VALUE);

	bool res = openModem();
	if (!res) {
		wxLogError(wxT("Cannot find the GMSK Modem with address: 0x%04X"), m_address);
		return false;
	}

	wxLogInfo(wxT("Found the GMSK Modem with address: 0x%04X"), m_address);

	wxString version;

	int ret;
	do {
		unsigned char buffer[GMSK_MODEM_DATA_LENGTH];
		ret = io(GET_VERSION, 0xC0U, 0U, buffer, GMSK_MODEM_DATA_LENGTH);
		if (ret > 0) {
			wxString text((char*)buffer, wxConvLocal, ret);
			version.Append(text);
		} else if (ret < 0) {
			wxLogError(wxT("GET_VERSION returned %d"), -ret);
			close();
			return false;
		}
	} while (ret == int(GMSK_MODEM_DATA_LENGTH));

	wxLogInfo(wxT("Firmware version: %s"), version.c_str());

	// Trap firmware version 0.1.00 of DUTCH*Star and complain loudly
	if (version.Find(wxT("DUTCH*Star")) != wxNOT_FOUND && version.Find(wxT("0.1.00")) != wxNOT_FOUND) {
		wxLogWarning(wxT("This modem firmware is not fully supported by the GMSK Repeater"));
		wxLogWarning(wxT("Please upgrade to a newer version if possible"));
		m_broken = true;
	}

	return true;
}
Example #12
0
int ExcludeCommand :: Execute( ALib::CommandLine & cmd ) {

	GetSkipOptions( cmd );
	ProcessFlags( cmd );

	IOManager io( cmd );
	CSVRow row;

	while( io.ReadCSV( row ) ) {
		if ( Skip( row ) ) {
			continue;
		}
		if ( ! Pass( row ) ) {
			if ( EvalExprOnRow( io, row ) ) {
				Exclude( row );
			}
		}
		io.WriteRow( row );
	}

	return 0;
}
Example #13
0
int FileInfoCommand :: Execute( ALib::CommandLine & cmd ) {

	GetSkipOptions( cmd );
	mTwoCols = cmd.HasFlag( FLAG_TWOC );
	mBasename = cmd.HasFlag( FLAG_BASEN );

	IOManager io( cmd );

	CSVRow row;
	while( io.ReadCSV( row ) ) {
		if ( Skip( io, row ) ) {
			continue;
		}
		if ( Pass( io, row ) ) {
			io.WriteRow( row );
			continue;
		}

		string fname = mBasename
						? ALib::Filename( io.CurrentFileName() ).Base()
						: io.CurrentFileName();

		CSVRow outrow;
		if ( mTwoCols ) {
			outrow.push_back( fname );
			outrow.push_back( ALib::Str( io.CurrentLine() ));
		}
		else {
			outrow.push_back( fname + " ("
				+ ALib::Str( io.CurrentLine() ) + ")"
			);
		}
		ALib::operator+=( outrow, row );
		io.WriteRow( outrow );
	}

	return 0;
}
Example #14
0
int main(){

	Scheduler s;

	ProcessNode& effects = s.add<ProcessNode>(); // add effects group
	//s.add<Echo>(effects); // add Echo to effects
	//s.add<Chorus1>(effects); // add chorus to effects

	s.add<ChorusEffect>(effects); // add chorus to effects
	s.add<EchoEffect>(effects); // add Echo to effects

	double attack = 0.1;
	double decay = 0.1;
	double pan = 0.0; 

	double clip = 0.05;

	double q=0.25 - clip;
	// double e=0.125 - clip;
	double h=0.5 - clip;
	//  double w=1.0 - clip;

	double start = 0.0;
	double aug = 1.0;
	double dyn = 0.2;

	s.add<SineEnv>( start + 0     ).set( aug * q, doh, dyn, attack, decay, -1.0*pan);
	s.add<SineEnv>( start + (0.5*aug)  ).set( aug * q, me, dyn, attack, decay, -0.8*pan);
	s.add<SineEnv>( start + (1.0*aug)   ).set( aug * q, sol, dyn, attack, decay, -0.6*pan);
	s.add<SineEnv>( start + (1.5*aug)  ).set( aug * q, le, dyn, attack, decay, -0.4*pan);
	s.add<SineEnv>( start + (2.00*aug)  ).set( aug * h+q, ti, dyn, attack, decay, -0.2*pan);


	AudioIO io(256, 44100., Scheduler::audioCB, &s);
	gam::sampleRate(io.fps());
	io.start();
	printf("\nPress 'enter' to quit...\n"); getchar();
}
Example #15
0
void MainWindow::openDocument(const QUrl &url)
{
    Q_D(MainWindow);
    if (!url.isLocalFile()) {
        return;
    }

    d->_url = url;

    using Result = std::pair<ImageIOResult, ImageContents>;

    auto worker = [](const QString &path)
    {
        ImageIO io(path);
        return io.read();
    };

    auto finisher = [this, d]()
    {
        const auto watcher = static_cast<QFutureWatcher<Result> *>(sender());
        const auto result = watcher->future().result();
        const auto &status = result.first;
        const auto &contents = result.second;
        watcher->deleteLater();
        if (status) {
            d->_document->setContents(contents);
        } else {
            QMessageBox::warning(this,
                                 tr("Open"),
                                 tr("Can't open file"),
                                 QMessageBox::Close);
        }
    };

    auto watcher = new QFutureWatcher<Result>(this);
    connect(watcher, &QFutureWatcherBase::finished, this, finisher);
    watcher->setFuture(QtConcurrent::run(worker, url.toLocalFile()));
}
Example #16
0
int main(){

	// set parameters of audio stream
	int blockSize = 64;				// how many samples per block?
	float sampleRate = 44100;		// sampling rate (samples/second)
	int outputChannels = 2;			// how many output channels to open
	int inputChannels = 1;			// how many input channels to open
	UserData user = {-0.5, 0.5};	// external data to be passed into callback

	printf("Audio devices found:\n");
	AudioDevice::printAll();
	printf("\n");

	// create an audio i/o object using default input and output devices
	AudioIO io(blockSize, sampleRate, audioCB, &user, outputChannels, inputChannels);

	// we can also set the input and output devices explicitly
	// use device 0 for input and output
	//io.deviceIn (AudioDevice(0));
	//io.deviceOut(AudioDevice(0));

	// use devices matching keyword in name
	//io.deviceIn (AudioDevice("Microphone", AudioDevice::INPUT));
	//io.deviceOut(AudioDevice("Built-in", AudioDevice::OUTPUT));

	// set the global sample rate "subject"
	Sync::master().spu(io.framesPerSecond());
	
	// start the audio stream
	io.start();
	
	// print some information about the i/o streams
	printf("Audio stream info:\n");
	io.print();
	
	printf("\nPress 'enter' to quit...\n"); getchar();
	return 0;
}
Example #17
0
int main(){
	
	ArrayPow2<float> tbSin(2048), tbSqr(2048), tbSaw(2048);
	addWave(tbSin, SINE);
	addWave(tbSqr, SQUARE);
	addWave(tbSaw, SAW);
	
	Scheduler s;
	s.add<OscTrm>( 0).set(10, 262, 0.5, 0.1,2,0.8, 0.4,4,8,0.5, tbSin, 0.8); 
	
	s.add<OscTrm>(11).set(10, 262, 0.5, 0.1,2,0.8, 0.4,4,8,0.5, tbSqr, 0.8); 
	
	s.add<OscTrm>(20).freq(120).table(tbSaw);
	
	s.add<OscTrm>(30).set(20, 262, 0.5, 0.1,2,0.8, 0.4,4,80,0.2, tbSin, 0.8); 
	
	s.add<OscTrm>(50).set(10, 262, 0.5, 0.1,2,0.8, 0.8,4,8,0.5, tbSin, 0.8); 
	
	AudioIO io(256, 44100., Scheduler::audioCB, &s);
	gam::sampleRate(io.fps());
	io.start();
	printf("\nPress 'enter' to quit...\n"); getchar();
}
Example #18
0
nitf::Record doRead(const std::string& inFile)
{
    nitf::Reader reader;
    nitf::IOHandle io(inFile);
    nitf::Record record = reader.read(io);

    /*  Set this to the end, so we'll know when we're done!  */
    nitf::ListIterator end = record.getImages().end();
    nitf::ListIterator iter = record.getImages().begin();
    for (int count = 0, numImages = record.getHeader().getNumImages();
            count < numImages && iter != end; ++count, ++iter)
    {
        nitf::ImageSegment imageSegment = *iter;
        nitf::ImageReader deserializer = reader.newImageReader(count);
        std::cout << "Writing image " << count << "..." << std::endl;

        /*  Write the thing out  */
        manuallyWriteImageBands(imageSegment, inFile, deserializer, count);
        std::cout << "done.\n" << std::endl;
    }

    return record;
}
Example #19
0
int Socket::readImpl(char *buffer, int length) {
  ASSERT(m_fd);
  ASSERT(length > 0);

  int recvFlags = 0;
  if (m_timeout > 0) {
    int flags = fcntl(m_fd, F_GETFL, 0);
    if ((flags & O_NONBLOCK) == 0) {
      if (!waitForData()) {
        m_eof = true;
        return 0;
      }
      recvFlags = MSG_DONTWAIT; // polled, so no need to wait any more
    }
  }

  IOStatusHelper io("socket::recv", m_address.c_str(), m_port);
  int ret = recv(m_fd, buffer, length, recvFlags);
  if (ret == 0 || (ret == -1 && errno != EWOULDBLOCK)) {
    m_eof = true;
  }
  return (ret < 0) ? 0 : ret;
}
bool MultipleDocumentsReadingModeSelectorController::mergeDocumentOption(const FormatDetectionResult& formatResult, QMap<QString, qint64>* headerSequenceLengths){
    QVariantMap docHints = formatResult.rawDataCheckResult.properties;
    if(formatResult.format == NULL){
        return false;
    }
    if(formatResult.format->getFormatId() == BaseDocumentFormats::PLAIN_GENBANK){
        if(docHints.value(RawDataCheckResult_Sequence) == false){
            static const int MAX_LINE = 8192;
            char buff[MAX_LINE + 1] = {0};

            QScopedPointer<LocalFileAdapterFactory> factory( new LocalFileAdapterFactory());
            QScopedPointer<IOAdapter> io(factory->createIOAdapter());
            if(!io->open(formatResult.url, IOAdapterMode_Read)){
                return false;
            }
            bool terminatorFound = false;
            io->readLine(buff, MAX_LINE, &terminatorFound);
            if(!terminatorFound){
                return false;
            }
            QString line = QString(QByteArray(buff));
            QStringList words = line.split(QRegExp("\\s"), QString::SkipEmptyParts);
            if(words.size() < 3){ // origin len not defined
                return false;
            }
            bool isLenDefined = false;
            qint64 seqLen = words[2].toLongLong(&isLenDefined); 
            
            if(!isLenDefined || seqLen <= 0){
                return false;
            }
            (*headerSequenceLengths)[formatResult.url.getURLString()] = seqLen;
            return true;
        }
    }
    return docHints.value(RawDataCheckResult_Sequence).toBool();
}
void ut_class_test(void)
{
	al::AudioIO io(64, 44100, 0, 0, 2, 2, al::AudioIO::DUMMY); // Dummy Audio Backend
	al::Decorrelation dec(32, 1, 1, false);
	dec.configure(io, 1000);
	assert(dec.getCurrentSeed() == 1000);
	assert(dec.getSize() == 32);

	float *ir = dec.getIR(0);
	double expected[] = {0.65027274, -0.16738815,  0.1617437 ,  0.18901241,  0.01768662,
						 -0.0802799 , -0.12612745,  0.09564361,  0.00803435,  0.07643685,
						 -0.030273  ,  0.26991193, -0.03412993, -0.05709789,  0.05474607,
						 -0.12850219,  0.03040506, -0.05887395,  0.05779415,  0.12589107,
						 0.0778308 , -0.19303948,  0.16970104, -0.34332016, -0.14030879,
						 0.02862106,  0.18978155,  0.02629568, -0.09265464, -0.04808504,
						 0.00549774,  0.26477413};
	for (int i = 0; i < 32; i++) {
//		std::cout << ir[i] << "..." << expected[i];
		assert(fabs(ir[i] - expected[i]) < 0.000001);
	}
	std::cout << std::endl;

	al::Decorrelation dec2(1024, 1, 32, false);
	dec2.configure(io, 1001);
	assert(dec2.getCurrentSeed() == 1001);
	assert(dec2.getSize() == 1024);


	al::Decorrelation dec3(10, 1, 8, false);
	dec3.configure(io, 1001);
	assert(dec3.getCurrentSeed() == 1001);
	assert(dec3.getSize() == 0); // Size of 10 is too small

	al::Decorrelation dec4(32, 1, 0);
	dec4.configure(io, 1001);
	assert(dec4.getSize() == 0); // Num Outs is 0
}
Example #22
0
int ReadXMLCommand :: Execute( ALib::CommandLine & cmd ) {

	IOManager io( cmd );

	for ( unsigned int i = 0; i < io.InStreamCount(); i++ ) {
		ALib::XMLTreeParser tp;
		std::auto_ptr<ALib::XMLElement>	safe_root(
					tp.ParseStream( io.In(i) )
		);

		ALib::XMLElement * root = safe_root.get();

		if ( root == 0 ) {
			CSVTHROW( "XML error '" << tp.ErrorMsg()
						<< "' in " << io.InFileName( i )
						<< " at line " << tp.ErrorLine()
			);
		}

		TableToCSV( root, io, i );
	}

	return 0;
}
Example #23
0
Document* DocumentFormat::loadDocument(IOAdapterFactory* iof, const GUrl& url, const QVariantMap& hints, U2OpStatus& os) {
    QScopedPointer<IOAdapter> io(iof->createIOAdapter());
    if (!io->open(url, IOAdapterMode_Read)) {
        os.setError(L10N::errorOpeningFileRead(url));
        return NULL;
    }

    Document* res = NULL;

    U2DbiRef dbiRef = fetchDbiRef(hints, os);
    CHECK_OP(os, NULL);

    if (dbiRef.isValid()) {
        DbiConnection con(dbiRef, os);
        CHECK_OP(os, NULL);
        Q_UNUSED(con);

        res = loadDocument(io.data(), dbiRef, hints, os);
        CHECK_OP(os, NULL);
    } else {
        res = loadDocument(io.data(), U2DbiRef(), hints, os);
    }
    return res;
}
Example #24
0
int main(void) {
	clock_t start, en;
	start = clock();
	int sten = 1, i = 0, l = 0, win = 0;
	FILE * save;

	rule();
	io();

	while (sten == 1) {
		i++;
		win = game();
		sten = end();
	}
	if (win == 0)l++;
	save = fopen("save.txt", "a");
	fprintf(save, "%d:", i);
	fprintf(save, "%d:", l);
	en = clock();
	fprintf(save, "%d[ms]:", en - start);
	fclose(save);
	//name:回数:勝利回数:時間
	return 0;
}
Example #25
0
Variant f_time_nanosleep(int seconds, int nanoseconds) {
  if (seconds < 0) {
    throw_invalid_argument("seconds: cannot be negative");
    return false;
  }
  if (nanoseconds < 0 || nanoseconds > 999999999) {
    throw_invalid_argument("nanoseconds: has to be 0 to 999999999");
    return false;
  }

  struct timespec req, rem;
  req.tv_sec = (time_t)seconds;
  req.tv_nsec = nanoseconds;

  IOStatusHelper io("nanosleep");
  if (!nanosleep(&req, &rem)) {
    return true;
  }
  if (errno == EINTR) {
    return make_map_array(s_seconds, (int64_t)rem.tv_sec,
                       s_nanoseconds, (int64_t)rem.tv_nsec);
  }
  return false;
}
Example #26
0
bool f_socket_connect(CObjRef socket, CStrRef address, int port /* = 0 */) {
  Socket *sock = socket.getTyped<Socket>();

  switch (sock->getType()) {
  case AF_INET6:
  case AF_INET:
    if (port == 0) {
      raise_warning("Socket of type AF_INET/6 requires 3 arguments");
      return false;
    }
    break;
  default:
    break;
  }

  const char *addr = address.data();
  sockaddr_storage sa_storage;
  struct sockaddr *sa_ptr;
  size_t sa_size;
  if (!set_sockaddr(sa_storage, sock, addr, port, sa_ptr, sa_size)) {
    return false;
  }

  IOStatusHelper io("socket::connect", address.data(), port);
  int retval = connect(sock->fd(), sa_ptr, sa_size);
  if (retval != 0) {
    std::string msg = "unable to connect to ";
    msg += addr;
    msg += ":";
    msg += boost::lexical_cast<std::string>(port);
    SOCKET_ERROR(sock, msg.c_str(), errno);
    return false;
  }

  return true;
}
Example #27
0
Variant HHVM_FUNCTION(gethostbyaddr, const String& ip_address) {
  IOStatusHelper io("gethostbyaddr", ip_address.data());
  struct addrinfo hints, *res, *res0;
  char h_name[NI_MAXHOST];
  int error;

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = PF_UNSPEC;
  error = getaddrinfo(ip_address.data(), NULL, &hints, &res0);
  if (error)  {
    return false;
  }

  for (res = res0; res; res = res->ai_next) {
    if (getnameinfo(res->ai_addr, res->ai_addrlen, h_name, NI_MAXHOST,
          NULL, 0, 0) < 0) {
      continue;
    }
    freeaddrinfo(res0);
    return String(h_name, CopyString);
  }
  freeaddrinfo(res0);
  return ip_address;
}
Example #28
0
void nsChromeRegistryContent::RegisterSubstitution(
    const SubstitutionMapping& aSubstitution) {
  nsCOMPtr<nsIIOService> io(do_GetIOService());
  if (!io) return;

  nsCOMPtr<nsIProtocolHandler> ph;
  nsresult rv =
      io->GetProtocolHandler(aSubstitution.scheme.get(), getter_AddRefs(ph));
  if (NS_FAILED(rv)) return;

  nsCOMPtr<nsISubstitutingProtocolHandler> sph(do_QueryInterface(ph));
  if (!sph) return;

  nsCOMPtr<nsIURI> resolvedURI;
  if (aSubstitution.resolvedURI.spec.Length()) {
    rv = NS_NewURI(getter_AddRefs(resolvedURI), aSubstitution.resolvedURI.spec,
                   nullptr, nullptr, io);
    if (NS_FAILED(rv)) return;
  }

  rv = sph->SetSubstitutionWithFlags(aSubstitution.path, resolvedURI,
                                     aSubstitution.flags);
  if (NS_FAILED(rv)) return;
}
Example #29
0
int main(int argc, char **args)
{
  char release[]={"$Name: Release-0-3 $"};
  char *loc0=strchr(release,'-');
  if(loc0>0){
    loc0++;
    char *loc=loc0;
    do{
      loc=strchr(loc,'-');
      if(loc)*loc='.';
    }while(loc);
    release[strlen(release)-1]='\0'; // Strip off $
  }

  printf("Release %s\n",loc0);

  
  
  IOParport io(PPDEV);
  int chainpos=0;
  if(io.checkError()){
    fprintf(stderr,"Could not access parallel device '%s'.\n",PPDEV);
    fprintf(stderr,"You may need to set permissions of '%s' ",PPDEV);
    fprintf(stderr,"by issuing the following command as root:\n\n# chmod 666 %s\n\n",PPDEV);
  }
  if(argc<=1){
    fprintf(stderr,"\nUsage: %s infile.bit [POS]\n\n",args[0]);
    fprintf(stderr,"\tPOS  position in JTAG chain, 0=closest to TDI (default)\n\n",args[0]);
    return 1;
  }
  if(argc>2)chainpos=atoi(args[2]);
  BitFile file;
  if(file.load(args[1]))process(io,file,chainpos);
  else return 1;
  return 0;
}
Example #30
0
int FileSplitCommand :: Execute( ALib::CommandLine & cmd ) {

	GetSkipOptions( cmd );
	ProcessFlags( cmd );

	IOManager io( cmd );
	CSVRow row;

	while( io.ReadCSV( row ) ) {
		if ( Skip( row ) ) {
			continue;
		}
		if ( Pass( row ) ) {
			io.WriteRow( row  );
		}
		else {
			WriteRow( io, row );
		}
	}

	mOutFile.flush();

	return 0;
}