Esempio n. 1
0
int main(int argc, const char * argv[])
{
    Buffer buffer;
    Storage disk;
    Record::buffer=&buffer;
    Bptree_node::buffer=&buffer;
    Bptree::buffer=&buffer;
    Record record;
    Table_info table;
    table.table_name="friendg";
    table.database="zyh";
    Attribute attribute;
    Tuple_data tuple_data(90);
    Tuple_info tuple;
    table.tuple_size=21;
    attribute.type=SQL_INT;
    attribute.size=4;
    table.attribute_list.push_back(attribute);
    attribute.type=SQL_STRING;
    attribute.size=6;
    table.attribute_list.push_back(attribute);
    attribute.type=SQL_STRING;
    attribute.size=4;
    table.attribute_list.push_back(attribute);
    attribute.type=SQL_STRING;
    attribute.size=3;
    table.attribute_list.push_back(attribute);
    attribute.attribute_name="result";
    attribute.type=SQL_FLOAT;
    attribute.size=4;
    table.attribute_list.push_back(attribute);
    tuple.info.push_back("44");
    tuple.info.push_back("abcde");
    tuple.info.push_back("ac");
    tuple.info.push_back("ac");
    tuple.info.push_back("44.4");
    Tuple_info tuple_unpack;
    for (int i=0;i<5;i++)
        tuple_unpack.info.push_back("");
    try
    {
        record.pack(table,tuple,&tuple_data);
    }
    catch (Error error)
    {
        error.print_error();
    }
    printf("before unpack\n");
      printf("\n");
    record.unpack(table,&tuple_unpack,&tuple_data);
    for (int i=0;i<5;i++)
        std::cout<<tuple_unpack.info[i]<<std::endl;
    for (int i=0;i<30;i++)
        printf("%X  ",tuple_data.data[i]);
    printf("\n");
    Storage storage;
    record.create_table(table);
    record.insert_tuple(table, tuple_unpack);
    record.insert_tuple(table, tuple_unpack);
    record.insert_tuple(table, tuple_unpack);
    Address del_address;
    del_address=record.int_to_address(table, 12);
    record.delete_tuple(table, del_address);
    del_address=record.int_to_address(table, 41);
    record.delete_tuple(table, del_address);
    record.insert_tuple(table, tuple_unpack);
    Tuple_info new_tuple;
    new_tuple.info.push_back("55");
    new_tuple.info.push_back("qqqq");
    new_tuple.info.push_back("ac");
    new_tuple.info.push_back("ac");
    new_tuple.info.push_back("32.2");
    record.insert_tuple(table, new_tuple);
    Tuple_info get_tuple(5);
    Address next_address;
    record.get_first_tuple(table, &get_tuple, &next_address);
    while (!(next_address.block_offset==0 && next_address.file_offset==0))
    {
        for (int i=0;i<5;i++)
        {
            std::cout<<get_tuple.info[i]<<std::endl;
        }
        std::cout<<"next"<<std::endl;
        Address address=next_address;
        record.get_tuple(table, address,&get_tuple, &next_address);
    }
    for (int i=0;i<5;i++)
    {
        std::cout<<get_tuple.info[i]<<std::endl;
    }
    Bptree bptree;
    Table_info table2;
    table2.table_name="friendindex";
    table2.database="zyh";
    table2.tuple_size=2400;
    attribute.type=SQL_STRING;
    attribute.size=2400;
    table2.attribute_list.push_back(attribute);
//    Tuple_info tuple2;
//    Address add;
//    tuple2.info.push_back("a");
//    tuple2.info[0]="b";
//    Address finded;
//    Address nnext_address;
//    Tuple_info finded_tuple;
//    finded=bptree.search(table2, attribute, "b");
//    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
//    std::cout<<finded_tuple.info[0]<<std::endl;
    //1
    Tuple_info tuple2;
    tuple2.info.push_back("a");
    record.create_table(table2);
    Address add;
    add=record.insert_tuple(table2, tuple2);
    bptree.drop(table2, attribute);
    bptree.create(table2, attribute);
    bptree.insert(table2, attribute, "a", add);
    Address finded=bptree.search(table2, attribute, "a");
    Tuple_info finded_tuple;
    Address nnext_address;
    //2
    tuple2.info[0]="b";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "b", add);
    finded=bptree.search(table2, attribute, "b");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    //3
    tuple2.info[0]="c";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "c", add);
    finded=bptree.search(table2, attribute, "c");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.print(table2,attribute);

    std::cout<<finded_tuple.info[0]<<std::endl;
    //4
    tuple2.info[0]="d";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "d", add);
    finded=bptree.search(table2, attribute, "d");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    //5
    tuple2.info[0]="f";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "f", add);
    finded=bptree.search(table2, attribute, "f");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    //6
    tuple2.info[0]="e";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "e", add);
    finded=bptree.search(table2, attribute, "e");
//    record.get_tuple(table2, add, &finded_tuple, &nnext_address);
//    std::cout<<finded_tuple.info[0]<<std::endl;
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    //6
    tuple2.info[0]="g";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "g", add);
    finded=bptree.search(table2, attribute, "g");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    //7
    tuple2.info[0]="q";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "q", add);
    finded=bptree.search(table2, attribute, "q");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    //3
    tuple2.info[0]="h";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "h", add);
    finded=bptree.search(table2, attribute, "h");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    //8
    tuple2.info[0]="z";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "z", add);
//    bptree.print(table2,attribute);

    finded=bptree.search(table2, attribute, "z");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    //9
    tuple2.info[0]="y";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "y", add);
    //    bptree.print(table2,attribute);
    
    finded=bptree.search(table2, attribute, "y");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
//10
    tuple2.info[0]="w";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "w", add);
    //    bptree.print(table2,attribute);
    
    finded=bptree.search(table2, attribute, "w");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
//11
    tuple2.info[0]="u";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "u", add);
    //    bptree.print(table2,attribute);
    
    finded=bptree.search(table2, attribute, "u");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);

//12
    tuple2.info[0]="v";
    add=record.insert_tuple(table2, tuple2);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    bptree.insert(table2, attribute, "v", add);
    //    bptree.print(table2,attribute);
    
    finded=bptree.search(table2, attribute, "v");
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    bptree.print(table2,attribute);
    record.delete_tuple(table2, finded);
    bptree.deletion(table2, attribute, "v");
    add=bptree.search(table2, attribute, "v");
    add=record.insert_tuple(table2, tuple2);
    bptree.insert(table2, attribute, "v", add);
    record.get_tuple(table2, finded, &finded_tuple, &nnext_address);
    std::cout<<finded_tuple.info[0]<<std::endl;
    std::cout<<add.address_int()<<std::endl;
    Address begin,end;
    bptree.search_section(table2, attribute, false, "inf", false, "inf", &begin, &end);
    int loop_address=begin.address_int();
    for (int i=loop_address;i<end.address_int();i+=ADDRESS_SIZE)
    {
        Address now(begin.database_name,begin.file_name,i);
        Address_byte record_address;
        Block block;
        buffer.read_data(now,&block);
        block.get_block_data(now.block_offset, ADDRESS_SIZE, record_address.byte);
        Address record_add=Address(table2.database,table2.table_name,record_address.address);
        record.get_tuple(table2, record_add, &finded_tuple, &nnext_address);
        std::cout<<finded_tuple.info[0]<<std::endl;
    }
    if (end.address_int()>loop_address)
    {
        buffer.remove_file(begin);
    }
    
//        bptree.test(table,attribute);
//    record.drop_table(table);
//    uuid_t uu;
//    int i;
//    uuid_generate( uu );
//    
//    for(i=0;i<16;i++)
//    {
//        printf("%02X-",uu[i]);
//    }
//    printf("\n");
//    uuid_string_t strc;
//    uuid_unparse_upper(uu,strc);
//    std::cout<<strc<<std::endl;
    return 0;
}
Esempio n. 2
0
/**
 * Logs the details of this crash and shows an error.
 * @param ex Pointer to exception data (PEXCEPTION_POINTERS on Windows, signal int on Unix)
 * @param err Exception message, if any.
 */
void crashDump(void *ex, const std::string &err)
{
	std::ostringstream error;
#ifdef _MSC_VER
	PEXCEPTION_POINTERS exception = (PEXCEPTION_POINTERS)ex;
	std::exception *cppException = 0;
	switch (exception->ExceptionRecord->ExceptionCode)
	{
	case EXCEPTION_CODE_CXX:
		cppException = (std::exception *)exception->ExceptionRecord->ExceptionInformation[1];
		error << cppException->what();
		break;
	case EXCEPTION_ACCESS_VIOLATION:
		error << "Memory access violation. This usually indicates something missing in a mod.";
		break;
	default:
		error << "code 0x" << std::hex << exception->ExceptionRecord->ExceptionCode;
		break;
	}
	Log(LOG_FATAL) << "A fatal error has occurred: " << error.str();
	stackTrace(exception->ContextRecord);
	std::string dumpName = Options::getUserFolder();
	dumpName += now() + ".dmp";
	HANDLE dumpFile = CreateFileA(dumpName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	MINIDUMP_EXCEPTION_INFORMATION exceptionInformation;
	exceptionInformation.ThreadId = GetCurrentThreadId();
	exceptionInformation.ExceptionPointers = exception;
	exceptionInformation.ClientPointers = FALSE;
	if (MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, MiniDumpNormal, exception ? &exceptionInformation : NULL, NULL, NULL))
	{
		Log(LOG_FATAL) << "Crash dump generated at " << dumpName;
	}
	else
	{
		Log(LOG_FATAL) << "No crash dump generated: " << GetLastError();
	}
#else
	if (ex == 0)
	{
		error << err;
	}
	else
	{
		int signal = *((int*)ex);
		switch (signal)
		{
		case SIGSEGV:
			error << "Segmentation fault. This usually indicates something missing in a mod.";
			break;
		default:
			error << "signal " << signal;
			break;
		}
	}
	Log(LOG_FATAL) << "A fatal error has occurred: " << error.str();
	stackTrace(0);
#endif
	std::ostringstream msg;
	msg << "OpenXcom has crashed: " << error.str() << std::endl;
	msg << "Extra information has been saved to openxcom.log." << std::endl;
	msg << "If this error was unexpected, please report it to the developers.";
	showError(msg.str());
}
Esempio n. 3
0
 virtual void schedule(const schedulable& scbl) const {
     queue::push(queue::item_type(now(), scbl));
 }
