示例#1
0
void ClientWorker2::performEcho(const std::shared_ptr<Client>& client) {
  std::string sendStr(getConfig()->pickSendSize(), 'a');
  std::string recvStr;
  client->sync_echo(recvStr, sendStr);
}
示例#2
0
RateControl::RateControl(const char* _group,
                         ConfigObject<ConfigValue>* _config)
    : EngineControl(_group, _config),
      m_pBpmControl(NULL),
      m_ePbCurrent(0),
      m_ePbPressed(0),
      m_bTempStarted(false),
      m_dTempRateChange(0.0),
      m_dRateTemp(0.0),
      m_eRampBackMode(RATERAMP_RAMPBACK_NONE),
      m_dRateTempRampbackChange(0.0) {
    m_pScratchController = new PositionScratchController(_group);

    m_pRateDir = new ControlObject(ConfigKey(_group, "rate_dir"));
    m_pRateRange = new ControlObject(ConfigKey(_group, "rateRange"));
    m_pRateSlider = new ControlPotmeter(ConfigKey(_group, "rate"), -1.f, 1.f);

    // Search rate. Rate used when searching in sound. This overrules the
    // playback rate
    m_pRateSearch = new ControlPotmeter(ConfigKey(_group, "rateSearch"), -300., 300.);

    // Reverse button
    m_pReverseButton = new ControlPushButton(ConfigKey(_group, "reverse"));
    m_pReverseButton->set(0);

    // Forward button
    m_pForwardButton = new ControlPushButton(ConfigKey(_group, "fwd"));
    connect(m_pForwardButton, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlFastForward(double)),
            Qt::DirectConnection);
    m_pForwardButton->set(0);

    // Back button
    m_pBackButton = new ControlPushButton(ConfigKey(_group, "back"));
    connect(m_pBackButton, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlFastBack(double)),
            Qt::DirectConnection);
    m_pBackButton->set(0);

    m_pReverseRollButton = new ControlPushButton(ConfigKey(_group, "reverseroll"));
    connect(m_pReverseRollButton, SIGNAL(valueChanged(double)),
            this, SLOT(slotReverseRollActivate(double)),
            Qt::DirectConnection);

    m_pSlipEnabled = new ControlObjectSlave(_group, "slip_enabled", this);

    m_pVCEnabled = ControlObject::getControl(ConfigKey(getGroup(), "vinylcontrol_enabled"));
    m_pVCScratching = ControlObject::getControl(ConfigKey(getGroup(), "vinylcontrol_scratching"));

    // Permanent rate-change buttons
    buttonRatePermDown =
        new ControlPushButton(ConfigKey(_group,"rate_perm_down"));
    connect(buttonRatePermDown, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRatePermDown(double)),
            Qt::DirectConnection);

    buttonRatePermDownSmall =
        new ControlPushButton(ConfigKey(_group,"rate_perm_down_small"));
    connect(buttonRatePermDownSmall, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRatePermDownSmall(double)),
            Qt::DirectConnection);

    buttonRatePermUp =
        new ControlPushButton(ConfigKey(_group,"rate_perm_up"));
    connect(buttonRatePermUp, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRatePermUp(double)),
            Qt::DirectConnection);

    buttonRatePermUpSmall =
        new ControlPushButton(ConfigKey(_group,"rate_perm_up_small"));
    connect(buttonRatePermUpSmall, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRatePermUpSmall(double)),
            Qt::DirectConnection);

    // Temporary rate-change buttons
    buttonRateTempDown =
        new ControlPushButton(ConfigKey(_group,"rate_temp_down"));
    connect(buttonRateTempDown, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRateTempDown(double)),
            Qt::DirectConnection);

    buttonRateTempDownSmall =
        new ControlPushButton(ConfigKey(_group,"rate_temp_down_small"));
    connect(buttonRateTempDownSmall, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRateTempDownSmall(double)),
            Qt::DirectConnection);

    buttonRateTempUp =
        new ControlPushButton(ConfigKey(_group,"rate_temp_up"));
    connect(buttonRateTempUp, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRateTempUp(double)),
            Qt::DirectConnection);

    buttonRateTempUpSmall =
        new ControlPushButton(ConfigKey(_group,"rate_temp_up_small"));
    connect(buttonRateTempUpSmall, SIGNAL(valueChanged(double)),
            this, SLOT(slotControlRateTempUpSmall(double)),
            Qt::DirectConnection);

    // We need the sample rate so we can guesstimate something close
    // what latency is.
    m_pSampleRate = ControlObject::getControl(ConfigKey("[Master]","samplerate"));

    // Wheel to control playback position/speed
    m_pWheel = new ControlTTRotary(ConfigKey(_group, "wheel"));

    // Scratch controller, this is an accumulator which is useful for
    // controllers that return individiual +1 or -1s, these get added up and
    // cleared when we read
    m_pScratch = new ControlTTRotary(ConfigKey(_group, "scratch2"));
    m_pOldScratch = new ControlTTRotary(ConfigKey(_group, "scratch"));  // Deprecated

    // Scratch enable toggle
    m_pScratchToggle = new ControlPushButton(ConfigKey(_group, "scratch2_enable"));
    m_pScratchToggle->set(0);

    m_pJog = new ControlObject(ConfigKey(_group, "jog"));
    m_pJogFilter = new Rotary();
    // FIXME: This should be dependent on sample rate/block size or something
    m_pJogFilter->setFilterLength(25);

    // Update Internal Settings
    // Set Pitchbend Mode
    m_eRateRampMode = (RateControl::RATERAMP_MODE)
            getConfig()->getValueString(ConfigKey("[Controls]","RateRamp")).toInt();

    // Set the Sensitivity
    m_iRateRampSensitivity =
            getConfig()->getValueString(ConfigKey("[Controls]","RateRampSensitivity")).toInt();

    m_pSyncMode = new ControlObjectSlave(_group, "sync_mode", this);
}
示例#3
0
ContactsSource::ContactsSource(QObject* parent, const QVariantList& args)
    : FunambolSyncSource(parent, args),
    d(new ContactsSource::Private)
{
    setSourceUID("contacts-test-stub-plugin");
    setSyncMimeType("application/base64"); // test
    setRemoteURI("http://localhost/", Base64); // Is this needed?
    
    ContactsBackend *backend = new ContactsBackend("contacts-test-stub-plugin",
                                   dynamic_cast<Funambol::AbstractSyncSourceConfig *>(getConfig()));
    setBackend(backend);
}
示例#4
0
文件: musicmgr.c 项目: foxbow/mixplay
/**
 * adds a new title to the current playlist
 *
 * Core functionality of the mixplay architecture:
 * - does not play the same artist twice in a row
 * - prefers titles with lower playcount
 *
 * returns the head of the (new/current) playlist
 */
mpplaylist *addNewTitle( mpplaylist *pl, mptitle *root ) {
	mptitle *runner=NULL;
	mptitle *guard=NULL;
	unsigned long num=0;
	char *lastpat;
	unsigned int pcount=getConfig()->playcount;
	unsigned int cycles=0;
	int valid=0;
	/* 0 - nothing checked
	   1 - namecheck okay
	   2 - playcount okay
	   3 - all okay
	  -1 - stuffing
	*/

	if( pl != NULL ) {
		while( pl->next != NULL ) {
			pl=pl->next;
		}
		runner=pl->title;
		lastpat=pl->title->artist ;
	}
	else {
		valid=1;
		runner=root;
	}

	/* select a random title from the database */
	/* skip forward until a title is found that is neither DNP nor MARK */
	num = countTitles( MP_ALL, MP_DNP|MP_MARK|MP_CNTD );
	runner=skipTitles( runner, rand()%num );

	if( runner==NULL ) {
		if( pl == NULL ) {
			addMessage( 0, "No titles in database and no playlist to add them to.." );
			return NULL;
		}
		runner=pl->title;
		addMessage( 0, "Next round!" );
		newCount( );
		/* Try again */
		num = countTitles( MP_ALL, MP_DNP|MP_MARK|MP_CNTD );
		runner=skipTitles( runner, rand()%num );
		if( runner == NULL ) {
			addMessage( 0, "No more titles in the database!?" );
			return NULL;
		}
	}

	cycles=0;

	while( ( valid & 3 ) != 3 ) {
		if( lastpat == NULL ) valid |=1;
		/* title did not pass namecheck */
		if( ( valid & 1 ) != 1 ) {
			guard=runner;

			while( checkSim( runner->artist, lastpat ) ) {
				addMessage( 3, "%s = %s", runner->artist, lastpat );
				activity( "Nameskipping" );
				runner=skipOver( runner->next, 1 );

				/* hopefully this will not happen */
				if( (runner == guard ) || ( runner == NULL ) ) {
					addMessage( 0, "Only %s left..", lastpat );
					newCount( );
					return(	addNewTitle( pl, root ) );
				}
			}
			addMessage( 3, "%s != %s", runner->artist, lastpat );

			if( guard != runner ) {
				valid=1; /* we skipped and need to check playcount */
			}
			else {
				valid |= 1; /* we did not skip, so if playcount was fine it's still fine */
			}
		}

		guard=runner;
		/* title did not pass playcountcheck and we are not in stuffing mode */
		while( (valid & 2 ) != 2 ) {
			if( runner->flags & MP_FAV ) {
				if ( runner-> playcount <= 2*pcount ) {
					valid|=2;
				}
			}
			else {
				if ( runner->playcount <= pcount ) {
					valid|=2;
				}
			}

			if( ( valid & 2 ) != 2 ) {
				activity( "Playcountskipping" );
				/* simply pick a new title at random to avoid edge cases */
				runner=skipTitles( runner, rand()%num );
				valid=0;

				if( (runner == NULL ) || ( guard == runner ) ) {
					pcount++;	/* allow more replays */
					getConfig()->playcount=pcount;
					addMessage( 1, "Increasing maxplaycount to %li", pcount );
					runner=guard;
				}
			}
		}

		if( ++cycles > 10 ) {
			addMessage( 1, "Looks like we ran into a loop" );
			cycles=0;
			pcount++;	/* allow replays */
			getConfig()->playcount=pcount;
			addMessage( 1, "Increasing maxplaycount to %li", pcount );
		}
	} /* while( valid != 3 ) */

	addMessage( 3, "[+] (%i/%li/%3s) %s", runner->playcount, pcount, ONOFF( runner->flags&MP_FAV ), runner->display );

	/* count again in case this is a favourite */
	if( runner->flags & MP_FAV ) {
		runner->flags &= ~MP_CNTD;
	}
	addMessage(2,"Added %2d %5d - %s", runner->playcount, runner->key, runner->display );
	return appendToPL( runner, pl, -1 );
}
示例#5
0
文件: musicmgr.c 项目: foxbow/mixplay
/**
 * adds searchresults to the playlist
 * range - title-display/artist/album
 * arg - either a title key or a string
 * insert - play next or append to the end of the playlist
 */
int playResults( mpcmd range, const char *arg, const int insert ) {
	mpconfig   *config=getConfig();
	mpplaylist *pos=config->current;
	mpplaylist *end=NULL;
	mpplaylist *res=config->found->titles;
	mptitle *title=NULL;
	int key=atoi(arg);

	/* insert results at current pos or at the end? */
	if( (pos != NULL ) && ( insert == 0 ) ) {
		while( pos->next != NULL ) {
			pos=pos->next;
		}
	}

	if( ( range == mpc_title ) || ( range == mpc_display ) ) {
		/* Play the current resultlist */
		if( key == 0 ) {
			/* should not happen but better safe than sorry! */
			if( config->found->tnum == 0 ) {
				addMessage( 0, "No results to be added!" );
				return 0;
			}
			if( config->found->titles == NULL ) {
				addMessage( 0, "%i titles found but none in list!", config->found->tnum );
				return 0;
			}

			end=res;
			/* find end of searchresults and mark titles as counted on the way */
			end->title->flags|=MP_CNTD;
			while( end->next != NULL ) {
				end=end->next;
				end->title->flags|=MP_CNTD;
			}

			while( res!=NULL ) {
				res->title->flags|=MP_CNTD;
				pos=addToPL( res->title, pos, 0 );
				if( config->current == NULL ) {
					config->current=pos;
				}
				res=res->next;
			}

			notifyChange();
			return config->found->tnum;
		}

		/* play only one */
		title=getTitleByIndex(key);
		if( title == NULL ) {
			addMessage( 0, "No title with key %i!", key );
			return 0;
		}
		/*
		 * do not count this title as played and do not mark it skipped during this play
		 * this will be reverted after play if needed.
		 */
		title->flags|=MP_CNTD;
		/*
		 * Do not touch marking, we searched the title so it's playing out of order.
		 * It has been played before? Don't care, we want it now and it won't come back!
		 * It's not been played before? Then play it now and whenever it's time comes.
		 */
		pos=addToPL( title, pos, 0 );
		if( config->current == NULL ) {
			config->current=pos;
		}

		notifyChange();
		return 1;
	}

	addMessage( 0, "Range not supported!" );
	return 0;
}
示例#6
0
文件: view.cpp 项目: qhliao/Equalizer
void View::updateCapabilities()
{
    CapabilitiesUpdater visitor( this );
    getConfig()->accept( visitor );
    setCapabilities( visitor.getCapabilities( ));
}
PermutationScorer::PermutationScorer(const string &distanceMetric, const string &config)
  :StatisticsBasedScorer(distanceMetric,config)
{
  //configure regularisation

  static string KEY_REFCHOICE = "refchoice";
  static string REFCHOICE_AVERAGE = "average";
  static string REFCHOICE_CLOSEST = "closest";

  string refchoice = getConfig(KEY_REFCHOICE,REFCHOICE_CLOSEST);
  if (refchoice == REFCHOICE_AVERAGE) {
    m_refChoiceStrategy = REFERENCE_CHOICE_AVERAGE;
  } else if (refchoice == REFCHOICE_CLOSEST) {
    m_refChoiceStrategy = REFERENCE_CHOICE_CLOSEST;
  } else {
    throw runtime_error("Unknown reference choice strategy: " + refchoice);
  }
  cerr << "Using reference choice strategy: " << refchoice << endl;

  if (distanceMetric.compare("HAMMING") == 0) {
    m_distanceMetric = HAMMING_DISTANCE;
  } else if (distanceMetric.compare("KENDALL") == 0) {
    m_distanceMetric = KENDALL_DISTANCE;
  }
  cerr << "Using permutation distance metric: " << distanceMetric << endl;

  //Get reference alignments from scconfig refalign option
  static string KEY_ALIGNMENT_FILES = "refalign";
  string refalign = getConfig(KEY_ALIGNMENT_FILES,"");
  //cout << refalign << endl;
  if (refalign.length() > 0) {
    string substring;
    while (!refalign.empty()) {
      getNextPound(refalign, substring, "+");
      m_referenceAlignments.push_back(substring);
    }
  }

  //Get length of source sentences read in from scconfig source option
  // this is essential for extractor but unneccesary for mert executable
  static string KEY_SOURCE_FILE = "source";
  string sourceFile = getConfig(KEY_SOURCE_FILE,"");
  if (sourceFile.length() > 0) {
    cerr << "Loading source sentence lengths from " << sourceFile << endl;
    ifstream sourcein(sourceFile.c_str());
    if (!sourcein) {
      throw runtime_error("Unable to open: " + sourceFile);
    }
    string line;
    while (getline(sourcein,line)) {
      size_t wordNumber = 0;
      string word;
      while(!line.empty()) {
        getNextPound(line, word, " ");
        wordNumber++;
      }
      m_sourceLengths.push_back(wordNumber);
    }
    sourcein.close();
  }
}
示例#8
0
文件: drink.c 项目: charwliu/xia-core
int main(int argc, char **argv)
{
	struct addrinfo *ai;
	sockaddr_x *sa;
	int seq = 0;

// FIXME: put signal handlers back into code once Xselect is working
//	signal(SIGINT, handler);
//	signal(SIGTERM, handler);
	getConfig(argc, argv);

	if (Xgetaddrinfo(NAME, NULL, NULL, &ai) < 0)
		die("Unable to lookup address for  %s\n", NAME);
	sa = (sockaddr_x*)ai->ai_addr;

	if ((sock = Xsocket(AF_XIA, SOCK_STREAM, 0)) < 0)
		die("Unable to create a socket\n");

	say("Opening firehose: %s\n", NAME);
	if (Xconnect(sock, (struct sockaddr*)sa, sizeof(sockaddr_x)) < 0) {
		Xclose(sock);
		die("Unable to connect to %s\n", NAME);
	}

	// tell firehose how many packets we expect
	if (Xsend(sock, &fhc, sizeof(fhc), 0) < 0) {
		Xclose(sock);
		die("Unable to send config information to the firehose\n");
	}

	int count = 0;
	char  *buf = (char *)malloc(pktSize);

	while (!timetodie) {
		int n;
		fd_set fds;
		FD_ZERO(&fds);
		FD_SET(sock, &fds);

		struct timeval tv;
		tv.tv_sec = 2;
		tv.tv_usec = 0;

		if ((n = Xselect(sock + 1, &fds, NULL, NULL, &tv)) < 0) {
			printf("select failed\n");
			break;

		} else if (n == 0) {
			printf("recv timeout\n");
			break;
		} else if (!FD_ISSET(sock, &fds)) {
			// this shouldn't happen!
			printf("something is really wrong, exiting\n");
			break;
		}

		int rc = Xrecv(sock, buf, sizeof(buf), 0);
		if (rc < 0)
			die("Receive failure\n");
		memcpy(&seq, buf, sizeof(int));

		say("expecting %d, got %d", count, seq);
		if (count == seq)
			say("\n");
		else
			say(" lost %d\n", seq - count);
		count++;
		if (count == numPkts)
			break;
		if (delay)
			usleep(delay);
	}

	seq++;
	if (count != seq)
		printf("lost %d packets, received %d, expected %d\n", seq - count, count, seq); 
	else
		printf("success!\n");
	Xclose(sock);
}
bool UpdateManager::isRecommended() {
    UpdaterConfig& config = ((OutlookConfig*)getConfig())->getUpdaterConfig();
    return (config.getRecommended() != "0") ? true : false;
}
示例#10
0
//=========================================================================
void BubbleChartView::prepareScene()
{
    QPen peng(Qt::black);
    peng.setWidth(1.5);
    QBrush brushg(Qt::transparent);
    chartRectGI = scene()->addRect(chartRect, peng, brushg);
    gGrid.addToGroup(chartRectGI);
    setHeader(/*chartData.header*/ "Chart header");
    ChartDataProvider *dp = dataProvider();
    if ( dp->data.size() == 0 )
        return;
    QPen pen(Qt::lightGray);
    pen.setWidth(0.05);
    QBrush brush(Qt::transparent);
    quint32 swidth = (int)this->sceneRect().height()*0.8;
    quint32 columnWidth = qMin((quint32)getConfig()->bubbleSize, swidth/dp->providers->count());
    grid.clear();
    for ( int i = 0; i < dp->providers->size(); i++ )
    {
        BlastTaxDataProvider *provider = dp->providers->at(i);
        for ( int j = 0; j < dp->data.count(); j++)
        {
            if ( !dp->data.at(j).checked )
                continue;
            const BlastTaxNodes &btns = dp->data.at(j).tax_nodes;
            BlastTaxNode *node = btns.at(i);
            if ( node != NULL )
            {
                quint32 sum = node->sum();
                if ( sum == 0 )
                    continue;
                CreateGraphNode(node, provider);
            }
        }
        qreal x1 = i*columnWidth;
        QGraphicsRectItem *gridItem  = scene()->addRect(chartRect.x()+x1, chartRect.y(), columnWidth, chartRect.height(), pen, brush);
        grid.append(gridItem);
        gGrid.addToGroup(gridItem);
        scene()->addItem(&gGrid);
        gGrid.setVisible(getConfig()->showGrid);
        // Create horizontal axe labels
        BlastTaxDataProvider *p = dp->providers->at(i);
        QString stxt = p->name;
        if ( stxt.length() > 30 )
        {
            stxt.truncate(27);
            stxt.append("...");
        }
        QGraphicsTextItem *item = scene()->addText(stxt);
        item->setToolTip(p->name);
        item->setRotation(45);
        horizontalLegend.append(item);
    }
    for ( int j = 0; j < dp->data.count(); j++)
    {
        const BlastTaxNodes &btns = dp->data.at(j).tax_nodes;
        QString txt;
        for ( int i = 0 ; i < btns.size(); i++ )
        {
            if ( btns[i] == NULL )
                continue;
            txt = btns[i]->getText();
            break;
        }
        QString stxt = txt;
        if ( stxt.length() > 30 )
        {
            stxt.truncate(27);
            stxt.append("...");
        }
        QGraphicsTextItem *item = scene()->addText(stxt);
        item->installEventFilter(this);
        item->setToolTip(txt);
        item->setVisible(dp->data.at(j).checked);
        verticalLegend.append(item);
    }

    header->setPos(0, 10-MARGIN);
    quint32 tw = header->textWidth();
    header->setTextWidth(qMax(tw, dp->providers->count()*columnWidth));
}
示例#11
0
/*
 *
 *	main()
 *
 */