Esempio n. 4
0
bool QAudioInputPrivate::open()
{
#ifdef DEBUG_AUDIO
    QTime now(QTime::currentTime());
    qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif
    header = 0;
    if(buffer_size == 0) {
        // Default buffer size, 200ms, default period size is 40ms
        buffer_size = settings.frequency()*settings.channels()*(settings.sampleSize()/8)*0.2;
        period_size = buffer_size/5;
    } else {
        period_size = buffer_size/5;
    }
#ifdef Q_OS_WINCE
    // For wince reduce size to 40ms for buffer size and 20ms period
    buffer_size = settings.sampleRate()*settings.channelCount()*(settings.sampleSize()/8)*0.04;
    period_size = buffer_size/2;
#endif
    timeStamp.restart();
    elapsedTimeOffset = 0;
    wfx.nSamplesPerSec = settings.frequency();
    wfx.wBitsPerSample = settings.sampleSize();
    wfx.nChannels = settings.channels();
    wfx.cbSize = 0;

    wfx.wFormatTag = WAVE_FORMAT_PCM;
    wfx.nBlockAlign = (wfx.wBitsPerSample >> 3) * wfx.nChannels;
    wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;

    UINT_PTR devId = WAVE_MAPPER;

    WAVEINCAPS wic;
    unsigned long iNumDevs,ii;
    iNumDevs = waveInGetNumDevs();
    for(ii=0; ii<iNumDevs; ii++) {
        if(waveInGetDevCaps(ii, &wic, sizeof(WAVEINCAPS))
                == MMSYSERR_NOERROR) {
            QString tmp;
            tmp = QString((const QChar *)wic.szPname);
            if(tmp.compare(QLatin1String(m_device)) == 0) {
                devId = ii;
                break;
            }
        }
    }

    if(waveInOpen(&hWaveIn, devId, &wfx,
                  (DWORD_PTR)&waveInProc,
                  (DWORD_PTR) this,
                  CALLBACK_FUNCTION) != MMSYSERR_NOERROR) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        qWarning("QAudioInput: failed to open audio device");
        return false;
    }
    waveBlocks = allocateBlocks(period_size, buffer_size/period_size);

    if(waveBlocks == 0) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        qWarning("QAudioInput: failed to allocate blocks. open failed");
        return false;
    }

    EnterCriticalSection(&waveInCriticalSection);
    waveFreeBlockCount = buffer_size/period_size;
    LeaveCriticalSection(&waveInCriticalSection);

    waveCurrentBlock = 0;

    for(int i=0; i<buffer_size/period_size; i++) {
        result = waveInAddBuffer(hWaveIn, &waveBlocks[i], sizeof(WAVEHDR));
        if(result != MMSYSERR_NOERROR) {
            qWarning("QAudioInput: failed to setup block %d,err=%d",i,result);
            errorState = QAudio::OpenError;
            deviceState = QAudio::StoppedState;
            emit stateChanged(deviceState);
            return false;
        }
    }
    result = waveInStart(hWaveIn);
    if(result) {
        qWarning("QAudioInput: failed to start audio input");
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        return false;
    }
    timeStampOpened.restart();
    elapsedTimeOffset = 0;
    totalTimeValue = 0;
    errorState  = QAudio::NoError;
    return true;
}
Esempio n. 5
0
// global sender initialize (not thread specific)
iterator_t* send_init(void)
{

	// generate a new primitive root and starting position
	iterator_t *it;
	it = iterator_init(zconf.senders, zconf.shard_num, zconf.total_shards);

	// process the dotted-notation addresses passed to ZMAP and determine
	// the source addresses from which we'll send packets;
	srcip_first = inet_addr(zconf.source_ip_first);
	if (srcip_first == INADDR_NONE) {
		log_fatal("send", "invalid begin source ip address: `%s'",
				zconf.source_ip_first);
	}
	srcip_last = inet_addr(zconf.source_ip_last);
	if (srcip_last == INADDR_NONE) {
		log_fatal("send", "invalid end source ip address: `%s'",
				zconf.source_ip_last);
	}
	log_debug("send", "srcip_first: %u", srcip_first);
	log_debug("send", "srcip_last: %u", srcip_last);
	if (srcip_first == srcip_last) {
		srcip_offset = 0;
		num_src_addrs = 1;
	} else {
		uint32_t ip_first = ntohl(srcip_first);
		uint32_t ip_last = ntohl(srcip_last);
		assert(ip_first && ip_last);
		assert(ip_last > ip_first);
		uint32_t offset = (uint32_t) (aesrand_getword(zconf.aes) & 0xFFFFFFFF);
		srcip_offset = offset % (srcip_last - srcip_first);
		num_src_addrs = ip_last - ip_first + 1;
	}

	// process the source port range that ZMap is allowed to use
	num_src_ports = zconf.source_port_last - zconf.source_port_first + 1;
	log_debug("send", "will send from %i address%s on %u source ports",
		  num_src_addrs, ((num_src_addrs ==1 ) ? "":"es"),
		  num_src_ports);

	// global initialization for send module
	assert(zconf.probe_module);
	if (zconf.probe_module->global_initialize) {
		zconf.probe_module->global_initialize(&zconf);
	}

	// concert specified bandwidth to packet rate
	if (zconf.bandwidth > 0) {
		int pkt_len = zconf.probe_module->packet_length;
		pkt_len *= 8;
		pkt_len += 8*24;	// 7 byte MAC preamble, 1 byte Start frame,
		                        // 4 byte CRC, 12 byte inter-frame gap
		if (pkt_len < 84*8) {
			pkt_len = 84*8;
		}
		if (zconf.bandwidth / pkt_len > 0xFFFFFFFF) {
			zconf.rate = 0;
		} else {
			zconf.rate = zconf.bandwidth / pkt_len;
			if (zconf.rate == 0) {
				log_warn("send", "bandwidth %lu bit/s is slower than 1 pkt/s, "
								"setting rate to 1 pkt/s", zconf.bandwidth);
				zconf.rate = 1;
			}
		}
		log_debug("send", "using bandwidth %lu bits/s, rate set to %d pkt/s",
						zconf.bandwidth, zconf.rate);
	}

	// Get the source hardware address, and give it to the probe
	// module
	if (get_iface_hw_addr(zconf.iface, zconf.hw_mac)) {
		log_fatal("send", "could not retrieve hardware address for "
			  "interface: %s", zconf.iface);
		return NULL;
	}
	log_debug("send", "source MAC address %02x:%02x:%02x:%02x:%02x:%02x",
           zconf.hw_mac[0], zconf.hw_mac[1], zconf.hw_mac[2],
           zconf.hw_mac[3], zconf.hw_mac[4], zconf.hw_mac[5]);

	if (zconf.dryrun) {
		log_info("send", "dryrun mode -- won't actually send packets");
	}

	// initialize random validation key
	validate_init();

	zsend.start = now();
	return it;
}
Esempio n. 6
0
int parse_timestamp(const char *t, usec_t *usec) {
        static const struct {
                const char *name;
                const int nr;
        } day_nr[] = {
                { "Sunday",    0 },
                { "Sun",       0 },
                { "Monday",    1 },
                { "Mon",       1 },
                { "Tuesday",   2 },
                { "Tue",       2 },
                { "Wednesday", 3 },
                { "Wed",       3 },
                { "Thursday",  4 },
                { "Thu",       4 },
                { "Friday",    5 },
                { "Fri",       5 },
                { "Saturday",  6 },
                { "Sat",       6 },
        };

        const char *k;
        const char *utc;
        struct tm tm, copy;
        time_t x;
        usec_t x_usec, plus = 0, minus = 0, ret;
        int r, weekday = -1;
        unsigned i;

        /*
         * Allowed syntaxes:
         *
         *   2012-09-22 16:34:22
         *   2012-09-22 16:34     (seconds will be set to 0)
         *   2012-09-22           (time will be set to 00:00:00)
         *   16:34:22             (date will be set to today)
         *   16:34                (date will be set to today, seconds to 0)
         *   now
         *   yesterday            (time is set to 00:00:00)
         *   today                (time is set to 00:00:00)
         *   tomorrow             (time is set to 00:00:00)
         *   +5min
         *   -5days
         *   @2147483647          (seconds since epoch)
         *
         */

        assert(t);
        assert(usec);

        if (t[0] == '@')
                return parse_sec(t + 1, usec);

        ret = now(CLOCK_REALTIME);

        if (streq(t, "now"))
                goto finish;

        else if (t[0] == '+') {
                r = parse_sec(t+1, &plus);
                if (r < 0)
                        return r;

                goto finish;

        } else if (t[0] == '-') {
                r = parse_sec(t+1, &minus);
                if (r < 0)
                        return r;

                goto finish;

        } else if ((k = endswith(t, " ago"))) {
                t = strndupa(t, k - t);

                r = parse_sec(t, &minus);
                if (r < 0)
                        return r;

                goto finish;

        } else if ((k = endswith(t, " left"))) {
                t = strndupa(t, k - t);

                r = parse_sec(t, &plus);
                if (r < 0)
                        return r;

                goto finish;
        }

        utc = endswith_no_case(t, " UTC");
        if (utc)
                t = strndupa(t, utc - t);

        x = ret / USEC_PER_SEC;
        x_usec = 0;

        assert_se(localtime_or_gmtime_r(&x, &tm, utc));
        tm.tm_isdst = -1;

        if (streq(t, "today")) {
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
                goto from_tm;

        } else if (streq(t, "yesterday")) {
                tm.tm_mday--;
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
                goto from_tm;

        } else if (streq(t, "tomorrow")) {
                tm.tm_mday++;
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
                goto from_tm;
        }


        for (i = 0; i < ELEMENTSOF(day_nr); i++) {
                size_t skip;

                if (!startswith_no_case(t, day_nr[i].name))
                        continue;

                skip = strlen(day_nr[i].name);
                if (t[skip] != ' ')
                        continue;

                weekday = day_nr[i].nr;
                t += skip + 1;
                break;
        }

        copy = tm;
        k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
        if (k) {
                if (*k == '.')
                        goto parse_usec;
                else if (*k == 0)
                        goto from_tm;
        }

        tm = copy;
        k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
        if (k) {
                if (*k == '.')
                        goto parse_usec;
                else if (*k == 0)
                        goto from_tm;
        }

        tm = copy;
        k = strptime(t, "%y-%m-%d %H:%M", &tm);
        if (k && *k == 0) {
                tm.tm_sec = 0;
                goto from_tm;
        }

        tm = copy;
        k = strptime(t, "%Y-%m-%d %H:%M", &tm);
        if (k && *k == 0) {
                tm.tm_sec = 0;
                goto from_tm;
        }

        tm = copy;
        k = strptime(t, "%y-%m-%d", &tm);
        if (k && *k == 0) {
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
                goto from_tm;
        }

        tm = copy;
        k = strptime(t, "%Y-%m-%d", &tm);
        if (k && *k == 0) {
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
                goto from_tm;
        }

        tm = copy;
        k = strptime(t, "%H:%M:%S", &tm);
        if (k) {
                if (*k == '.')
                        goto parse_usec;
                else if (*k == 0)
                        goto from_tm;
        }

        tm = copy;
        k = strptime(t, "%H:%M", &tm);
        if (k && *k == 0) {
                tm.tm_sec = 0;
                goto from_tm;
        }

        return -EINVAL;

parse_usec:
        {
                unsigned add;

                k++;
                r = parse_fractional_part_u(&k, 6, &add);
                if (r < 0)
                        return -EINVAL;

                if (*k)
                        return -EINVAL;

                x_usec = add;

        }

from_tm:
        x = mktime_or_timegm(&tm, utc);
        if (x == (time_t) -1)
                return -EINVAL;

        if (weekday >= 0 && tm.tm_wday != weekday)
                return -EINVAL;

        ret = (usec_t) x * USEC_PER_SEC + x_usec;

finish:
        ret += plus;
        if (ret > minus)
                ret -= minus;
        else
                ret = 0;

        *usec = ret;

        return 0;
}
Esempio n. 7
0
int sd_ipv4ll_start (sd_ipv4ll *ll) {
        int r;

        assert_return(ll, -EINVAL);
        assert_return(ll->event, -EINVAL);
        assert_return(ll->index > 0, -EINVAL);
        assert_return(IN_SET(ll->state, IPV4LL_STATE_INIT,
                             IPV4LL_STATE_STOPPED), -EBUSY);

        ll->state = IPV4LL_STATE_INIT;

        r = arp_network_bind_raw_socket(ll->index, &ll->link);

        if (r < 0)
                goto out;

        ll->fd = r;
        ll->conflict = 0;
        ll->defend_window = 0;
        ll->claimed_address = 0;

        if (!ll->random_data) {
                uint8_t seed[8];

                /* Fallback to mac */
                siphash24(seed, &ll->mac_addr.ether_addr_octet,
                          ETH_ALEN, HASH_KEY.bytes);

                r = sd_ipv4ll_set_address_seed(ll, seed);
                if (r < 0)
                        goto out;
        }

        if (ll->address == 0) {
                r = ipv4ll_pick_address(ll, &ll->address);
                if (r < 0)
                        goto out;
        }

        ipv4ll_set_state (ll, IPV4LL_STATE_INIT, 1);

        r = sd_event_add_io(ll->event, &ll->receive_message, ll->fd,
                            EPOLLIN, ipv4ll_receive_message, ll);
        if (r < 0)
                goto out;

        r = sd_event_source_set_priority(ll->receive_message, ll->event_priority);
        if (r < 0)
                goto out;

        r = sd_event_source_set_name(ll->receive_message, "ipv4ll-receive-message");
        if (r < 0)
                goto out;

        r = sd_event_add_time(ll->event,
                              &ll->timer,
                              clock_boottime_or_monotonic(),
                              now(clock_boottime_or_monotonic()), 0,
                              ipv4ll_timer, ll);

        if (r < 0)
                goto out;

        r = sd_event_source_set_priority(ll->timer, ll->event_priority);
        if (r < 0)
                goto out;

        r = sd_event_source_set_name(ll->timer, "ipv4ll-timer");
out:
        if (r < 0)
                ipv4ll_stop(ll, IPV4LL_EVENT_STOP);

        return 0;
}
Esempio n. 8
0
int main (int argc, char *argv[])
{

  MPI_Init (&argc, &argv);
  
  int nProc, iProc;

  MPI_Comm_rank (MPI_COMM_WORLD, &iProc);
  MPI_Comm_size (MPI_COMM_WORLD, &nProc);

  // number of threads
  const int NTHREADS = 1;

  // number of buffers
  const int NWAY     = 2;

  // left neighbour
  const int left  = LEFT(iProc, nProc);

  // right neighbour
  const int right = RIGHT(iProc, nProc);

  // allocate array of for local vector, left halo and right halo
  double* array = malloc (NWAY * (NTHREADS+2) * 2 * VLEN * sizeof (double));
  ASSERT (array != 0);

  // initial buffer id
  int buffer_id = 0;

  // initialize data
  data_init (NTHREADS, iProc, buffer_id, array);

  MPI_Barrier (MPI_COMM_WORLD);

  double time = -now();

  for (int k = 0; k < NITER; ++k)
  {
    for (int i = 0; i < nProc; ++i)
    {
      MPI_Request send_req[2];
      MPI_Request recv_req[2];
      int slice_id    = 1;
      int left_halo   = 0;
      int right_halo  = 2;
	
      // post recv
      MPI_Irecv ( &array_ELEM_right (buffer_id, left_halo, 0), VLEN, MPI_DOUBLE
		  , left, i, MPI_COMM_WORLD, &recv_req[0]);

      MPI_Irecv ( &array_ELEM_left (buffer_id, right_halo, 0), VLEN, MPI_DOUBLE
		  , right, i, MPI_COMM_WORLD, &recv_req[1]);

      // issue send
      MPI_Isend ( &array_ELEM_right (buffer_id, right_halo - 1, 0), VLEN, MPI_DOUBLE
		  , right, i, MPI_COMM_WORLD, &send_req[0]);

      MPI_Isend ( &array_ELEM_left (buffer_id, left_halo + 1, 0), VLEN, MPI_DOUBLE
		  , left, i, MPI_COMM_WORLD, &send_req[1]);

      // wait for recv
      MPI_Waitall (2, recv_req, MPI_STATUSES_IGNORE);

      // compute data, read from id "buffer_id", write to id "1 - buffer_id"
      data_compute (NTHREADS, array, 1 - buffer_id, buffer_id, slice_id);

      // wait for send
      MPI_Waitall (2, send_req, MPI_STATUSES_IGNORE);

      // alternate the buffer
      buffer_id = 1 - buffer_id;

    }
  }

  time += now();

  data_verify (NTHREADS, iProc, (NITER * nProc) % NWAY, array);

  printf ("# mpi %s nProc %d vlen %i niter %d nthreads %i nway %i time %g\n"
         , argv[0], nProc, VLEN, NITER, NTHREADS, NWAY, time
         );
  
  MPI_Finalize();

  free (array);

  return EXIT_SUCCESS;
}
Esempio n. 9
0
void record_frame(struct fps_queue* queue) {
  queue->frames[queue->pos++] = now();
  queue->pos %= queue->samples;
}
Esempio n. 10
0
long Clock::start()
{
    _active = true;
    return _start = now();
}
Esempio n. 11
0
int mount_cgroup_controllers(char ***join_controllers) {
        _cleanup_set_free_free_ Set *controllers = NULL;
        int r;

        if (!cg_is_legacy_wanted())
                return 0;

        /* Mount all available cgroup controllers that are built into the kernel. */

        controllers = set_new(&string_hash_ops);
        if (!controllers)
                return log_oom();

        r = cg_kernel_controllers(controllers);
        if (r < 0)
                return log_error_errno(r, "Failed to enumerate cgroup controllers: %m");

        for (;;) {
                _cleanup_free_ char *options = NULL, *controller = NULL, *where = NULL;
                MountPoint p = {
                        .what = "cgroup",
                        .type = "cgroup",
                        .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
                        .mode = MNT_IN_CONTAINER,
                };
                char ***k = NULL;

                controller = set_steal_first(controllers);
                if (!controller)
                        break;

                if (join_controllers)
                        for (k = join_controllers; *k; k++)
                                if (strv_find(*k, controller))
                                        break;

                if (k && *k) {
                        char **i, **j;

                        for (i = *k, j = *k; *i; i++) {

                                if (!streq(*i, controller)) {
                                        _cleanup_free_ char *t;

                                        t = set_remove(controllers, *i);
                                        if (!t) {
                                                free(*i);
                                                continue;
                                        }
                                }

                                *(j++) = *i;
                        }

                        *j = NULL;

                        options = strv_join(*k, ",");
                        if (!options)
                                return log_oom();
                } else {
                        options = controller;
                        controller = NULL;
                }

                where = strappend("/sys/fs/cgroup/", options);
                if (!where)
                        return log_oom();

                p.where = where;
                p.options = options;

                r = mount_one(&p, true);
                if (r < 0)
                        return r;

                if (r > 0 && k && *k) {
                        char **i;

                        for (i = *k; *i; i++) {
                                _cleanup_free_ char *t = NULL;

                                t = strappend("/sys/fs/cgroup/", *i);
                                if (!t)
                                        return log_oom();

                                r = symlink(options, t);
                                if (r >= 0) {
#ifdef SMACK_RUN_LABEL
                                        _cleanup_free_ char *src;
                                        src = strappend("/sys/fs/cgroup/", options);
                                        if (!src)
                                                return log_oom();
                                        r = mac_smack_copy(t, src);
                                        if (r < 0 && r != -EOPNOTSUPP)
                                                return log_error_errno(r, "Failed to copy smack label from %s to %s: %m", src, t);
#endif
                                } else if (errno != EEXIST)
                                        return log_error_errno(errno, "Failed to create symlink %s: %m", t);
                        }
                }
        }

        /* Now that we mounted everything, let's make the tmpfs the
         * cgroup file systems are mounted into read-only. */
        (void) mount("tmpfs", "/sys/fs/cgroup", "tmpfs", MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755");

        return 0;
}

#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
static int nftw_cb(
                const char *fpath,
                const struct stat *sb,
                int tflag,
                struct FTW *ftwbuf) {

        /* No need to label /dev twice in a row... */
        if (_unlikely_(ftwbuf->level == 0))
                return FTW_CONTINUE;

        label_fix(fpath, false, false);

        /* /run/initramfs is static data and big, no need to
         * dynamically relabel its contents at boot... */
        if (_unlikely_(ftwbuf->level == 1 &&
                      tflag == FTW_D &&
                      streq(fpath, "/run/initramfs")))
                return FTW_SKIP_SUBTREE;

        return FTW_CONTINUE;
};
#endif

int mount_setup(bool loaded_policy) {
        int r = 0;

        r = mount_points_setup(ELEMENTSOF(mount_table), loaded_policy);

        if (r < 0)
                return r;

#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
        /* Nodes in devtmpfs and /run need to be manually updated for
         * the appropriate labels, after mounting. The other virtual
         * API file systems like /sys and /proc do not need that, they
         * use the same label for all their files. */
        if (loaded_policy) {
                usec_t before_relabel, after_relabel;
                char timespan[FORMAT_TIMESPAN_MAX];

                before_relabel = now(CLOCK_MONOTONIC);

                nftw("/dev", nftw_cb, 64, FTW_MOUNT|FTW_PHYS|FTW_ACTIONRETVAL);
                nftw("/dev/shm", nftw_cb, 64, FTW_MOUNT|FTW_PHYS|FTW_ACTIONRETVAL);
                nftw("/run", nftw_cb, 64, FTW_MOUNT|FTW_PHYS|FTW_ACTIONRETVAL);

                after_relabel = now(CLOCK_MONOTONIC);

                log_info("Relabelled /dev and /run in %s.",
                         format_timespan(timespan, sizeof(timespan), after_relabel - before_relabel, 0));
        }
#endif

        /* Create a few default symlinks, which are normally created
         * by udevd, but some scripts might need them before we start
         * udevd. */
        dev_setup(NULL, UID_INVALID, GID_INVALID);

        /* Mark the root directory as shared in regards to mount
         * propagation. The kernel defaults to "private", but we think
         * it makes more sense to have a default of "shared" so that
         * nspawn and the container tools work out of the box. If
         * specific setups need other settings they can reset the
         * propagation mode to private if needed. */
        if (detect_container() <= 0)
                if (mount(NULL, "/", NULL, MS_REC|MS_SHARED, NULL) < 0)
                        log_warning_errno(errno, "Failed to set up the root directory for shared mount propagation: %m");

        /* Create a few directories we always want around, Note that
         * sd_booted() checks for /run/systemd/system, so this mkdir
         * really needs to stay for good, otherwise software that
         * copied sd-daemon.c into their sources will misdetect
         * systemd. */
        (void) mkdir_label("/run/systemd", 0755);
        (void) mkdir_label("/run/systemd/system", 0755);
        (void) mkdir_label("/run/systemd/inaccessible", 0000);
        /* Set up inaccessible items */
        (void) mknod("/run/systemd/inaccessible/reg", S_IFREG | 0000, 0);
        (void) mkdir_label("/run/systemd/inaccessible/dir", 0000);
        (void) mknod("/run/systemd/inaccessible/chr", S_IFCHR | 0000, makedev(0, 0));
        (void) mknod("/run/systemd/inaccessible/blk", S_IFBLK | 0000, makedev(0, 0));
        (void) mkfifo("/run/systemd/inaccessible/fifo", 0000);
        (void) mknod("/run/systemd/inaccessible/sock", S_IFSOCK | 0000, 0);

        return 0;
}
Esempio n. 12
0
bool do_sooner(QDateTime const& date1,Priority priority1, std::string const& name1,bool dl1, double weight1,
              QDateTime const& date2,Priority priority2, std::string const& name2,bool dl2, double weight2,
               double comparisonFactor) {
    //std::cout << "testing " << date1.toString().toStdString();
    //std::cout << " " << priority1 << " " << name1 << " " << dl1 << " " << weight1 << std::endl;
    //std::cout << "against " << date2.toString().toStdString() << " " << priority2 << " " << name2 << " " << dl2 << " " << weight2 << std::endl;
    QDateTime now(QDateTime::currentDateTime());
    int to1(now.secsTo(date1));
    int to2(now.secsTo(date2));
    bool dueToday1(to1>0 && to1<43200);
    bool dueToday2(to2>0 && to2<43200);
    if (dl1 && dueToday1 && !dueToday2) {
        //std::cout << 1 << std::endl;
        return true;
    }
    if (dl2 && dueToday2 && !dueToday1  ) {
        //std::cout << 0 << std::endl;
        return false;
    }
    if (priority1==priority2) {
        if (date1.date()==date2.date()) {
            if (weight1!=weight2) {
                return weight1<weight2;
            }
            if (dl1==dl2) {
                //std::cout << (name1<name2) << std::endl;
                return compare(name1,name2);
            }
            else if (dl1) {
                //std::cout << 1 << std::endl;
                return true;
            }
            else {
                //std::cout << 0 << std::endl;
                return false;
            }
        }
        else {
            //std::cout << "date compare " << (date1<date2) << std::endl;
            return to1*weight1<to2*weight2;
        }
    }
    if (priority1==LOW) {
        //std::cout << 0 << std::endl;
        return false;
    }
    if (priority2==LOW) {
        //std::cout << 1 << std::endl;
        return true;
    }
    //medium/high
    to1*=weight1;
    to2*=weight2;
    bool handInFirst(to1<to2);
    if (priority1==HIGH && (handInFirst || to1==to2)) {
        //std::cout << 1 << std::endl;
        return true;
    }
    if (priority2==HIGH && (!handInFirst || to1==to2)) {
        //std::cout << 0 << std::endl;
        return false;
    }
    if (handInFirst) {
        //std::cout << (to1*comparisonFactor<=to2) << std::endl;
        return to1*comparisonFactor<=to2;
    }
    else {
        //std::cout << (to2*comparisonFactor>to1) << std::endl;
        return to2*comparisonFactor>to1;
    }
}
  lwr_impedance_controller::CartImpTrajectoryPoint sampleInterpolation() {
    lwr_impedance_controller::CartImpTrajectoryPoint next_point;

    double timeFromStart =
        (double) (now() - trajectory_.header.stamp).toSec();
    double segStartTime = last_point_.time_from_start.toSec();
    double segEndTime =
        trajectory_.trajectory[trajectory_index_].time_from_start.toSec();

    next_point = setpoint_;

    // interpolate position
    // x
    next_point.pose.position.x = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.pose.position.x,
        trajectory_.trajectory[trajectory_index_].pose.position.x);
    // y
    next_point.pose.position.y = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.pose.position.y,
        trajectory_.trajectory[trajectory_index_].pose.position.y);
    // z
    next_point.pose.position.z = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.pose.position.z,
        trajectory_.trajectory[trajectory_index_].pose.position.z);

    // interpolate orientation

    Eigen::Quaternion<double> start = Eigen::Quaternion<double>(last_point_.pose.orientation.w,
        last_point_.pose.orientation.x, last_point_.pose.orientation.y,
        last_point_.pose.orientation.z);
    Eigen::Quaternion<double> end = Eigen::Quaternion<double>(
        trajectory_.trajectory[trajectory_index_].pose.orientation.w,
        trajectory_.trajectory[trajectory_index_].pose.orientation.x,
        trajectory_.trajectory[trajectory_index_].pose.orientation.y,
        trajectory_.trajectory[trajectory_index_].pose.orientation.z);

    double t = linearlyInterpolate(timeFromStart, segStartTime, segEndTime, 0,
        1);

    Eigen::Quaternion<double> rot = start.slerp(t, end);

    next_point.pose.orientation.x = rot.x();
    next_point.pose.orientation.y = rot.y();
    next_point.pose.orientation.z = rot.z();
    next_point.pose.orientation.w = rot.w();


    /*
     // x
     next_point.pose.orientation.x = linearlyInterpolate(timeFromStart,
     segStartTime, segEndTime, last_point_.pose.orientation.x,
     trajectory_.trajectory[trajectory_index_].pose.orientation.x);
     // y
     next_point.pose.orientation.y = linearlyInterpolate(timeFromStart,
     segStartTime, segEndTime, last_point_.pose.orientation.y,
     trajectory_.trajectory[trajectory_index_].pose.orientation.y);
     // z
     next_point.pose.orientation.z = linearlyInterpolate(timeFromStart,
     segStartTime, segEndTime, last_point_.pose.orientation.z,
     trajectory_.trajectory[trajectory_index_].pose.orientation.z);
     // w
     next_point.pose.orientation.w = linearlyInterpolate(timeFromStart,
     segStartTime, segEndTime, last_point_.pose.orientation.w,
     trajectory_.trajectory[trajectory_index_].pose.orientation.w);
     */
    //interpolate stiffness
    // x
    next_point.impedance.stiffness.force.x = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.impedance.stiffness.force.x,
        trajectory_.trajectory[trajectory_index_].impedance.stiffness.force.x);

    next_point.impedance.stiffness.force.y = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.impedance.stiffness.force.y,
        trajectory_.trajectory[trajectory_index_].impedance.stiffness.force.y);

    next_point.impedance.stiffness.force.z = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.impedance.stiffness.force.z,
        trajectory_.trajectory[trajectory_index_].impedance.stiffness.force.z);

    next_point.impedance.stiffness.torque.x = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.impedance.stiffness.torque.x,
        trajectory_.trajectory[trajectory_index_].impedance.stiffness.torque.x);

    next_point.impedance.stiffness.torque.y = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.impedance.stiffness.torque.y,
        trajectory_.trajectory[trajectory_index_].impedance.stiffness.torque.y);

    next_point.impedance.stiffness.torque.z = linearlyInterpolate(timeFromStart,
        segStartTime, segEndTime, last_point_.impedance.stiffness.torque.z,
        trajectory_.trajectory[trajectory_index_].impedance.stiffness.torque.z);

    next_point.impedance.damping =
        trajectory_.trajectory[trajectory_index_].impedance.damping;
    next_point.wrench = trajectory_.trajectory[trajectory_index_].wrench;

    return next_point;
  }