int main(void)
{
	struct sockaddr_in serverAddr;	/* server's address */
	struct timeval timeout;
	int status;
	struct ioc_log_server *pserver;

	osiSockIoctl_t	optval;

	status = getConfig();
	if(status<0){
		fprintf(stderr, "iocLogServer: EPICS environment underspecified\n");
		fprintf(stderr, "iocLogServer: failed to initialize\n");
		return IOCLS_ERROR;
	}

	pserver = (struct ioc_log_server *) 
			calloc(1, sizeof *pserver);
	if(!pserver){
		fprintf(stderr, "iocLogServer: %s\n", strerror(errno));
		return IOCLS_ERROR;
	}

	pserver->pfdctx = (void *) fdmgr_init();
	if(!pserver->pfdctx){
		fprintf(stderr, "iocLogServer: %s\n", strerror(errno));
		return IOCLS_ERROR;
	}

	/*
	 * Open the socket. Use ARPA Internet address format and stream
	 * sockets. Format described in <sys/socket.h>.
	 */
	pserver->sock = epicsSocketCreate(AF_INET, SOCK_STREAM, 0);
	if (pserver->sock==INVALID_SOCKET) {
        char sockErrBuf[64];
        epicsSocketConvertErrnoToString ( sockErrBuf, sizeof ( sockErrBuf ) );
		fprintf(stderr, "iocLogServer: sock create err: %s\n", sockErrBuf);
		return IOCLS_ERROR;
	}
	
    epicsSocketEnableAddressReuseDuringTimeWaitState ( pserver->sock );

	/* Zero the sock_addr structure */
	memset((void *)&serverAddr, 0, sizeof serverAddr);
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(ioc_log_port);

	/* get server's Internet address */
	status = bind (	pserver->sock, 
			(struct sockaddr *)&serverAddr, 
			sizeof (serverAddr) );
	if (status<0) {
        char sockErrBuf[64];
        epicsSocketConvertErrnoToString ( sockErrBuf, sizeof ( sockErrBuf ) );
		fprintf(stderr, "iocLogServer: bind err: %s\n", sockErrBuf );
		fprintf (stderr,
			"iocLogServer: a server is already installed on port %u?\n", 
			(unsigned)ioc_log_port);
		return IOCLS_ERROR;
	}

	/* listen and accept new connections */
	status = listen(pserver->sock, 10);
	if (status<0) {
        char sockErrBuf[64];
        epicsSocketConvertErrnoToString ( sockErrBuf, sizeof ( sockErrBuf ) );
		fprintf(stderr, "iocLogServer: listen err %s\n", sockErrBuf);
		return IOCLS_ERROR;
	}

	/*
	 * Set non blocking IO
	 * to prevent dead locks
	 */
	optval = TRUE;
	status = socket_ioctl(
					pserver->sock,
					FIONBIO,
					&optval);
	if(status<0){
        char sockErrBuf[64];
        epicsSocketConvertErrnoToString ( sockErrBuf, sizeof ( sockErrBuf ) );
		fprintf(stderr, "iocLogServer: ioctl FIONBIO err %s\n", sockErrBuf);
		return IOCLS_ERROR;
	}

#	ifdef UNIX
		status = setupSIGHUP(pserver);
		if (status<0) {
			return IOCLS_ERROR;
		}
#	endif

	status = openLogFile(pserver);
	if (status<0) {
		fprintf(stderr,
			"File access problems to `%s' because `%s'\n", 
			ioc_log_file_name,
			strerror(errno));
		return IOCLS_ERROR;
	}

	status = fdmgr_add_callback(
			pserver->pfdctx, 
			pserver->sock, 
			fdi_read,
			acceptNewClient,
			pserver);
	if(status<0){
		fprintf(stderr,
			"iocLogServer: failed to add read callback\n");
		return IOCLS_ERROR;
	}


	while(TRUE){
		timeout.tv_sec = 60; /* 1 min */
		timeout.tv_usec = 0;
		fdmgr_pend_event(pserver->pfdctx, &timeout);
		fflush(pserver->poutfile);
	}
}
示例#12
0
//=========================================================================
void BubbleChartView::setChartRectSize(int w, int h)
{
    chartRect = QRectF(0, 0, w, h);
    scene()->setSceneRect(-4*MARGIN, getConfig()->showTitle ? -MARGIN : 0, chartRect.width()+4*MARGIN, chartRect.height()+MARGIN+(getConfig()->showTitle ? MARGIN : 0));
}
示例#13
0
//=========================================================================
void BubbleChartView::showChart(bool forceNodeUpdate)
{
    ChartDataProvider *chartDataProvider = dataProvider();
    if ( chartDataProvider->data.size() == 0 )
        return;
    quint32 sheight = (int)this->size().height()*0.8;
    quint32 swidth = (int)this->sceneRect().height()*0.8;
    quint32 tsize = dataProvider()->visibleTaxNumber();
    quint32 bubbleSize = getConfig()->bubbleSize;
    quint32 maxBubbleSize = tsize == 0 ? 0 : qMin(bubbleSize, sheight/tsize);
    quint32 columnWidth = qMin(bubbleSize, swidth/dataProvider()->providers->count())+getConfig()->horInterval;
    quint32 rowHeight = maxBubbleSize + getConfig()->vertInterval;
    int rnum = 0;
    quint32 column = 0;
    for ( int j = 0; j < chartDataProvider->data.count(); j++)
    {
        const BlastTaxNodes &btns = chartDataProvider->data.at(j).tax_nodes;
        if ( !chartDataProvider->data.at(j).checked )
            continue;
        column = 0;
        // In some corner cases if not all the data providers are correctly restored
        // it is possible that no nodes should be created for the spices
        bool has_node = false;
        for ( int i = 0; i < btns.size(); i++ )
        {
            if ( !chartDataProvider->getBlastTaxDataProviders()->isVisible(i) )
                continue;
            qreal x1 = (column++)*columnWidth;
            BlastTaxNode *node = btns.at(i);
            if ( node == NULL || node->sum() == 0 )
                continue;
            has_node = true;
            ChartGraphNode *gnode = (ChartGraphNode*)node->getGnode();
            Q_ASSERT_X(gnode != NULL, "showChart", "GraphNode must be created here");            
            gnode->setMaxNodeSize(bubbleSize);
            gnode->setPos(chartRect.x()+x1+columnWidth/2, chartRect.y()+(rnum)*rowHeight+rowHeight/2);
            if ( forceNodeUpdate )
                gnode->update();
        }
        if ( has_node )
        {
            verticalLegend[j]->setPos(chartRect.x()-verticalLegend[j]->boundingRect().width(), rnum*rowHeight);
            ++rnum;
        }
    }
    quint32 rectHeight = rnum*rowHeight + maxBubbleSize/2;
    chartRectGI->setRect(chartRect.x(), chartRect.y(), column*columnWidth, rectHeight);
    if ( header->isVisible() && false )
    {
        header->setPos(0, 10-MARGIN);
        header->setTextWidth(column*columnWidth);
    }
    column = 0;
    for ( int i = 0; i < chartDataProvider->providers->size(); i++ )
    {
        if ( !horizontalLegend.at(i)->isVisible() )
            continue;
        qreal x1 = column*columnWidth;
        grid.at(i)->setRect(chartRect.x()+x1, chartRect.y(), columnWidth, rectHeight);
        horizontalLegend.at(i)->setPos(chartRect.x()+x1+columnWidth/2, chartRect.y()+rectHeight+5);
        column++;
    }
}
示例#14
0
std::shared_ptr<ClientWorker2::Client> ClientWorker2::createConnection() {
  const std::shared_ptr<ClientLoadConfig>& config = getConfig();
  std::shared_ptr<TAsyncSocket> socket;
  std::unique_ptr<
    RequestChannel,
    apache::thrift::async::TDelayedDestruction::Destructor> channel;
  if (config->useSR()) {
    facebook::servicerouter::ConnConfigs configs;
    facebook::servicerouter::ServiceOptions options;
    configs["sock_sendtimeout"] = folly::to<std::string>(kTimeout);
    configs["sock_recvtimeout"] = folly::to<std::string>(kTimeout);
    if (config->SASLPolicy() == "required" ||
        config->SASLPolicy() == "permitted") {
      configs["thrift_security"] = config->SASLPolicy();
      if (!config->SASLServiceTier().empty()) {
        configs["thrift_security_service_tier"] = config->SASLServiceTier();
      }
    }
    channel = std::move(facebook::servicerouter::cpp2::getClientFactory()
                                        .getChannel(config->srTier(),
                                                    ebm_.getEventBase(),
                                                    std::move(options),
                                                    std::move(configs)));
  } else {
    if (config->useSSL()) {
      std::shared_ptr<SSLContext> context = std::make_shared<SSLContext>();
      socket = TAsyncSSLSocket::newSocket(context, ebm_.getEventBase());
      socket->connect(nullptr, *config->getAddress());
      // Loop once to connect
      ebm_.getEventBase()->loop();
    } else {
      socket =
        TAsyncSocket::newSocket(ebm_.getEventBase(),
                                *config->getAddress());
    }
    std::unique_ptr<
      HeaderClientChannel,
      apache::thrift::async::TDelayedDestruction::Destructor> headerChannel(
          HeaderClientChannel::newChannel(socket));
    // Always use binary in loadtesting to get apples to apples comparison
    headerChannel->getHeader()->setProtocolId(
        apache::thrift::protocol::T_BINARY_PROTOCOL);
    if (config->zlib()) {
      headerChannel->getHeader()->setTransform(THeader::ZLIB_TRANSFORM);
    }
    if (!config->useHeaderProtocol()) {
      headerChannel->getHeader()->setClientType(THRIFT_FRAMED_DEPRECATED);
    }
    headerChannel->setTimeout(kTimeout);
    if (config->SASLPolicy() == "permitted") {
      headerChannel->getHeader()->setSecurityPolicy(THRIFT_SECURITY_PERMITTED);
    } else if (config->SASLPolicy() == "required") {
      headerChannel->getHeader()->setSecurityPolicy(THRIFT_SECURITY_REQUIRED);
    }

    if (config->SASLPolicy() == "required" ||
        config->SASLPolicy() == "permitted") {
      static auto saslThreadManager_ = std::make_shared<SaslThreadManager>();
      static auto ccManagerLogger_ = std::make_shared<SecurityLogger>();
      static auto credentialsCacheManager_ =
        std::make_shared<krb5::Krb5CredentialsCacheManager>(ccManagerLogger_);
      headerChannel->setSaslClient(std::unique_ptr<apache::thrift::SaslClient>(
        new apache::thrift::GssSaslClient(socket->getEventBase())
      ));
      headerChannel->getSaslClient()->setSaslThreadManager(saslThreadManager_);
      headerChannel->getSaslClient()->setCredentialsCacheManager(
        credentialsCacheManager_);
      headerChannel->getSaslClient()->setServiceIdentity(
        folly::format(
          "{}@{}",
          config->SASLServiceTier(),
          config->getAddressHostname()).str());
    }
    channel = std::move(headerChannel);
  }

  return std::shared_ptr<ClientWorker2::Client>(
    new ClientWorker2::Client(std::move(channel)));
}
示例#15
0
short *Audio_ALSA::open (AudioConfig &cfg, const char *)
{
    AudioConfig tmpCfg;

    if (_audioHandle != NULL)
    {
        _errorString = "ERROR: Device already in use";
        return NULL;
     }

    snd_pcm_uframes_t    buffer_frames;
    snd_pcm_hw_params_t *hw_params = 0;

    if (snd_pcm_open (&_audioHandle, "default", SND_PCM_STREAM_PLAYBACK, 0))
    {
        _errorString = "ERROR: Could not open audio device.";
        goto open_error;
    }

    // May later be replaced with driver defaults.
    tmpCfg = cfg;

    if (snd_pcm_hw_params_malloc (&hw_params))
    {
        _errorString = "ERROR: could not malloc hwparams.";
        goto open_error;
    }

    if (snd_pcm_hw_params_any (_audioHandle, hw_params))
    {
        _errorString = "ERROR: could not initialize hw params";
        goto open_error;
    }

    if (snd_pcm_hw_params_set_access (_audioHandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED))
    {
        _errorString = "ERROR: could not set access type";
        goto open_error;
    }

    if (snd_pcm_hw_params_set_format (_audioHandle, hw_params, SND_PCM_FORMAT_S16_LE))
    {
        _errorString = "ERROR: could not set sample format";
        goto open_error;
    }

    if (snd_pcm_hw_params_set_channels (_audioHandle, hw_params, tmpCfg.channels))
    {
        _errorString = "ERROR: could not set channel count";
        goto open_error;
    }

    {   // Gentoo bug #98769, comment 4
        unsigned int rate = tmpCfg.frequency;
        if (snd_pcm_hw_params_set_rate_near (_audioHandle, hw_params, &rate, 0))
        {
            _errorString = "ERROR: could not set sample rate";
            goto open_error;
        }
    }

    _alsa_to_frames_divisor = tmpCfg.channels;
    buffer_frames = 4096;
    snd_pcm_hw_params_set_period_size_near(_audioHandle, hw_params, &buffer_frames, 0);

    if (snd_pcm_hw_params (_audioHandle, hw_params))
    {
        _errorString = "ERROR: could not set hw parameters";
        goto open_error;
    }

    snd_pcm_hw_params_free (hw_params);
    hw_params = 0;

    if (snd_pcm_prepare (_audioHandle))
    {
        _errorString = "ERROR: could not prepare audio interface for use";
        goto open_error;
    }

    tmpCfg.bufSize = buffer_frames * _alsa_to_frames_divisor;
#ifdef HAVE_EXCEPTIONS
    _sampleBuffer = new(std::nothrow) short[tmpCfg.bufSize];
#else
    _sampleBuffer = new short[tmpCfg.bufSize];
#endif

    if (!_sampleBuffer)
    {
        _errorString = "AUDIO: Unable to allocate memory for sample buffers.";
        goto open_error;
    }

    // Setup internal Config
    _settings = tmpCfg;
    // Update the users settings
    getConfig (cfg);
    return _sampleBuffer;

open_error:
    if (hw_params)
        snd_pcm_hw_params_free (hw_params);
    if (_audioHandle != NULL)
        close ();
    perror ("ALSA");
    return NULL;
}
bool UpdateManager::checkForMandatoryUpdateBeforeStarting() {    

    UpdaterConfig& config = ((OutlookConfig*)getConfig())->getUpdaterConfig();
    updater.setUI(this);
    return updater.newVersionAvailable(true);
}
示例#17
0
文件: view.cpp 项目: qhliao/Equalizer
ServerPtr View::getServer()
{
    Config* config = getConfig();
    LBASSERT( config );
    return ( config ? config->getServer() : 0 );
}
NResponse & NTcpServerSocketUserServices::putUser(const NClientSession & session, NResponse & response)
{
    QScriptEngine se;
    QScriptValue svRoot = se.newObject();

    QString strId = session.resource();
    logDebug("svcPutUser strId", strId);
    bool ok;
    int id = strId.toInt(&ok);
    if (!ok)
    {
        svRoot.setProperty(RSP_SUCCESS , QScriptValue(false));
        svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_INVALID_USER));
        response.setData(NJson::serializeToQByteArray(svRoot));
        return response;
    }

    se.evaluate("var data = " + QString::fromUtf8(session.content()));
    if (se.hasUncaughtException()){
        svRoot.setProperty(RSP_SUCCESS , QScriptValue(false));
        svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_INVALID_JSON));
        logDebug("NTcpServerSocketUserServices::svcPutUser", se.uncaughtExceptionBacktrace());
        logDebug("NJson::serialize(svRoot)", NJson::serialize(svRoot));
        response.setData(NJson::serializeToQByteArray(svRoot));
        return response;
    }

    NStringMap user = NDB.getUserById(id);
    if (user.count()  == 0)
    {
        svRoot.setProperty(RSP_SUCCESS , QScriptValue(false));
        svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_INVALID_USER));
        //logDebug("NJson::serialize(svRoot)", NJson::serialize(svRoot));
        response.setData(NJson::serializeToQByteArray(svRoot));
        return response;
    }

    QScriptValue svReadUser = se.globalObject().property("data").property("data");
    QString email = svReadUser.property("email").toString();
    QString password = getConfig().toPasswordHash(svReadUser.property("password").toString());
    QString name = svReadUser.property("name").toString();
    QString preferences = svReadUser.property("preferences").toString();
    QString enabled = svReadUser.property("enabled").toString();
    QString level = NTcpServerAuthSession::normalizeLevels(svReadUser.property("level").toString());

    email = email.isEmpty() ? user["email"] : email;
    password = password.isEmpty() ? user["password"] : password;
    name = name.isEmpty() ? user["name"] : name;
    preferences = preferences.isEmpty() ? user["preferences"] : preferences;
    enabled = enabled.isEmpty() ? user["enabled"] : enabled;
    level = level.isEmpty() ? user["level"] : level;

    logDebug("email", email);
    logDebug("password", password);
    logDebug("name", name);
    logDebug("preferences", preferences);
    logDebug("enabled", enabled);
    logDebug("level", level);

    if (!NDB.updateUser(id, email, password, name, preferences,
                        QVariant(enabled).toBool(),level)) {
        svRoot.setProperty(RSP_SUCCESS , QScriptValue(false));
        svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_ERROR_OCCURRED));
        response.setData(NJson::serializeToQByteArray(svRoot));
        return response;
    }

    logMessage("User update succeed", QString("%1, %2 (%3); user agent: %4").
               arg(id).
               arg(email).
               arg(session.peerAddress()).
               arg(session.userAgent()));

    svRoot.setProperty(RSP_SUCCESS , QScriptValue(true));
    svRoot.setProperty(RSP_MSG, QScriptValue(QString(RSP_MSG_N_UPDATED).arg(id)));
    QScriptValue svData = se.newArray();
    svRoot.setProperty(RSP_DATA, svData);
    QScriptValue svUser = se.newObject();
    svData.setProperty(0, svUser);
    svUser.setProperty("id", id);
    svUser.setProperty("email", email);
    svUser.setProperty("name", name);
    svUser.setProperty("preferences", preferences);
    svUser.setProperty("enabled", QVariant(enabled).toBool());
    svUser.setProperty("level", level);

    response.setData(NJson::serializeToQByteArray(svRoot));
    return response;
}
void Widget::on_runScriptButton_clicked()
{
    QProcess *process = new QProcess();

    QString filename = "";
    if(ui->scriptFilenameEdit->text() == ""){
        filename = "sca_" + QDateTime::currentDateTime().toString("yyyy_MM_dd_hh_mm") + getOptions();
    }else{
        filename = ui->scriptFilenameEdit->text();
    }

    //process->setStandardOutputFile(filename);

    QString command = "cd;cd " + ui->scriptLocationEdit->text() + ";" + "python run-clang-tidy.py " + getConfig() +
            " -checks='-*,misc-suspicious-call-argument' -> " + QDir::currentPath() + "/" + filename;

    /*process->setWorkingDirectory(ui->scriptLocationEdit->text());

    this->setCursor(Qt::WaitCursor);*/
    process->start("gnome-terminal");
    process->waitForStarted();

    ui->textBrowser->setText(command);

    QApplication::clipboard()->setText(command);


    /*process = new QProcess();
    process->start("gedit", QStringList() << ui->scriptLocationEdit->text() + filename);
    process->waitForFinished();
    process->close();
    this->setCursor(Qt::ArrowCursor);*/
}
NResponse & NTcpServerSocketUserServices::postUser(const NClientSession & session, NResponse & response)
{
    QScriptEngine se;
    QScriptValue svRoot = se.newObject();

    se.evaluate("var data = " + QString::fromUtf8(session.content()));
    if (se.hasUncaughtException()){
        svRoot.setProperty(RSP_SUCCESS , QScriptValue(false));
        svRoot.setProperty(RSP_MSG, QScriptValue(RSP_MSG_INVALID_JSON));
        logDebug("NTcpServerSocketUserServices::svcPostUser", se.uncaughtExceptionBacktrace());
        logDebug("NJson::serialize(svRoot)", NJson::serialize(svRoot));
        response.setData(NJson::serializeToQByteArray(svRoot));
        return response;
    }

    QScriptValue svReadUser = se.globalObject().property("data").property("data");
    QString email = svReadUser.property("email").toString();
    QString name = svReadUser.property("name").toString();
    QString password = getConfig().toPasswordHash(svReadUser.property("password").toString());
    QString preferences = svReadUser.property("preferences").toString();
    QString enabled = svReadUser.property("enabled").toString();
    QString level = NTcpServerAuthSession::normalizeLevels(svReadUser.property("level").toString());

    logDebug("email", email);
    logDebug("name", name);
    logDebug("password", password);
    logDebug("preferences", preferences);
    logDebug("enabled", enabled);
    logDebug("level", level);

    // User already exists?
    NStringMap user = NDB.getUserByEmail(email);

    if (user.count() > 0) // User already exists
    {
        svRoot.setProperty(RSP_SUCCESS , QScriptValue(false));
        svRoot.setProperty(RSP_MSG, "User already exists");
        logMessage("Registration failed", QString("already registered; %1(%2); user agent: %3").
              arg(email).
              arg(session.peerAddress()).
              arg(session.userAgent()));

        response.setData(NJson::serializeToQByteArray(svRoot));
        return response;
    }

    // User do not exists
    int userId = NDB.addUser(name, email, password, level, preferences, QVariant(enabled).toBool());
    if (userId < 0) // Error
    {
        svRoot.setProperty(RSP_SUCCESS , QScriptValue(false));
        QString errorMsg;
        switch(userId){
        case DB_USER_ERROR_INVALID_PARAMS:
            errorMsg = "Invalid params";
            break;
        case  DB_USER_ERROR_QUERY:
            errorMsg = "Query error";
            break;
        }
        svRoot.setProperty(RSP_MSG, errorMsg);
        logMessage("User add failed", QString("%1; %2(%3); user agent: %4").
              arg(errorMsg).
              arg(email).
              arg(session.peerAddress()).
              arg(session.userAgent()));

        response.setData(NJson::serializeToQByteArray(svRoot));
        return response;
    }

    svRoot.setProperty(RSP_SUCCESS , QScriptValue(true));
    svRoot.setProperty(RSP_MSG, QString("User %1 added").arg(email));
    logMessage("User add succeed", QString("%1, %2(%3); user agent: %4").
               arg(userId).
               arg(email).
               arg(session.peerAddress()).
               arg(session.userAgent()));

    // We add new user to response
    QScriptValue svData = se.newArray(1);
    svRoot.setProperty(RSP_DATA, svData);
    QScriptValue svUser = se.newObject();
    svData.setProperty(0, svUser);
    svUser.setProperty("id", userId);
    svUser.setProperty("name", name);
    svUser.setProperty("email", email);
    svUser.setProperty("preferences", preferences);
    svUser.setProperty("enabled", QVariant(enabled).toBool());
    svUser.setProperty("level", level);

    response.setData(NJson::serializeToQByteArray(svRoot));
    return response;
}
示例#21
0
/**
 * Instantiate an application and replay a ledger history out
 * of the dump file `filename`.
 */