Esempio n. 14
0
void
main_init(int argc, char* argv[])
{
	char**		ptr; 
	MyString		job_queue_name;
 
	int argc_count = 1;
	for(ptr = argv + 1, argc_count = 1; argc_count<argc && *ptr; ptr++,argc_count++)
	{
		if(ptr[0][0] != '-')
		{
			usage(argv[0]);
		}
		switch(ptr[0][1])
		{
		  case 'n':
			Name = build_valid_daemon_name( *(++ptr) );
			break;
		  default:
			usage(argv[0]);
		}
	}

		// Tell Attrlist to publish the server time
	AttrList_setPublishServerTime( true );

		// Initialize DaemonCore's use of ProcFamily. We do this so that we
		// launch a ProcD if necessary so that any Starters that we launch
		// for Local Universe jobs can share a single ProcD, instead of
		// each creating their own
	daemonCore->Proc_Family_Init();

#if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT)
#if defined(HAVE_DLOPEN)
		// Intialization of the plugin manager, i.e. loading all
		// plugins, should be performed before the job queue log is
		// read so plugins have a chance to learn about all jobs
		// already in the queue
	ClassAdLogPluginManager::Load();

		// Load all ScheddPlugins. In reality this doesn't do much
		// since initializing any plugin manager loads plugins for all
		// plugin manager.
	ScheddPluginManager::Load();

		// Tell all ScheddPlugins to initialze themselves
	ScheddPluginManager::EarlyInitialize();

		// Tell all plugins to initialize themselves
	ClassAdLogPluginManager::EarlyInitialize();
#endif
#endif
	
		// Initialize all the modules
	scheduler.Init();
	scheduler.Register();

		// Initialize the job queue
	char *job_queue_param_name = param("JOB_QUEUE_LOG");

	if (job_queue_param_name == NULL) {
		// the default place for the job_queue.log is in spool
		job_queue_name.formatstr( "%s/job_queue.log", Spool);
	} else {
		job_queue_name = job_queue_param_name; // convert char * to MyString
		free(job_queue_param_name);
	}

		// Make a backup of the job queue?
	if ( param_boolean_crufty("SCHEDD_BACKUP_SPOOL", false) ) {
			MyString hostname;
			UtcTime now(true);
			hostname = get_local_hostname();
			MyString		job_queue_backup;
			job_queue_backup.formatstr( "%s/job_queue.bak.%s.%ld",
									  Spool, hostname.Value(), now.seconds() );
			if ( copy_file( job_queue_name.Value(), job_queue_backup.Value() ) ) {
				dprintf( D_ALWAYS, "Failed to backup spool to '%s'\n",
						 job_queue_backup.Value() );
			} else {
				dprintf( D_FULLDEBUG, "Spool backed up to '%s'\n",
						 job_queue_backup.Value() );
			}
	}

	int max_historical_logs = param_integer( "MAX_JOB_QUEUE_LOG_ROTATIONS", DEFAULT_MAX_JOB_QUEUE_LOG_ROTATIONS );

	InitJobQueue(job_queue_name.Value(),max_historical_logs);
	mark_jobs_idle();

		// The below must happen _after_ InitJobQueue is called.
	if ( scheduler.autocluster.config() ) {
		// clear out auto cluster id attributes
		WalkJobQueue( (int(*)(ClassAd *))clear_autocluster_id );
	}
	
		//
		// Update the SchedDInterval attributes in jobs if they
		// have it defined. This will be for JobDeferral and
		// CronTab jobs
		//
	WalkJobQueue( (int(*)(ClassAd *))::updateSchedDInterval );

		// Initialize the dedicated scheduler stuff
	dedicated_scheduler.initialize();

		// Do a timeout now at startup to get the ball rolling...
	scheduler.timeout();

#if defined(WANT_CONTRIB) && defined(WITH_MANAGEMENT)
#if defined(HAVE_DLOPEN)
		// Tell all ScheddPlugins to initialze themselves
	ScheddPluginManager::Initialize();

		// Tell all plugins to initialize themselves
	ClassAdLogPluginManager::Initialize();
#endif
#endif
} 
Esempio n. 15
0
int
main(int argc, char **argv)
{
	int		c;
	uint_t		cursize;
	DIR		*dirp;
	int		i;
	int		j;
	char		name[NAME_MAX + 1];
	struct stat	stb;
	double		stime;

	while ((c = getopt(argc, argv, "a:c:d:f:l:m:n:s:")) != -1) {
		switch (c) {
		case 'a':
			addval = (uint_t)atoi(optarg);
			break;
		case 'c':
			nchars = (uint_t)atoi(optarg);
			break;
		case 'd':
			directory = optarg;
			break;
		case 'f':
			firstsize = (uint_t)atoi(optarg);
			break;
		case 'l':
			lastsize = (uint_t)atoi(optarg);
			break;
		case 'm':
			mulval = atof(optarg);
			break;
		case 'n':
			ndirs = (uint_t)atoi(optarg);
			break;
		case 's':
			stats = (uint_t)atoi(optarg);
			break;
		case '?':
		default:
			usage();
			exit(1);
		}
	}
	if (!addval && !mulval)
		mulval = 2.0;
	else if ((addval && mulval) || mulval < 0.0) {
		usage();
		exit(1);
	}
	if (stats == 0)
		stats = 1;
	if (!directory)
		directory = ".";
	else {
		if (mkdir(directory, 0777) < 0 && errno != EEXIST) {
			perror(directory);
			exit(1);
		}
		if (chdir(directory) < 0) {
			perror(directory);
			exit(1);
		}
	}
	if (firstsize == 0)
		firstsize = DFL_FIRST_SIZE;
	else if (firstsize > MAX_DIR_SIZE)
		firstsize = MAX_DIR_SIZE;
	if (lastsize == 0)
		lastsize = DFL_LAST_SIZE;
	else if (lastsize > MAX_DIR_SIZE)
		lastsize = MAX_DIR_SIZE;
	if (lastsize < firstsize)
		lastsize = firstsize;
	minchars = hexchars(lastsize - 1);
	if (nchars < minchars)
		nchars = minchars;
	else if (nchars >= NAME_MAX + 1)
		nchars = NAME_MAX;
	if (ndirs > MAX_DIR_COUNT)
		ndirs = MAX_DIR_COUNT;
	if (ndirs < MIN_DIR_COUNT)
		ndirs = MIN_DIR_COUNT;
	dirchars = hexchars(ndirs);
	pfxchars = nchars - minchars;
	if (pfxchars)
		memset(&name[dirchars + 1], 'a', pfxchars);
	for (j = 0; j < ndirs; j++) {
		filename(0, j, name);
		name[dirchars] = '\0';
		mkdir(name, 0777);
	}
	for (cursize = firstsize;
	     cursize <= lastsize;
	     cursize = nextsize(cursize)) {
		stime = now();
		for (i = 0; i < cursize; i++) {
			for (j = 0; j < ndirs; j++) {
				filename((i + j) % cursize, j, name);
				close(creat(name, 0666));
			}
		}
		for (i = 0; i < cursize * stats; i++) {
			for (j = 0; j < ndirs; j++) {
				filename((i + j) % cursize, j, name);
				stat(name, &stb);
			}
		}
		for (j = 0; j < ndirs; j++) {
			filename(0, j, name);
			name[dirchars] = '\0';
			dirp = opendir(name);
			while (readdir(dirp))
				continue;
			closedir(dirp);
		}
		for (i = 0; i < cursize; i++) {
			for (j = 0; j < ndirs; j++) {
				filename((i + j) % cursize, j, name);
				unlink(name);
			}
		}
		printf("%d %.3f\n", cursize,
			(now() - stime) * 1.0e3 / (cursize * ndirs));
	}
	for (j = 0; j < ndirs; j++) {
		filename(0, j, name);
		name[dirchars] = '\0';
		rmdir(name);
	}
	return 0;
}
Esempio n. 16
0
int main(int argc, char** argv) {
  width = 12, depth = 8, height = 60;
  xd = (width - 1) / 2.4;
  yd = (depth - 1) / 1.6;
  zd = (height - 1) / 2.0;
  xl = (width - 1) / xd;
  yl = (depth - 1) / yd;
  zl = (height - 1) / zd;
  total_leds = width * depth * height;
  channel = 0;

  fps = 60;
  period_x = xl / (2 * M_PI);
  speed_x = 1.0 / fps;
  period_y = yl / (2 * M_PI);
  speed_y = 0.9 / fps;
  period_z = zl / (2 * M_PI);
  speed_z = 0.8 / fps;

  sphere_r = .3;
  spheres = sqrt(pow(xl/2, 2) + pow(yl/2, 2) + pow(zl/2, 2)) / sphere_r;
  spheres += 2;
  frames_per_layer = fps / 2;
  pixel l_sphere_colors[spheres];
  sphere_colors = l_sphere_colors;
  int i;
  for (i = 0; i < spheres; i++) {
    sphere_colors[i] = randcolor();
  }

  pixel pixels[total_leds + 1];
  opc_sink s;

  if (argc < 2) {
    fprintf(stderr, "Usage: %s <server>[:<port>]\n", argv[0]);
    return 1;
  }

  s = opc_new_sink(argv[1]);

  int64_t frame_index = 0;
  int64_t start = now();
  struct fps_queue fpsq;
  int64_t frames[total_leds];
  fpsq.samples = fps;
  fpsq.pos = 0;
  fpsq.frames = frames;
  while (1) {
    sleep_until(start + 1000000 * frame_index / fps);
    render_frame(pixels, frame_index);
    if (!opc_put_pixels(s, channel, total_leds, pixels)) {
      break;
    }
    record_frame(&fpsq);
    if (fpsq.pos == 0) {
      double cur_fps = (fpsq.samples - 1) / (get_elapsed(&fpsq) / 1000000.0);
      printf("fps: %.2f  (%.2f Mbps)\n",
	     cur_fps, total_leds * 24 * cur_fps / 1000000.0);
    }
    frame_index++;
  }
  printf("fps: %f\n", frame_index / 5.0);
}
Esempio n. 17
0
char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
        const char *s;
        usec_t n, d;

        if (t <= 0 || t == USEC_INFINITY)
                return NULL;

        n = now(CLOCK_REALTIME);
        if (n > t) {
                d = n - t;
                s = "ago";
        } else {
                d = t - n;
                s = "left";
        }

        if (d >= USEC_PER_YEAR)
                snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
                         d / USEC_PER_YEAR,
                         (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
        else if (d >= USEC_PER_MONTH)
                snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
                         d / USEC_PER_MONTH,
                         (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
        else if (d >= USEC_PER_WEEK)
                snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
                         d / USEC_PER_WEEK,
                         (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
        else if (d >= 2*USEC_PER_DAY)
                snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
        else if (d >= 25*USEC_PER_HOUR)
                snprintf(buf, l, "1 day " USEC_FMT "h %s",
                         (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
        else if (d >= 6*USEC_PER_HOUR)
                snprintf(buf, l, USEC_FMT "h %s",
                         d / USEC_PER_HOUR, s);
        else if (d >= USEC_PER_HOUR)
                snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
                         d / USEC_PER_HOUR,
                         (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
        else if (d >= 5*USEC_PER_MINUTE)
                snprintf(buf, l, USEC_FMT "min %s",
                         d / USEC_PER_MINUTE, s);
        else if (d >= USEC_PER_MINUTE)
                snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
                         d / USEC_PER_MINUTE,
                         (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
        else if (d >= USEC_PER_SEC)
                snprintf(buf, l, USEC_FMT "s %s",
                         d / USEC_PER_SEC, s);
        else if (d >= USEC_PER_MSEC)
                snprintf(buf, l, USEC_FMT "ms %s",
                         d / USEC_PER_MSEC, s);
        else if (d > 0)
                snprintf(buf, l, USEC_FMT"us %s",
                         d, s);
        else
                snprintf(buf, l, "now");

        buf[l-1] = 0;
        return buf;
}
Esempio n. 18
0
Date_t getWallClockTimeForOpLog(OperationContext* opCtx) {
    auto const clockSource = opCtx->getServiceContext()->getFastClockSource();
    return clockSource->now();
}
Esempio n. 19
0
File: fsck.c Progetto: dds/systemd
static int process_progress(int fd) {
        _cleanup_fclose_ FILE *console = NULL, *f = NULL;
        usec_t last = 0;
        bool locked = false;
        int clear = 0;

        f = fdopen(fd, "r");
        if (!f) {
                safe_close(fd);
                return -errno;
        }

        console = fopen("/dev/console", "we");
        if (!console)
                return -ENOMEM;

        while (!feof(f)) {
                int pass, m;
                unsigned long cur, max;
                _cleanup_free_ char *device = NULL;
                double p;
                usec_t t;

                if (fscanf(f, "%i %lu %lu %ms", &pass, &cur, &max, &device) != 4)
                        break;

                /* Only show one progress counter at max */
                if (!locked) {
                        if (flock(fileno(console), LOCK_EX|LOCK_NB) < 0)
                                continue;

                        locked = true;
                }

                /* Only update once every 50ms */
                t = now(CLOCK_MONOTONIC);
                if (last + 50 * USEC_PER_MSEC > t)
                        continue;

                last = t;

                p = percent(pass, cur, max);
                fprintf(console, "\r%s: fsck %3.1f%% complete...\r%n", device, p, &m);
                fflush(console);

                if (m > clear)
                        clear = m;
        }

        if (clear > 0) {
                unsigned j;

                fputc('\r', console);
                for (j = 0; j < (unsigned) clear; j++)
                        fputc(' ', console);
                fputc('\r', console);
                fflush(console);
        }

        return 0;
}
Esempio n. 20
0
void
ReliableSession::send_naks()
{
  // Could get data samples before syn control message.
  // No use nak'ing until syn control message is received and session is acked.
  if (!this->acked_) return;

  if (DCPS_debug_level > 0) {
    ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) ReliableSession::send_naks local %d ")
                          ACE_TEXT ("remote %d nak request size %d \n"),
      this->link_->local_peer(), this->remote_peer_, this->nak_requests_.size()));
  }

  if (!this->nak_sequence_.disjoint()) return;  // nothing to send

  ACE_Time_Value now(ACE_OS::gettimeofday());

  // Record high-water mark for this interval; this value will
  // be used to reset the low-water mark in the event the remote
  // peer becomes unresponsive:
  this->nak_requests_.insert(
    NakRequestMap::value_type(now, this->nak_sequence_.high()));

  typedef std::vector<std::pair<SequenceNumber, SequenceNumber> > RangeVector;
  RangeVector ignored;

  /// The range first - second will be skiped (no naks sent for it).
  SequenceNumber first;
  SequenceNumber second;

  NakRequestMap::reverse_iterator itr(this->nak_requests_.rbegin());

  if (this->nak_requests_.size() > 1) {
    // The sequences between rbegin - 1 and rbegin will not be ignored for naking.
    ++itr;

    size_t nak_delay_intervals = this->link()->config()->nak_delay_intervals_;
    size_t nak_max = this->link()->config()->nak_max_;
    size_t sz = this->nak_requests_.size ();

    // Image i is the index of element in nak_requests_ in reverse order.
    // index 0 sequence is most recent high water mark.
    // e.g index , 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
    //  0 (rbegin) is always skipped because missing sample between 1 and 0 interval
    //  should always be naked.,
    //  if nak_delay_intervals=4, nak_max=3, any sequence between 5 - 1, 10 - 6, 15 - 11
    //  are skipped for naking due to nak_delay_intervals and 20 - 16 are skipped for
    //  naking due to nak_max.
    for (size_t i = 1; i < sz; ++i) {
      if ((i * 1.0) / (nak_delay_intervals + 1) > nak_max) {
        if (first != SequenceNumber()) {
          first = this->nak_requests_.begin ()->second;
        }
        else {
          ignored.push_back (std::make_pair(this->nak_requests_.begin ()->second, itr->second));
        }
        break;
      }

      if (i % (nak_delay_intervals + 1) == 1) {
        second = itr->second;
      }
      if (second != SequenceNumber()) {
        first = itr->second;
      }

      if (i % (nak_delay_intervals + 1) == 0) {
        first = itr->second;

        if (first != SequenceNumber() && second != SequenceNumber()) {
          ignored.push_back (std::make_pair(first, second));
          first = SequenceNumber();
          second == SequenceNumber();
        }
      }

      ++itr;
    }

    if (first != SequenceNumber() && second != SequenceNumber() && first != second) {
      ignored.push_back (std::make_pair(first, second));
    }
  }

  // Take a copy to facilitate temporary suppression:
  DisjointSequence missing(this->nak_sequence_);
  if (DCPS_debug_level > 0) {
    missing.dump ();
  }

  size_t sz = ignored.size ();
  for (size_t i = 0; i < sz; ++i) {

    if (ignored[i].second > missing.low ()) {
      SequenceNumber high = ignored[i].second;
      SequenceNumber low = ignored[i].first;
      if (low < missing.low ()) {
        low = missing.low ();
      }

      if (DCPS_debug_level > 0) {
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) ReliableSession::send_naks local %d ")
          ACE_TEXT ("remote %d ignore missing %d - %d \n"),
          this->link_->local_peer(), this->remote_peer_, low.getValue(), high.getValue()));
      }

      // Make contiguous between ignored sequences.
      for (SequenceNumber i = low + 1; i < high; ++i) {
        missing.update(i);
      }
    }
  }

  for (NakPeerSet::iterator it(this->nak_peers_.begin());
       it != this->nak_peers_.end(); ++it) {
    // Update sequence to temporarily suppress repair requests for
    // ranges already requested by other peers for this interval:
    missing.update(*it);
  }

  if (missing.disjoint()) {
    send_naks (missing);
  }

  // Clear peer repair requests:
  this->nak_peers_.clear();
}
Esempio n. 21
0
int main( int argc, char** argv ){

  // Set up real-time task
  mlockall(MCL_CURRENT | MCL_FUTURE);
  RT_TASK task;
  rt_task_shadow( &task, "GroupWAM", 99, 0 );

  // Initialize ROS
  ros::init(argc, argv, "wam_server", ros::init_options::NoSigintHandler);

  // Add custom signal handlers
  signal(SIGTERM, quitRequested);
  signal(SIGINT, quitRequested);
  signal(SIGHUP, quitRequested);

  // Construct the wam structure
  ros::NodeHandle wam_nh("wam");
  barrett_hw::WAM wam_hw( wam_nh );

  // Timer variables
  struct timespec ts = {0,0};

  if(clock_gettime(CLOCK_REALTIME, &ts) != 0) {
    ROS_FATAL("Failed to poll realtime clock!");
  }

  ros::Time 
    last(ts.tv_sec, ts.tv_nsec),
    now(ts.tv_sec, ts.tv_nsec);
  ros::Duration period(1.0);

  ros::AsyncSpinner spinner(1);
  spinner.start();

  realtime_tools::RealtimePublisher<std_msgs::Duration> publisher(wam_nh, "loop_rate", 2);

  bool wam_ok = false;
  while(!g_quit && !wam_ok) {
    if(!wam_hw.configure()) {
      ROS_ERROR("Could not configure WAM!");
    } else if(!wam_hw.start()) {
      ROS_ERROR("Could not start WAM!");
    } else {
      ros::Duration(1.0).sleep();

      if(!wam_hw.read(now, period)) {
        ROS_ERROR("Could not read from WAM!");
      } else {
        wam_ok = true;
      }
    }

    ros::Duration(1.0).sleep();
  }

  // Construct the controller manager
  ros::NodeHandle nh;
  controller_manager::ControllerManager manager(&wam_hw, nh);

  uint32_t count = 0;

  // Run as fast as possible
  while( !g_quit ) {
    // Get the time / period
    if (!clock_gettime(CLOCK_REALTIME, &ts)) {
      now.sec = ts.tv_sec;
      now.nsec = ts.tv_nsec;
      period = now - last;
      last = now;
    } else {
      ROS_FATAL("Failed to poll realtime clock!");
      break;
    } 

    // Read the state from the WAM
    if(!wam_hw.read(now, period)) {
      g_quit=true;
      break;
    }

    // Update the controllers
    manager.update(now, period);

    // Write the command to the WAM
    wam_hw.write(now, period);

    if(count++ > 1000) {
      if(publisher.trylock()) {
        count = 0;
        publisher.msg_.data = period;
        publisher.unlockAndPublish();
      }
    }
  }

  publisher.stop();

  std::cerr<<"Stpping spinner..."<<std::endl;
  spinner.stop();

  std::cerr<<"Stopping WAM..."<<std::endl;
  wam_hw.stop();

  std::cerr<<"Cleaning up WAM..."<<std::endl;
  wam_hw.cleanup();

  std::cerr<<"Poka!"<<std::endl;

  return 0;
}
Esempio n. 22
0
double sbGetCurrentTime() {
	return now();
}
Esempio n. 23
0
// one sender thread
int send_run(sock_t st, shard_t *s)
{
	log_trace("send", "send thread started");
	pthread_mutex_lock(&send_mutex);
	// Allocate a buffer to hold the outgoing packet
	char buf[MAX_PACKET_SIZE];
	memset(buf, 0, MAX_PACKET_SIZE);

	// OS specific per-thread init
	if (send_run_init(st)) {
		return -1;
	}

	// MAC address length in characters
	char mac_buf[(ETHER_ADDR_LEN * 2) + (ETHER_ADDR_LEN - 1) + 1];
	char *p = mac_buf;
	for(int i=0; i < ETHER_ADDR_LEN; i++) {
		if (i == ETHER_ADDR_LEN-1) {
			snprintf(p, 3, "%.2x", zconf.hw_mac[i]);
			p += 2;
		} else {
			snprintf(p, 4, "%.2x:", zconf.hw_mac[i]);
			p += 3;
		}
	}
	log_debug("send", "source MAC address %s",
			mac_buf);
	void *probe_data;
	if (zconf.probe_module->thread_initialize) {
		zconf.probe_module->thread_initialize(buf, zconf.hw_mac, zconf.gw_mac,
					      zconf.target_port, &probe_data);
	}
	pthread_mutex_unlock(&send_mutex);

	// adaptive timing to hit target rate
	uint32_t count = 0;
	uint32_t last_count = count;
	double last_time = now();
	uint32_t delay = 0;
	int interval = 0;
	uint32_t max_targets = s->state.max_targets;
	volatile int vi;
	if (zconf.rate > 0) {
		// estimate initial rate
		delay = 10000;
		for (vi = delay; vi--; )
			;
		delay *= 1 / (now() - last_time) / (zconf.rate / zconf.senders);
		interval = (zconf.rate / zconf.senders) / 20;
		last_time = now();
	}
	uint32_t curr = shard_get_cur_ip(s);
	int attempts = zconf.num_retries + 1;
	uint32_t idx = 0;
	while (1) {
		// adaptive timing delay
		if (delay > 0) {
			count++;
			for (vi = delay; vi--; )
				;
			if (!interval || (count % interval == 0)) {
				double t = now();
				delay *= (double)(count - last_count)
					/ (t - last_time) / (zconf.rate / zconf.senders);
				if (delay < 1)
					delay = 1;
				last_count = count;
				last_time = t;
			}
		}
		if (zrecv.complete) {
			s->cb(s->id, s->arg);
			break;
		}
		if (s->state.sent >= max_targets) {
			s->cb(s->id, s->arg);
			break;
		}
		if (zconf.max_runtime && zconf.max_runtime <= now() - zsend.start) {
			s->cb(s->id, s->arg);
			break;
		}
		if (curr == 0) {
			s->cb(s->id, s->arg);
			break;
		}
		s->state.sent++;
		for (int i=0; i < zconf.packet_streams; i++) {
			uint32_t src_ip = get_src_ip(curr, i);

		  	uint32_t validation[VALIDATE_BYTES/sizeof(uint32_t)];
			validate_gen(src_ip, curr, (uint8_t *)validation);
			zconf.probe_module->make_packet(buf, src_ip, curr, validation, i, probe_data);

			if (zconf.dryrun) {
				pthread_mutex_lock(&send_mutex);
				zconf.probe_module->print_packet(stdout, buf);
				pthread_mutex_unlock(&send_mutex);
			} else {
				int length = zconf.probe_module->packet_length;
				void *contents = buf + zconf.send_ip_pkts*sizeof(struct ether_header);
				for (int i = 0; i < attempts; ++i) {
					int rc = send_packet(st, contents, length, idx);
					if (rc < 0) {
						struct in_addr addr;
						addr.s_addr = curr;
						log_debug("send", "send_packet failed for %s. %s",
								  inet_ntoa(addr), strerror(errno));
						s->state.failures++;
					} else {
						break;
					}
				}
				idx++;
				idx &= 0xFF;
			}
		}

		curr = shard_get_next_ip(s);
	}
	if (zconf.dryrun) {
		pthread_mutex_lock(&send_mutex);
		fflush(stdout);
		pthread_mutex_unlock(&send_mutex);
	}
	log_debug("send", "thread %hu finished", s->id);
	return EXIT_SUCCESS;
}
Esempio n. 24
0
void save_assoc(Dbptr dbi, long is, long ie, long orid, char *vmodel,
	Tbl *residual,Hypocenter h, Dbptr dbo)
{
	/* These fields are copied from input assoc table */
	long arid;
	char sta[8];
	char phase[10];
	double belief;
	/* These fields are set here */
	double delta;
	double seaz;
	double esaz;
	double timeres;
	double azres;
	double slores;
	double lddate;
	double wgt;
	char timedef[2],slodef[2], azdef[2];
	
	/* intentionally ignored:  emares, commid */


	/* passed through arg list;  orid*/

	/* We use this to produce a keyed arr list of the residual 
	list passed into here as a Tbl */

	Arr *residual_array;
	long i;
	char key[40]; 

	double r, w, reswt,uxresid, uyresid;
	double stalat, stalon; 
	double ux, uy, azimuth;
	double u,phi;  /* polar form of measured slowness vector */
	double duphi;

	dbo = dblookup(dbo,0,"assoc",0,0);
	lddate = now();

	/* We build an associate array for the residual tbl keying
	each entry with a sta/phase/type key  where type is 
	set in ggnloc as time, ux, or uy.  This complication is
	needed to sort out array residuals. */
	residual_array = newarr(0);
	for(i=0;i<maxtbl(residual);++i)
	{
		char *s;
		char keysta[10], keyphase[10], keytype[5];
		s = (char *)gettbl(residual,i);
		sscanf(s,"%s %s %s",keysta,keyphase,keytype);
		/* handle S-P case by having the same residual mapped
		to each half of - phase pair */
		if(strchr(keyphase,'-'))
		{
			char *phase1,*phase2;
			/* algorithm to split phase names cloned from dbgenloc */
			phase1 = strdup(keyphase);
			phase2= strchr(phase1,'-');
			*phase2 = '\0';
			++phase2;
			sprintf(key,"%s %s %s",keysta,phase1,keytype);
			setarr(residual_array,key,s);
                        sprintf(key,"%s %s %s",keysta,phase2,keytype);
                        setarr(residual_array,key,s);
			free(phase1);
		}
		else
		{
			/* normal phases are one to one */
			sprintf(key,"%s %s %s",keysta,keyphase,keytype);
			setarr(residual_array,key,s);
		}
	}
		

	for(dbi.record=is;dbi.record < ie;++dbi.record)
	{
		char *time_residual_record;
		char *ux_residual_record,*uy_residual_record;
		if( dbgetv(dbi,0,
      	    		"assoc.arid",&arid,
          		"assoc.sta",sta,
          		"assoc.phase",phase,
          		"assoc.belief",&belief,
				NULL) == dbINVALID)
		{
		  elog_die(1,"save_assoc: dbgetv error reading assoc fields of input view at record %ld\n",
				dbi.record);
		}
		if( dbgetv(dbi,0,
			"site.lat",&stalat,
			"site.lon",&stalon,
				NULL) == dbINVALID)
		{
		  elog_die(1,"save_assoc: dbgetv error reading site fields of input view at record %ld\n",
				dbi.record);
		}
		/* Find the time residual record for this arrival */
		sprintf(key,"%s %s time",sta,phase);
		time_residual_record = (char *)getarr(residual_array,key);
		if(time_residual_record == NULL)
		{
			elog_complain(1,"save_assoc:  getarr mismatch for key %s\nCannot set residual\n",key);
			timeres = TIMENULL;
			wgt = 0.0;
			strcpy(timedef,"n");
		}
		else
		{
                        /* Changed by JN to avoid gcc warning */
			/* sscanf(time_residual_record,"%*s%*s%*s%*lg%lg%lg%lg", */
			sscanf(time_residual_record,"%*s%*s%*s%*g%lg%lg%lg",
				&r,&w,&reswt);
			timeres = r;
			wgt = w*reswt;
			strcpy(timedef,"d");
		}

		sprintf(key,"%s %s ux",sta,phase);		
		ux_residual_record = (char *)getarr(residual_array,key);
		sprintf(key,"%s %s uy",sta,phase);
		uy_residual_record = (char *)getarr(residual_array,key);
                /* Corrected by JN
		if( (ux_residual_record == NULL) 
			|| (ux_residual_record == NULL))
                */
		if( (ux_residual_record == NULL) 
			|| (uy_residual_record == NULL))
		{
			/* This trick is not documented.  By setting 
			the record filed to dbNULL, and then calling dbgetv
			each of the fields will be set to their NULL value */
			dbo.record = dbNULL;
			dbgetv(dbo,0,"azres",&azres,"slores",&slores,NULL );
			strcpy(azdef,"n");
			strcpy(slodef,"n");
		}
		else
		{
		/* This gets nasty because we have to convert to polar 
		coordinates from ux, uy components */
			sscanf(ux_residual_record,"%*s%*s%*s%*g%lg",&uxresid);

			sscanf(uy_residual_record,"%*s%*s%*s%*g%lg",&uyresid);
		/* We fetch the measured slowness vector to convert */
			if( dbgetv(dbi,0,
				"arrival.slow",&u,
				"arrival.azimuth",&phi,
					NULL) == dbINVALID)
			{
		  	  elog_die(1,"save_assoc: dbgetv error reading arrival fields of input view at record %ld\n",
				dbi.record);
			}
			/* css stores slowness in s/deg, but we use
			s/km internally here so we have to convert */

			slores = sqrt(uxresid*uxresid+uyresid*uyresid);
			slores *= KMPERDEG;

			/* this is the azimuth term */
			u /= KMPERDEG;
			duphi = ux*cos(rad(azimuth)) - uy*sin(rad(azimuth));
			duphi /= u;
			azres = deg(duphi);
			strcpy(azdef,"d");
			strcpy(slodef,"d");

		}
		dist(rad(h.lat),rad(h.lon),rad(stalat),rad(stalon),
				&delta,&esaz);
		dist(rad(stalat),rad(stalon),rad(h.lat),rad(h.lon),
				&delta,&seaz);
		delta = deg(delta);
		seaz = deg(seaz);
		esaz = deg(esaz);
			
		if(dbaddv(dbo,0,
                        "arid",arid,
                        "orid",orid,
                        "sta",sta,
                        "phase",phase,
                        "belief",belief,
                        "delta",delta,
                        "seaz",seaz,
                        "esaz",esaz,
                        "timeres",timeres,
                        "timedef",timedef,
                        "azres",azres,
                        "azdef",azdef,
                        "slores",slores,
                        "slodef",slodef,
                        "wgt",wgt,
                        "vmodel",vmodel,
                        "lddate",lddate,
			NULL ) == dbINVALID)
		{
			elog_die(1,"save_assoc: dbaddv error writing assoc record for arid %ld\n",
				arid);
		}
	}
	freearr(residual_array,0);
}
Esempio n. 25
0
int main(int argc, char **argv)
{
	struct args args = {
		/* Defaults. */
		.stack		= "ip",
		.add_rules	= 0,
		.ebtables	= "/sbin/ebtables",
		.sleep		= 10,
		.parents	= 0,
		.daemon		= 0,

		/* This parameter expects something like
		 * "experiment/stack/column/run".
		 */
		.file		= NULL,

		.count		= 0,
		.entries	= 0,
		.ifs		= NULL,
	};

	int i, sk, rcount;
	FILE *f;
	double start;
	struct ebt_counter *cnt;

	/* Read parameters. */
	argp_parse(&argp, argc, argv, 0, NULL, &args);

	/* Install ebtables(8) rules. */
	if (args.add_rules) {
		for (i = 0; i < args.count; i++)
			ebt_add_rule(args.ebtables, args.stack, args.ifs[i]);
	}

	/* Create parent paths of @args.file. */
	if (args.file && args.parents)
		assert(!close(mkdir_parents(args.file)));

	/* Test that only the expected ebtables(8) rules are in place.
	 * This is important to avoid silently wrong measurements.
	 */
	sk = ebt_socket();
	if (sk < 0)
		err(1, "Can't get a socket");
	rcount = ebt_rule_count(sk, args.stack);
	if (rcount != args.count)
		errx(1, "There is a mismatch between the number of ebtables(8) rules installed (= %i) and the number of monitored interfaces (= %i)",
		rcount, args.count);
	if (!rcount)
		errx(1, "There is no ebtables(8) rules to measure");

	/* Create sampling file. */
	if (args.file) {
		f = fopen(args.file, "w");
		if (!f)
			err(1, "Can't open file `%s'", args.file);
		ebt_add_header_to_file(sk, args.stack, f);
	} else {
		f = stdout;
	}

	/* Daemonize. */
	if (args.daemon && daemon(1, 1))
		err(1, "Can't daemonize");

	start = now();
	if (args.file) {
		ebt_write_sample_to_file(sk, args.stack, f);
		if (fflush(f))
			err(1, "Can't save content of file `%s'", args.file);
	} else {
		cnt = ebt_create_cnt(sk, args.stack);
		assert(cnt);
	}

	while (1) {
		double diff = now() - start;
		if (diff < args.sleep)
			nsleep(args.sleep - diff);
		else
			warnx("Option --sleep=%i is too little; not enough time to estimate rates. Consider increasing the period",
			args.sleep);

		start = now();
		if (args.file)
			ebt_write_sample_to_file(sk, args.stack, f);
		else
			ebt_write_rates_to_file(sk, args.stack, f, args.sleep,
				cnt);
		if (fflush(f))
			err(1, "Can't save content of file `%s'",
				args.file ? args.file : "STDOUT");
	}

	ebt_free_cnt(cnt);
	if (args.file)
		assert(!fclose(f));
	ebt_close(sk);
	end_args(&args);
	return 0;
}
Esempio n. 26
0
long save_origin(Dbptr dbi, long is, long ie, int depth_fixed,
	Hypocenter h, Dbptr dbo)
{
	long orid;

	/* These are parameters copied from input db -- names = css names */
	long evid;
	long jdate;
	long grn;
	long srn;
	char etype[8];
	double mb;
	long mbid;
	double ms;
	long msid;
	double ml;
	long mlid;
	/* These obtained from this solution */

	long nass;
	long ndef;
	char dtype[2];
	char algorithm[16]="genloc-nlls";
	char auth[20];
	double lddate;
	

	/* these are intentionally left null: ndp,depdp,commid*/


	/* set but obtained directly from hypo structure 
	lat, lon, depth, time */

	dbo = dblookup(dbo,0,"origin",0,0);
	
	/* Grab what we need from the input db for copying.  Note
	that because the joins used here, each of the input db
	records have the same origin entries.  Thus, we just fetch
	stuff from row is.  */
	dbi.record = is;
	if( dbgetv(dbi,0,
		"origin.evid", &evid,
		"origin.jdate", &jdate,
		"origin.grn", &grn,
		"origin.srn", &srn,
		"origin.etype", etype,
		"origin.mb", &mb,
		"origin.mbid", &mbid,
		"origin.ms", &ms,
		"origin.msid", &msid,
		"origin.ml", &ml,
		"origin.mlid", &mlid,
				NULL) == dbINVALID)
	{
		elog_die(1,"save_origin: dbgetv error reading origin fields of input view at record %ld\n",
				is);
	}
	nass = ie - is;
	/* ndef is potentially wrong by this calculation.  We set ndef 
	from the number of degrees of freedom in the solution + npar
	where npar is 3 when depth is fixed and 4 otherwise.  This does
	not match the real definition of ndef, especially when array 
	data are used because each arrival then then has 3 data points
	used to constrain the solution.  These is either an error in 
	my (glp) understanding of the css3.0 schema or a flaw in its 
	design.*/
	if(depth_fixed)
	{
		ndef = h.degrees_of_freedom + 3;
		strcpy(dtype,"r");
	}
	else
	{
		ndef = h.degrees_of_freedom + 4;
		strcpy(dtype,"f");
	}
	my_username(auth);
	lddate = now();
	orid = dbnextid(dbo,"orid");
	if(dbaddv(dbo,0,
                "lat",h.lat,
                "lon",h.lon,
                "depth",h.z,
                "time",h.time,
                "orid",orid,
                "evid",evid,
                "jdate",jdate,
                "nass",nass,
                "ndef",ndef,
                "grn",grn,
                "srn",srn,
                "etype",etype,
                "dtype",dtype,
                "mb",mb,
                "mbid",mbid,
                "ms",ms,
                "msid",msid,
                "ml",ml,
                "mlid",mlid,
                "algorithm",algorithm,
                "auth",auth,
                "lddate",lddate,
			NULL) == dbINVALID)
	{
		elog_die(1,"save_origin: dbaddv error writing orid %ld\n",
				orid);
	}
	return(orid);
}
// return local time (UTC time plus time zone offset)
time_t OpenSprinkler::now_tz() {
  return now()+(int32_t)3600/4*(int32_t)(options[OPTION_TIMEZONE].value-48);
}
Esempio n. 28
0
void initpf( char *pf )
 
{
   double epoch, sec;
   Pf  *Param;
   Tbl *Inputs;
   Arr *pfarr;
   DIR *dirp;
   struct dirent *direntp;
   char *istr;
   char *path, exten[132], name[132], *pfile;
   int getone = 0;
   int yr, day, hr, min;
   int i, n, ninputs;
 
 
   if( (pfile = (char *) malloc(256)) == NULL)  
     elog_die( 1, "initpf(): malloc error\n");
 
/* Get today's time  */
 
   if( pf == NULL )  {
      epoch = now();
      e2h(epoch, &yr, &day, &hr, &min, &sec);
      
      /* Get List of Parameter Files  */
 
      if( (path = getenv("DASPF_PATH") ) == NULL || (int) strlen(path) <= 0 )  { 
            DASPF = "pkt"; 
     
      }  else  {
         sprintf( pfile, "%04d%03d%02d%02d\0", yr, day, hr, min);
         dirp = opendir(path);
         if(dirp == NULL) 
            elog_die(1, "initIP():Can't open %s directory.\n", path);
         pfarr = newarr( 0 );
         while ( (direntp = readdir(dirp)) != NULL ) {
            istr = direntp->d_name;
            fexten( istr, exten);
            if( strncmp( exten, "pf", strlen("pf")) == 0)
               setarr( pfarr, direntp->d_name, "Y" );
         }
 
       /* Get the most recent PF name  */
 
         Inputs = keysarr( pfarr );
         ninputs = maxtbl( Inputs );
         for( i = 0; i < ninputs; i++ )  {
           istr = ( char *) gettbl( Inputs, i );
           if( strcmp( istr, pfile ) == 0 ) {
              sprintf( pfile, "%s/%s\0", path, istr);
              getone = 1; break;
           }
           else if( strcmp( istr, pfile ) > 0 )  {
              if( i == 0 )
                 istr = ( char *) gettbl( Inputs, (0));
              else 
                 istr = ( char *) gettbl( Inputs, (i -1));
              strncpy( name, istr, strlen(istr));
              name[strlen(istr)-strlen(".pf")] = '\0';
              for(n = 0; n < (int) strlen(name); n++)
                 if(!isdigit(name[n])) break;
              if( n == (int) strlen(name))
                   sprintf( pfile, "%s/%s\0",path, istr);
              else 
                  sprintf( pfile, "pkt.pf" );
              getone = 1; break;
           }
         }  /* end for  */
         if( !getone ) {
            istr = ( char *) gettbl( Inputs, (ninputs -1));
            sprintf( pfile, "%s/%s\0",path, istr);
         }
 
/* Read configuration file  */
      
         pfile[strlen(pfile)-strlen(".pf")] = '\0'; 
         DASPF = pfile;
         freearr( pfarr, 0 ); 
         closedir( dirp ); 
      }
   }  else {
 
/* Read configuration file  */

      fexten( pf, exten);
      if( strncmp( exten, "pf", strlen("pf")) == 0)
         pf[strlen(pf) - strlen(".pf")] = '\0';
      DASPF =  pf;
   }
  
}
Esempio n. 29
0
 virtual void schedule(const schedulable& scbl) const {
     schedule(now(), scbl);
 }