void
LedgerDump::loadTransactions (std::string const& filename)
{
    std::ifstream in (filename);
    require ((bool)in, "opening file");

    std::unique_ptr <Application> app (make_Application ());
    app->setup ();
    auto &lm = app->getLedgerMaster ();
    WriteLog (lsINFO, LedgerDump) << "Loading ledgers from " << filename;

    auto nTxs = 0;

    // app->setup() when called with START_UP == Config::FRESH calls
    // ApplicationImp::startNewLedger(). Unfortunately it starts the new
    // ledger at the wrong timestamp, so we call it again once we've read
    // the first ledger we're going to apply. However, it's worth
    // understanding that startNewLedger() establishes 3 ledgers:
    //
    // Ledger 0 is the genesis ledger, it's not a real ledger, just a
    //          number.
    //
    // Ledger 1 is the root-account deposit ledger, with a single pile of
    //          currency owned by a single account generated by the seed
    //          "masterpassword".
    //
    // Ledger 2 is created and closed immediately on start, not sure why.
    //
    // Ledger 3 is a new ledger chained to #2 and left open in
    //          ledgermaster.
    //
    // Ledger 3 is where replay should be starting, so (once we call
    // startNewLedger() again) we pull out ledger #2 and use it as the
    // parent of the new ledger 3 we're replaying, and throw away the #3
    // that was made by startNewLedger().

    Ledger::pointer parentLedger;

    while (in)
    {
        if ((gLedgerSeq & 0xfff) == 0) {
            Job j;
            app->doSweep (j);
        }

        Json::Value j = loadJsonRecord (in);

        Ledger::pointer deserializedLedger;
        SHAMap::pointer txSet;
        std::vector<uint256> txOrder;
        std::tie (deserializedLedger, txSet, txOrder) =
            loadLedgerAndTransactionsFromJSON (*app, j);

        if (!parentLedger)
        {
            if (getConfig ().START_LEDGER.empty ())
            {
                require (deserializedLedger->getLedgerSeq () == 3,
                         "Initial ledger isn't seq #3");

                // On first iteration, restart the app's view of the ledger
                // history at the same instant as the parent close time of the
                // first ledger (ledger #3).
                app->startNewLedger (deserializedLedger->getParentCloseTimeNC ());
                parentLedger = lm.getClosedLedger ();
                require (parentLedger->getLedgerSeq () == 2,
                         "Initial ledger parent isn't seq #2");
            }
            else
            {
                // We're being invoked with --ledger, which is where we
                // will start replay from.
                require (app->loadOldLedger (getConfig ().START_LEDGER, false),
                         "Reloading old ledger failed.");
                parentLedger = lm.getClosedLedger ();
            }

            auto const parentSeq = parentLedger->getLedgerSeq ();
            auto seq = j["seq"].asUInt ();
            while (parentSeq + 1 > seq)
            {
                // Fast-scan JSON records until we hit the right one.
                WriteLog (lsINFO, LedgerDump) << "scanning past ledger: "
                                              << seq;
                j = loadJsonRecord (in);
                seq = j["seq"].asUInt ();
                if (parentSeq + 1 <= seq)
                {
                    require (parentSeq + 1 == seq,
                             "Missing ledgers between loaded and replay-start");
                    std::tie (deserializedLedger, txSet, txOrder) =
                        loadLedgerAndTransactionsFromJSON (*app, j);
                }
            }
            gLedgerSeq = parentSeq;
            require(parentLedger->getLedgerSeq () + 1 ==
                    deserializedLedger->getLedgerSeq (),
                    "Mismatched ledger-sequence prefix.");
        }

        Ledger::pointer currentLedger =
            boost::make_shared<Ledger> (true, *parentLedger);
        currentLedger->setCloseTime (deserializedLedger->getCloseTimeNC ());
        currentLedger->setCloseFlags (deserializedLedger->getCloseFlags ());
        currentLedger->setParentHash (deserializedLedger->getParentHash ());

        WriteLog (lsINFO, LedgerDump) << "loading ledger: "
                                      << currentLedger->getLedgerSeq();

        if (ShouldLog (lsTRACE, LedgerDump))
        {
            WriteLog (lsTRACE, LedgerDump) << "expecting next ledger:";
            WriteLog (lsTRACE, LedgerDump) << deserializedLedger->getJson (0);
            WriteLog (lsTRACE, LedgerDump) << "synthetic next ledger:";
            WriteLog (lsTRACE, LedgerDump) << currentLedger->getJson (0);
        }

        gLedgerSeq++;

        // Apply transactions, transitioning from one ledger state to next.
        WriteLog (lsDEBUG, LedgerDump)
            << "Applying set of " << txOrder.size() << " transactions";
        CanonicalTXSet retriableTransactions (txSet->getHash ());
        std::set<uint256> failedTransactions;
        LedgerConsensus::applyTransactions (txSet, currentLedger, currentLedger,
                                            retriableTransactions, failedTransactions,
                                            false, txOrder);

        require (retriableTransactions.empty (), "failed retriable tx set is not empty");
        require (failedTransactions.empty (), "failed tx set is not empty");

        currentLedger->updateSkipList ();
        currentLedger->setClosed ();
        currentLedger->setCloseTime (deserializedLedger->getCloseTimeNC ());

        int asf = currentLedger->peekAccountStateMap ()->flushDirty (
            hotACCOUNT_NODE, currentLedger->getLedgerSeq());
        int tmf = currentLedger->peekTransactionMap ()->flushDirty (
            hotTRANSACTION_NODE, currentLedger->getLedgerSeq());
        nTxs += tmf;

        WriteLog (lsDEBUG, LedgerDump) << "Flushed " << asf << " account "
                                  << "and " << tmf << "transaction nodes";

        // Finalize with the LedgerMaster.
        currentLedger->setAccepted ();
        bool alreadyHadLedger = lm.storeLedger (currentLedger);
        assert (! alreadyHadLedger);
        lm.pushLedger (currentLedger);

        WriteLog (lsTRACE, LedgerDump) << "parent ledger:";
        traceLedgerContents (*parentLedger);
        WriteLog (lsTRACE, LedgerDump) << "current ledger:";
        traceLedgerContents (*currentLedger);

        try
        {
            checkLedgersEqual (*deserializedLedger, *currentLedger);
        }
        catch (...)
        {
            WriteLog (lsINFO, LedgerDump) << "bad ledger:";
            std::cerr << currentLedger->getJson (LEDGER_JSON_FULL);
            throw;
        }
        parentLedger = currentLedger;
    }

    WriteLog (lsINFO, LedgerDump) << "Loaded "
                             << gLedgerSeq << "ledgers, "
                             << nTxs << " transactions from "
                             << filename;
    exit (0);
}
示例#22
0
文件: audiodrv.cpp 项目: woytekm/QSID
void *Audio_ALSA::open (AudioConfig &cfg, const char *)
{
    AudioConfig tmpCfg;
    int mask, wantedFormat, format;
    int rtn;
    int card = -1, dev = 0;
   
    if (_audioHandle != NULL)
    {
        _errorString = "ERROR: Device already in use";
        return NULL;
    }

    if ((rtn = snd_pcm_open_preferred (&_audioHandle, &card, &dev, SND_PCM_OPEN_PLAYBACK)))
    {
        _errorString = "ERROR: Could not open audio device.";
        goto open_error;
    }
    
    // Transfer input parameters to this object.
    // May later be replaced with driver defaults.
    tmpCfg = cfg;

    snd_pcm_channel_params_t pp;
    snd_pcm_channel_setup_t setup;
 
    snd_pcm_channel_info_t pi;
   
    memset (&pi, 0, sizeof (pi));
    pi.channel = SND_PCM_CHANNEL_PLAYBACK;
    if ((rtn = snd_pcm_plugin_info (_audioHandle, &pi)))
    {
        _errorString = "ALSA: snd_pcm_plugin_info failed.";
        goto open_error;
    }
			
    memset(&pp, 0, sizeof (pp));
	
    pp.mode = SND_PCM_MODE_BLOCK;
    pp.channel = SND_PCM_CHANNEL_PLAYBACK;
    pp.start_mode = SND_PCM_START_FULL;
    pp.stop_mode = SND_PCM_STOP_STOP;
				     
    pp.buf.block.frag_size = pi.max_fragment_size;

    pp.buf.block.frags_max = 1;
    pp.buf.block.frags_min = 1;
   
    pp.format.interleave = 1;
    pp.format.rate = tmpCfg.frequency;
    pp.format.voices = tmpCfg.channels;
   
    // Set sample precision and type of encoding.
    if ( tmpCfg.precision == 8 )
    {
        tmpCfg.encoding = AUDIO_UNSIGNED_PCM;
        pp.format.format = SND_PCM_SFMT_U8;
    }
    if ( tmpCfg.precision == 16 )
    {
        tmpCfg.encoding = AUDIO_SIGNED_PCM;
        pp.format.format = SND_PCM_SFMT_S16_LE;
    }

    if ((rtn = snd_pcm_plugin_params (_audioHandle, &pp)) < 0)
    {
        _errorString = "ALSA: snd_pcm_plugin_params failed.";
        goto open_error;
    }
   
    if ((rtn = snd_pcm_plugin_prepare (_audioHandle, SND_PCM_CHANNEL_PLAYBACK)) < 0)
    {
        _errorString = "ALSA: snd_pcm_plugin_prepare failed.";
        goto open_error;
    }
   
    memset (&setup, 0, sizeof (setup));
    setup.channel = SND_PCM_CHANNEL_PLAYBACK;
    if ((rtn = snd_pcm_plugin_setup (_audioHandle, &setup)) < 0)
    {
        _errorString = "ALSA: snd_pcm_plugin_setup failed.";
        goto open_error;
    }

    tmpCfg.bufSize = setup.buf.block.frag_size;
#ifdef HAVE_EXCEPTIONS
    _sampleBuffer = new(std::nothrow) int_least8_t[tmpCfg.bufSize];
#else
    _sampleBuffer = new int_least8_t[tmpCfg.bufSize];
#endif

    if (!_sampleBuffer)
    {
        _errorString = "AUDIO: Unable to allocate memory for sample buffers.";
        goto open_error;
    }

    // Setup internal Config
    _settings = tmpCfg;
    // Update the users settings
    getConfig (cfg);
    return _sampleBuffer;

open_error:
    if (_audioHandle != NULL)
    {
        close ();
    }

    perror ("ALSA");
return NULL;
}
示例#23
0
文件: musicmgr.c 项目: foxbow/mixplay
/**
 * checks the current playlist.
 * If there are more than 10 previous titles, those get pruned.
 * While there are less that 10 next titles, titles will be added.
 *
 * todo: make this also work on other playlists
 */
void plCheck( int del ) {
	int cnt=0;
	mpplaylist *pl=getConfig()->current;
	mpplaylist *buf=pl;

	if( getConfig()->pledit ||
		( getConfig()->plplay && !getConfig()->plmix ) ){
		return;
	}

	if( pl != NULL ) {
		/* truncate stream title history to 20 titles */
		if( getConfig()->playstream ) {
			while( ( pl->next != NULL ) && ( cnt < 20 ) ) {
				pl=pl->next;
				cnt++;
			}

			buf=pl->next;
			pl->next=NULL;
			while( buf != NULL ) {
				pl=buf->next;
				free( buf->title );
				free( buf );
				buf=pl;
			}
			return;
		}

		/* truncate playlist title history to 10 titles */
		while( ( pl->prev != NULL ) && ( cnt < 10 ) ) {
			pl=pl->prev;
			cnt++;
		}

		buf=pl->prev;
		pl->prev=NULL;

		while( buf != NULL ) {
			pl=buf->prev;
			/* unmark title as it leaves the playlist */
			buf->title->flags&=~MP_MARK;
			free( buf );
			buf=pl;
		}

		cnt=0;
		pl=getConfig()->current;
		/* this should always be != NULL */
		if( pl == NULL ) {
			addMessage( 0, "There should not be no playlist!" );
		}
		else {
			/* go to the end of the playlist */
			while( pl->next != NULL ) {
				/* clean up on the way to remove DNP marked or deleted files? */
				if( del != 0 ) {
					if ( ( pl->title->flags | MP_DNP ) || ( !mp3Exists( pl->title ) ) ){
						buf=pl->next;
						if( pl->prev != NULL ) {
							pl->prev->next=pl->next;
						}
						pl->next->prev=pl->prev;
						free(pl);
						pl=buf;
						cnt--;
					}
				}
				else {
					pl=pl->next;
				}
				cnt++;
			}
		}
	}

	/* fill up the playlist with new titles */
	while( cnt < 10 ) {
		if( getConfig()->current == NULL ) {
			getConfig()->current=addNewTitle( NULL, getConfig()->root );
		}
		else {
			addNewTitle( getConfig()->current, getConfig()->root );
		}
		cnt++;
	}
}
示例#24
0
IOReturn
OHareATA::selectIOTimerValue( IOATADevConfig* configRequest, UInt32 unitNumber)
{
// table of default cycle times to use when a device requests a mode
// by number, but doesn't include a cycle time.

static const UInt16 MinPIOCycle[kATAMaxPIOMode + 1] =
				{
					600, 				// Mode 0
					383, 				// Mode 1
					240, 				// Mode 2
					180, 				// Mode 3
					120					// Mode 4
				};


static const UInt16 MinMultiDMACycle[kATAMaxMultiDMAMode + 1] =
				{
					480,				// Mode 0
					150,				// Mode 1
					120					// Mode 2
				};


// table of PIO cycle times and the corresponding binary numbers
// that the config register needs to make that timing.
static const UInt32 PIOCycleValue[kOHarePIOCycleEntries] = 
					{
						0x00000400,					// Hardware maximum		(2070 ns = 'E' + 1110 rec + 960 acc)
						0x00000526,					// Minimum PIO mode 0 	(600 ns = 'E' + 420 rec + 180 acc)	 
						0x00000085,					// Minimum PIO mode 1	(390 ns = 240 rec + 150 acc)	 
						0x00000046,					// Derated PIO Mode 2/3/4	(360 ns = 180 rec + 180 acc)	 
						0x00000045,					// Derated PIO Mode 2/3/4	(330 ns = 180 rec + 150 acc)	 
						0x00000025,					// Derated PIO Mode 2/3/4	(300 ns = 150 rec + 150 acc)	 
						0x00000025,					// Derated PIO mode 2/3/4	(300 ns = 150 rec + 150 acc)	 
						0x00000025,					// Minimum PIO mode 2 		(300 ns = 150 rec + 150 acc)	 
						0x00000025,					// Derated PIO Mode 3/4 	(300 ns = 150 rec + 150 acc)		 
						0x00000025,					// Minimum PIO mode 3		(300 ns = 150 rec + 150 acc)	 
						0x00000025					// Minimum PIO mode 4		(300 ns = 150 rec + 150 acc)	 
 					};


static const UInt16 PIOCycleTime[ kOHarePIOCycleEntries ]=
					{
						2070,						// Hardware maximum			(0)
						600,						// Minimum PIO mode 0 		(1)	 
						383,						// Minimum PIO mode 1		(2)	 
						360,						// Derated PIO Mode 2/3/4	(3) 	 
						330,						// Derated PIO Mode 2/3/4	(4) 	 
						300,						// Derated PIO Mode 2/3/4	(5) 	 
						270,						// Derated PIO mode 2/3/4	(6)	 
						240,						// Minimum PIO mode 2 		(7)	 
						239,						// Derated PIO Mode 3/4 	(8)		 
						180,						// Minimum PIO mode 3		(9)	 
						120,						// Minimum PIO mode 4		(10)	 
					};


// table of DMA cycle times and the corresponding binary value to reach that number.
static const UInt32 MultiDMACycleValue[kOHareMultiDMACycleEntries] =
				{
					0x00000000, 				// Hardware maximum     (1950=  990rec+960acc)	 
					0x00074000, 				// Minimum Multi mode 0  (480=  240rec+240acc)	 
					0x00053000, 				// Derated mode 1 or 2   (360=  180rec+180acc)	 
					0x00242000, 				// Derated mode 1 or 2   (270=H+135rec+135acc)	 
					0x00032000, 				// Derated mode 1 or 2   (240=  120rec+120acc)	 
					0x00231800, 				// Derated mode 1 or 2   (210=H+105rec+105acc)	 
					0x00021800, 				// Derated mode 1 or 2   (180=   90rec+90acc)	 
					0x00221000, 				// Minimum Multi mode 1  (150=H+75rec+75acc)	 
					0x00211000	 				// Minimum Multi mode 2  (120=H+45rec+75acc)(rd) (150=H+75rec+75acc)(wr)
				}; 

static const UInt16 MultiDMACycleTime[kOHareMultiDMACycleEntries] =
				{
					1950, 						// Hardware maximum     	(0) 
					480, 						// Minimum Multi mode 0  (1)	 
					360, 						// Derated mode 1 or 2   (2)	 
					270, 						// Derated mode 1 or 2   (3)	 
					240, 						// Derated mode 1 or 2   (4)	 
					210, 						// Derated mode 1 or 2   (5)	 
					180, 						// Derated mode 1 or 2   (6)	 
					150, 						// Minimum Multi mode 1  (7)	 
					120 						// Minimum Multi mode 2  (8)	 
				};


	UInt32 pioConfigBits = PIOCycleValue[0];

	// the theory is simple, just examine the requested mode and cycle time, find the 
	// entry in the table which is closest, but NOT faster than the requested cycle time.

	// convert the bit maps into numbers
	UInt32 pioModeNumber = bitSigToNumeric( configRequest->getPIOMode());

	// check for out of range values.
	if( pioModeNumber > kATAMaxPIOMode )
	{
		DLOG("OHareATA pio mode out of range\n");
		return kATAModeNotSupported;	
	}
	
	// use a default cycle time if the device didn't report a time
	// to use.
	UInt32 pioCycleTime = configRequest->getPIOCycleTime();
	if( pioCycleTime < MinPIOCycle[ pioModeNumber ] )
	{
		pioCycleTime = MinPIOCycle[ pioModeNumber ];
	}


	// loop until a the hardware cycle time is longer than the 
	// or equal to the requested cycle time
	for( int i = kOHarePIOCycleEntries - 1; i >= 0; i--)
	{
	
		if( pioCycleTime <= PIOCycleTime[ i ] )
		{
			// found the fastest time which is not greater than
			// the requested time.
			pioConfigBits = PIOCycleValue[i];
			break;
		}
	}
	

	// now do the same for DMA modes.
	UInt32 dmaConfigBits = MultiDMACycleValue[0];
	UInt32 dmaModeNumber = bitSigToNumeric( configRequest->getDMAMode() );

	// if the device requested no DMA mode, then just set the timer to mode 0
	if( dmaModeNumber > kATAMaxMultiDMAMode )
	{
		dmaModeNumber = 0;	
	}

	UInt32 dmaCycleTime = configRequest->getDMACycleTime();
	if( dmaCycleTime < MinMultiDMACycle[ dmaModeNumber ] )
	{
		dmaCycleTime = MinMultiDMACycle[ dmaModeNumber ];
	}


	// loop until a the hardware cycle time is longer than the 
	// or equal to the requested cycle time
	for( int i = kOHareMultiDMACycleEntries - 1; i >= 0; i--)
	{
	
		if( dmaCycleTime <= MultiDMACycleTime[ i ] )
		{
			// found the fastest time which is not greater than
			// the requested time.
			dmaConfigBits = MultiDMACycleValue[i];
			break;
		}
	}


	// now combine the bits forming the configuration and put them
	// into the timing structure along with the mode and cycle time
	
	busTimings[unitNumber].cycleRegValue = dmaConfigBits | pioConfigBits;
	busTimings[unitNumber].ataPIOSpeedMode = configRequest->getPIOMode();
	busTimings[unitNumber].ataPIOCycleTime = pioCycleTime;
	busTimings[unitNumber].ataMultiDMASpeed = configRequest->getDMAMode();
	busTimings[unitNumber].ataMultiCycleTime = dmaCycleTime;

	DLOG("OHareATA PIO mode %x at %ld ns selected for device: %x\n", (int)pioModeNumber, pioCycleTime, (int)unitNumber);
	DLOG("OHareATA DMA mode %x at %ld ns selected for device: %x\n", (int)dmaModeNumber, dmaCycleTime, (int)unitNumber);

	// stuff the values back into the request structure and return result
	return getConfig( configRequest, unitNumber);

}
示例#25
0
文件: musicmgr.c 项目: foxbow/mixplay
/**
 * fills the global searchresult structure with the results of the given search.
 * Returns the number of found titles.
 * pat - pattern to search for
 * global - include DNP
 * fill - fill artist and album results
 */