Esempio n. 30
0
int main(int argc, char *argv[])
{
  int          ix, num, prec = PRECISION;
  mp_int       a, b, c, d;
  instant_t    start, finish;
  time_t       seed;
  unsigned int d1, d2;

  seed = time(NULL);

  if(argc < 2) {
    fprintf(stderr, "Usage: %s <num-tests>\n", argv[0]);
    return 1;
  }

  if((num = atoi(argv[1])) < 0)
    num = -num;

  printf("Test 5a: Euclid vs. Binary, a GCD speed test\n\n"
	 "Number of tests: %d\n"
	 "Precision:       %d digits\n\n", num, prec);

  mp_init_size(&a, prec);
  mp_init_size(&b, prec);
  mp_init(&c);
  mp_init(&d);

  printf("Verifying accuracy ... \n");
  srand((unsigned int)seed);
  for(ix = 0; ix < num; ix++) {
    mpp_random_size(&a, prec);
    mpp_random_size(&b, prec);

    mp_gcd(&a, &b, &c);
    mp_bgcd(&a, &b, &d);

    if(mp_cmp(&c, &d) != 0) {
      printf("Error!  Results not accurate:\n");
      printf("a = "); mp_print(&a, stdout); fputc('\n', stdout);
      printf("b = "); mp_print(&b, stdout); fputc('\n', stdout);
      printf("c = "); mp_print(&c, stdout); fputc('\n', stdout);
      printf("d = "); mp_print(&d, stdout); fputc('\n', stdout);

      mp_clear(&a); mp_clear(&b); mp_clear(&c); mp_clear(&d);
      return 1;
    }
  }
  mp_clear(&d);
  printf("Accuracy confirmed for the %d test samples\n", num);

  printf("Testing Euclid ... \n");
  srand((unsigned int)seed);
  start = now();
  for(ix = 0; ix < num; ix++) {
    mpp_random_size(&a, prec);
    mpp_random_size(&b, prec);
    mp_gcd(&a, &b, &c);

  }
  finish = now();

  d1 = (finish.sec - start.sec) * 1000000;
  d1 -= start.usec; d1 += finish.usec;

  printf("Testing binary ... \n");
  srand((unsigned int)seed);
  start = now();
  for(ix = 0; ix < num; ix++) {
    mpp_random_size(&a, prec);
    mpp_random_size(&b, prec);
    mp_bgcd(&a, &b, &c);
  }
  finish = now();

  d2 = (finish.sec - start.sec) * 1000000;
  d2 -= start.usec; d2 += finish.usec;

  printf("Euclidean algorithm time: %u usec\n", d1);
  printf("Binary algorithm time:    %u usec\n", d2);
  printf("Improvement:              %.2f%%\n",
         (1.0 - ((double)d2 / (double)d1)) * 100.0);

  mp_clear(&c);
  mp_clear(&b);
  mp_clear(&a);

  return 0;
}