int search( const char *pat, const mpcmd range, const int global ) {
	mptitle *root=getConfig()->root;
	mptitle *runner=root;
	searchresults *res=getConfig()->found;
	unsigned int i=0;
	int found=0;
	unsigned int cnt=0;
	/* free buffer playlist, the arrays will not get lost due to the realloc later */
	res->titles=wipePlaylist(res->titles);
	res->tnum=0;
	res->anum=0;
	res->lnum=0;

	do {
		activity("searching");
		found=0;
		if( global || !(runner->flags & MP_DNP) ) {
			/* check for searchrange and pattern */
			if( MPC_ISTITLE(range) &&
					isMatch( runner->title, pat, MPC_ISFUZZY(range) ) ) {
				found=1;
			}
			if( MPC_ISDISPLAY( range ) &&
					isMatch( runner->display, pat, MPC_ISFUZZY(range) ) ) {
				found=1;
			}
			if( MPC_ISARTIST(range) &&
					isMatch( runner->artist, pat, MPC_ISFUZZY(range) ) ) {
				found=1;
			}
			if( MPC_ISALBUM( range ) &&
					isMatch( runner->album, pat, MPC_ISFUZZY(range) ) ) {
				found=1;
			}
			/* todo: genre and path are missing here */
			if( found ) {
				/* check for new artist */
				for( i=0; (i<res->anum) && strcmp( res->artists[i], runner->artist ); i++ );
				if( i == res->anum ) {
					res->anum++;
					res->artists=(char**)frealloc( res->artists, res->anum*sizeof(char*) );
					res->artists[i]=runner->artist;
				}

				for( i=0; (i<res->lnum) && strcmp( res->albums[i], runner->album ); i++ );
				if( i == res->lnum ) {
					res->lnum++;
					res->albums=(char**)frealloc( res->albums, res->lnum*sizeof(char*) );
					res->albums[i]=runner->album;
					res->albart=(char**)frealloc( res->albart, res->lnum*sizeof(char*) );
					res->albart[i]=runner->artist;
				}
				else if( !strcmp( res->albart[i], ARTIST_SAMPLER ) &&
						strcmp( res->albart[i], runner->artist ) ){
					addMessage(1, "%s is considered a sampler (%s <> %s).", runner->album, runner->artist, res->albart[i] );
					res->albart[i]=ARTIST_SAMPLER;
				}
			}

			/* add titles too */
			if( ( found != 0 ) && ( cnt++ < MAXSEARCH ) ) {
				res->titles=appendToPL( runner, res->titles, 0 );
				res->tnum++;
			}
		}
		runner=runner->next;
	} while( runner != root );

	res->send=-1;

	return (cnt>MAXSEARCH)?-1:cnt;
}
示例#26
0
const ConnectionString ShardLocal::getConnString() const {
    auto replCoord = repl::getGlobalReplicationCoordinator();
    return replCoord->getConfig().getConnectionString();
}
示例#27
0
/* expected hook, this is where custom stuff happens */
PAM_EXTERN int pam_sm_authenticate(pam_handle_t* pamh, int flags, int argc, const char **argv) {
    int ret = 0;

    const char *pUsername = NULL;
    const char *pAccountId = NULL;
    const char *pOperation = NULL;
    const char *pSecretKey = NULL;
    const char *pAppId = NULL;
    const char *pOperationId = NULL;
    const char *pAccounts = NULL;
    const char *pConfig = NULL;
    const char *pOtp = NULL;
    const char *pHost = NULL;
    const char *pTimeout = NULL;
    char *pDefaultOption = NULL;
    char *buffer;
    int timeout = 2;
    int default_option = PAM_SUCCESS;
    int res =  PAM_SUCCESS;
    char *otp = NULL;


    struct pam_message msg[1],*pmsg[1];
    struct pam_response *resp;

    // setting up conversation call prompting for one-time code
    pmsg[0] = &msg[0] ;
    msg[0].msg_style = PAM_PROMPT_ECHO_ON ;
    msg[0].msg = "One-time code: " ;
    resp = NULL ;


    if (pam_get_user(pamh, &pUsername, NULL) != PAM_SUCCESS) {
        return PAM_AUTH_ERR;
    }

    pAccounts = getArg("accounts", argc, argv);
    if (!pAccounts) {
        pAccounts = DEFAULT_LATCH_ACCOUNTS_FILE;
    }

    pAccountId = getAccountId(pUsername, pAccounts);
    if (pAccountId == NULL) {
        return PAM_SUCCESS;
    }

    pConfig = getArg("config", argc, argv);
    if (!pConfig) {
        pConfig = DEFAULT_LATCH_CONFIG_FILE;
    }

    pOperation = getArg("operation", argc, argv);
    if (!pOperation) {
        pOperationId = NULL;
    } else {
        pOperationId = getConfig(OPERATION_ID_LENGTH, pOperation, pConfig);
        if (pOperationId == NULL) {
            send_syslog_alert("PAM", "Latch-auth-pam error: Failed to find operation");
            perror("Failed to find operation");
            return PAM_SUCCESS;
        }
    }

    pOtp = getArg("otp", argc, argv);
    if (!pOtp) {
        pOtp = "no";
    }

    pDefaultOption = (char *)getConfig(DEFAULT_OPTION_MAX_LENGTH, "action", pConfig);
    if (pDefaultOption == NULL) {
        pDefaultOption = malloc(4 + 1);
        memset(pDefaultOption, 0, 4 + 1);
        strncpy(pDefaultOption, "open", 4);
    } else if (strcmp(pDefaultOption,"open") != 0 && strcmp(pDefaultOption,"close") != 0){
        pDefaultOption = realloc(pDefaultOption, 4 + 1);
        memset(pDefaultOption, 0, 4 + 1);
        strncpy(pDefaultOption, "open", 4);
    }

    if (strcmp(pDefaultOption,"open") == 0) {
        default_option = PAM_SUCCESS;
    } else {
        default_option = PAM_AUTH_ERR;
    }
    free(pDefaultOption);

    pAppId = getConfig(APP_ID_LENGTH, "app_id", pConfig);
    pSecretKey = getConfig(SECRET_KEY_LENGTH, "secret_key", pConfig);

    if(pAppId == NULL || pSecretKey == NULL || strcmp(pAppId, "") == 0 || strcmp(pSecretKey, "") == 0){
        send_syslog_alert("PAM", "Latch-auth-pam error: Failed to read \"latch.conf\"");
        perror("Failed to read \"latch.conf\"");
        free((char*)pAccountId);
        free((char*)pOperationId);
        return PAM_SUCCESS;
    }

    pHost = getConfig(MAX_SIZE, "latch_host", pConfig);
    if(pHost == NULL) {
        pHost = malloc(LATCH_API_HOST_LENGTH + 1);
        memset((char*)pHost, 0, LATCH_API_HOST_LENGTH + 1);
        strncpy((char*)pHost, LATCH_API_HOST, LATCH_API_HOST_LENGTH);
    }

    pTimeout = getConfig(TIMEOUT_MAX_LENGTH, "timeout", pConfig);
    if(pTimeout == NULL || ((timeout = atoi(pTimeout)) < TIMEOUT_MIN) || timeout > TIMEOUT_MAX) {
        timeout = 2;
    }
    free((char*)pTimeout);

    if (drop_privileges(0)) {
        send_syslog_alert("PAM", "Latch-auth-pam error: Couldn't drop privileges");
    }

    init(pAppId, pSecretKey);
    setHost(pHost);
    setTimeout(timeout);

    if (pOperationId != NULL) {
        buffer = operationStatus(pAccountId, pOperationId);
    } else {
        buffer = status(pAccountId);
    }
    free((char*)pAppId);
    free((char*)pSecretKey);
    free((char*)pAccountId);
    free((char*)pOperationId);
    free((char*)pHost);

    if (restore_privileges()) {
        send_syslog_alert("PAM", "Latch-auth-pam error: Couldn't restore privileges");
    }

    if(buffer == NULL || strcmp(buffer,"") == 0){
        free(buffer);
        return default_option;
    }

    if (strstr(buffer, "\"status\":\"off\"") != NULL){
        fprintf (stderr, "AUTH-PAM: latch locked\n");
        send_syslog_alert("PAM", "Latch-auth-pam warning: Someone tried to access. Latch locked");
        res = PAM_AUTH_ERR;

    }else if (strstr(buffer, "\"status\":\"on\"") != NULL) {

        if(strncmp(pOtp, "yes", 3) == 0){

            char *pch;
            if((pch = strstr(buffer, "\"two_factor\"")) != NULL){
                char code[OTP_LENGTH];
                memset(code, 0, OTP_LENGTH);

                strncpy (code, pch + strlen("\"two_factor\":{\"token\":\""), OTP_LENGTH);

                otp = get_response(pamh, "One-time password", 1);

                // comparing user input with known code
                if(strncmp(code, otp, OTP_LENGTH) != 0  || strlen(otp) != OTP_LENGTH){
                    send_syslog_alert("PAM", "Latch-auth-pam warning: Someone tried to access. Bad OTP");
                    res = PAM_AUTH_ERR;
                } else {
                    res = PAM_SUCCESS;
                }
            }

        }else{
            res = PAM_SUCCESS;
        }
    }

    free(buffer);
    return res;
}
示例#28
0
 ~RPCDoorImp ()
 {
     WriteLog (lsINFO, RPCDoor) <<
         "RPC port: " << getConfig ().getRpcAddress() <<
         " allow remote: " << getConfig ().RPC_ALLOW_REMOTE;
 }
示例#29
0
void Channel::_testFormats( float applyZoom )
{
    //----- setup constant data
    const eq::Images& images = _frame.getImages();
    eq::Image*        image  = images[ 0 ];
    LBASSERT( image );

    Config* config = static_cast< Config* >( getConfig( ));
    const eq::PixelViewport& pvp = getPixelViewport();
    const eq::Vector2i offset( pvp.x, pvp.y );
    const eq::Zoom zoom( applyZoom, applyZoom );

    lunchbox::Clock clock;
    eq::Window::ObjectManager* glObjects = getObjectManager();

    //----- test all default format/type combinations
    ConfigEvent event = _createConfigEvent();
    glGetError();
    for( uint32_t i=0; _enums[i].internalFormatString; ++i )
    {
        const uint32_t internalFormat = _enums[i].internalFormat;
        image->flush();
        image->setInternalFormat( eq::Frame::BUFFER_COLOR, internalFormat );
        image->setQuality( eq::Frame::BUFFER_COLOR, 0.f );
        image->setAlphaUsage( false );

        const GLEWContext* glewContext = glewGetContext();
        std::vector< uint32_t > names;
        image->findTransferers( eq::Frame::BUFFER_COLOR, glewContext, names );

        for( std::vector< uint32_t >::const_iterator j = names.begin();
             j != names.end(); ++j )
        {
            _draw( 0 );

            // setup
            event.formatType[31] = '\0';
            event.data.type = ConfigEvent::READBACK;

            image->allocDownloader( eq::Frame::BUFFER_COLOR, *j, glewContext );
            image->setPixelViewport( pvp );

            const uint32_t outputToken = 
                image->getExternalFormat( eq::Frame::BUFFER_COLOR );
            snprintf( event.formatType, 32, "%s/%x/%x", 
                _enums[i].internalFormatString, outputToken, *j );


            // read
            glFinish();
            size_t nLoops = 0;
            clock.reset();
            while( clock.getTime64() < 100 /*ms*/ )
            {
                image->startReadback( eq::Frame::BUFFER_COLOR, pvp, zoom,
                                      glObjects );
                image->finishReadback( zoom, glObjects->glewGetContext( ));
                ++nLoops;
            }
            glFinish();
            event.msec = clock.getTimef() / float( nLoops );

            const eq::PixelData& pixels =
                image->getPixelData( eq::Frame::BUFFER_COLOR );
            event.area.x() = pixels.pvp.w;             
            event.area.y() = pixels.pvp.h;
            event.dataSizeGPU = pixels.pvp.getArea() * _enums[i].pixelSize;
            event.dataSizeCPU = 
            image->getPixelDataSize( eq::Frame::BUFFER_COLOR );

            GLenum error = glGetError();
            if( error != GL_NO_ERROR )
                event.msec = -static_cast<float>( error );
            config->sendEvent( event );

            // write
            eq::Compositor::ImageOp op;
            op.channel = this;
            op.buffers = eq::Frame::BUFFER_COLOR;
            op.offset = offset;
            op.zoom = zoom;

            event.data.type = ConfigEvent::ASSEMBLE;
            event.dataSizeCPU = 
                image->getPixelDataSize( eq::Frame::BUFFER_COLOR );

            clock.reset();
            eq::Compositor::assembleImage( image, op );
            event.msec = clock.getTimef();

            const eq::PixelData& pixelA =
                image->getPixelData( eq::Frame::BUFFER_COLOR );
            event.area.x() = pixelA.pvp.w; 
            event.area.y() = pixelA.pvp.h;
            event.dataSizeGPU =
                image->getPixelDataSize( eq::Frame::BUFFER_COLOR );

            error = glGetError();
            
            if( error != GL_NO_ERROR )
                event.msec = -static_cast<float>( error );
            config->sendEvent( event );
        }
    }
}
示例#30
0
void ClientWorker2::performRecv(const std::shared_ptr<Client>& client) {
  std::string str;
  client->sync_recv(str, getConfig()->pickRecvSize());
}