Esempio n. 1
0
int main()
{
	int n;
	int t;
	cin>>t;
	while(t--)
	{
	
	scanf("%d",&n);
int x; int k=0;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
b[i]=a[i];
}
mergesort(a,0,n-1);
for(int i=0;i<n;i++)
{
	int y = bin(a,b[i],1,n);
	
}
cout<<endl;
}
return 0;
}
Esempio n. 2
0
BinaryNode *SSH2Channel::readBinary(ExceptionSink *xsink, int stream_id, int timeout_ms) {
   AutoLocker al(parent->m);
   if (check_open(xsink))
      return 0;

   SimpleRefHolder<BinaryNode> bin(new BinaryNode);

   BlockingHelper bh(parent);

   qore_offset_t rc;
   bool first = true;
   do {
     loop0:
      char buffer[QSSH2_BUFSIZE];
      rc = libssh2_channel_read_ex(channel, stream_id, buffer, QSSH2_BUFSIZE);
      //printd(5, "SSH2Channel::readBinary() rc=%ld (EAGAIN=%d)\n", rc, LIBSSH2_ERROR_EAGAIN);

      if (rc > 0) {
	 bin->append(buffer, rc);
      }
      else if (rc == LIBSSH2_ERROR_EAGAIN && !bin->size() && first) {
	 first = false;
	 if ((rc = parent->waitSocketUnlocked(xsink, SSH2CHANNEL_TIMEOUT, "SSH2CHANNEL-READBINARY-ERROR", "SSH2Channel::readBinary", timeout_ms)))
	    return 0;
	 goto loop0;
      }
   }
   while (rc > 0);

   if (rc < 0 && rc != LIBSSH2_ERROR_EAGAIN) {
      parent->doSessionErrUnlocked(xsink);
      return 0;
   }

   return bin.release();
}
Esempio n. 3
0
void STFT::inverse(float * dst){
	//printf("STFT::inverse(float *)\n");
	if(MAG_FREQ == mSpctFormat){
		// TODO:
		for(uint32_t i=1; i<numBins()-1; ++i) bin(i)[1] = mPhases[i];
	}	
	
	DFT::inverse(0);	// result goes into bufPos()
	
	// undo zero-phase windowing rotation?
	if(mRotateForward) mem::rotateHalf(bufPos(), sizeWin());

	// apply secondary window to smooth ends?
	if(mWindowInverse){
		arr::mulBartlett(bufPos(), sizeWin());
	}

	if(overlapping()){	//inverse windows overlap?
	
		// scale inverse so overlap-add is normalized
		//slice(mBuf, sizeWin()) *= mInvWinMul;
		for(unsigned i=0; i<sizeWin(); ++i){
			bufPos()[i] *= mInvWinMul;
		}
	
		// shift old output left while adding new output
		arr::add(mBufInv, bufPos(), mBufInv + sizeHop(), sizeWin() - sizeHop());
	}

	// copy remaining non-overlapped portion of new output
	uint32_t sizeOverlap = sizeWin() - sizeHop();
	mem::deepCopy(mBufInv + sizeOverlap, bufPos() + sizeOverlap, sizeHop());

	// copy output if external buffer provided
	if(dst) mem::deepCopy(dst, mBufInv, sizeWin());	
}
			void gatherMaster(std::vector<MessageT> &msgBuf) {
				int sendCount = 0;
				int *recvCount = new int[numPeers];
				int *recvOffset = new int[numPeers];

				/* Get the sizes of messages from each worker */
				MPI_Gather(&sendCount, 1, MPI_INT, recvCount, 1, MPI_INT, MASTER_RANK, MPI_COMM_WORLD);
				recvOffset[0] = 0;
				for (int i = 1; i < numPeers; ++i) {
					recvOffset[i] = recvOffset[i - 1] + recvCount[i - 1];
				}

				/* Get messages from each worker */
				int recvTotal = recvOffset[numPeers - 1] + recvCount[numPeers - 1];
				char *recvBuffer = new char[recvTotal];
				MPI_Gatherv(NULL, 0, MPI_CHAR, recvBuffer, recvCount, recvOffset, MPI_CHAR, MASTER_RANK, MPI_COMM_WORLD);

				/* Decode the messages */
				ibinstream bin(recvBuffer, recvTotal);
				for (int i = 0; i < numPeers; ++i) {
					if (i != me) {
						bin >> msgBuf[i];
					}
				}
Esempio n. 5
0
yarp::os::impl::HttpTwoWayStream::HttpTwoWayStream(TwoWayStream *delegate, const char *txt,
                                   const char *prefix,
                                   yarp::os::Property& prop) :
        delegate(delegate) {

    data = false;
    filterData = false;
    chunked = false;
    String s(txt);
    String sData = "";
    Property& p = prop;
    //p.fromQuery(txt);
    format = p.check("format",Value("html")).asString().c_str();
    outer = p.check("outer",Value("auto")).asString().c_str();
    bool admin = p.check("admin");
    if (p.check("cmd")) {
        s = p.check("cmd",Value("")).asString().c_str();
    } else if (p.check("data")) {
        s = p.check("data",Value("")).asString().c_str();
        s += " ";
        String sFixed = "";
        String var = "";
        bool arg = false;
        for (unsigned int i=0; i<s.length(); i++) {
            char ch = s[i];
            if (arg) {
                if ((ch>='A'&&ch<='Z')||
                    (ch>='a'&&ch<='z')||
                    (ch>='0'&&ch<='9')||
                    (ch=='_')) {
                    var += ch;
                } else {
                    arg = false;
                    sFixed+=p.check(var.c_str(),Value("")).toString().c_str();
                    if (i!=s.length()-1) {
                        sFixed += ch; // omit padding
                    }
                    var = "";
                }
            } else {
                if (ch=='$') {
                    arg = true;
                } else {
                    if (i!=s.length()-1) {
                        sFixed += ch; // omit padding
                    }
                }
            }
        }


        Bottle bin(sFixed.c_str());
        sData = sFixed;
        if (admin) {
            s = String("a\n") + sFixed;
        } else {
            s = String("d\n") + sFixed;
        }
    }


    String from = prefix;
    from += "<input type=text name=data value=\"";
    from += quoteFree(sData.c_str());

    from += "\"><input type=submit value=\"send data\"></form></p>\n";
    from += "<pre>\n";

    bool classic = false;
    // support old-style messages
    if (s.length()<=1) classic = true;
    if (s.length()>1) {
        if (s[0]=='?' || s[1]=='?') {
            classic = true;
        }
        if (s[0]=='d' && s[1]=='\n') {
            classic = true;
        }
    }
    if (s.length()>=4) {
        if (s[0]=='f'&&s[1]=='o'&&s[2]=='r'&&s[3]=='m') {
            classic = true;
        }
        if (s[0]=='d'&&s[1]=='a'&&s[2]=='t'&&s[3]=='a') {
            classic = true;
        }
        if (s[0]=='f'&&s[1]=='a'&&s[2]=='v'&&s[3]=='i') {
            // kill favicon.ico, sorry
            classic = true;
        }
    }
    //printf("S is %s, classic? %d\n", s.c_str(), classic);

    if (classic) {
        String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n";
        chunked = false;
        if (s[0]=='r') {
            header += "Transfer-Encoding: chunked\r\n";
            chunked = true;
        }
        header += "\r\n";
        int N = 2*1024;
        String body = from;
        if (chunked) {
            body += "Reading data from port...\n";
            header += NetType::toHexString(body.length()+N);
            header += "\r\n";
        }

        Bytes b1((char*)header.c_str(),header.length());
        delegate->getOutputStream().write(b1);

        if (chunked) {
            // chrome etc won't render until enough chars are received.
            for (int i=0; i<N; i++) {
                delegate->getOutputStream().write(' ');
            }
        }

        Bytes b2((char*)body.c_str(),body.length());
        delegate->getOutputStream().write(b2);
        delegate->getOutputStream().write('\r');
        delegate->getOutputStream().write('\n');
        delegate->getOutputStream().flush();

        if (s=="") {
            s = "*";
        }
        if (chunked) {
            filterData = true;
        }
        for (unsigned int i=0; i<s.length(); i++) {
            if (s[i]==',') {
                s[i] = '\n';
            }
            if (s[i]=='+') {
                s[i] = ' ';
            }
        }
        if (chunked) {
            sis.add("r\n");
        } else {
            sis.add(s);
            sis.add("\nq\n");
        }

    } else {
        chunked = true;
        if (admin) {
            sis.add("a\n");
        } else {
            sis.add("d\n");
        }
        for (int i=0; i<(int)s.length(); i++) {
            if (s[i]=='/') {
                s[i] = ' ';
            }
            if (s[i]=='?') {
                s = s.substr(0,i);
                break;
            }
        }
        sis.add(s);
        sis.add(" ");
        sis.add(p.toString());
        sis.add("\n");
    }
}
Esempio n. 6
0
int DecodeMultiColorSpriteGraphics (GifFileType *SpriteGif)
{
    int wwidth = 12; // wanted width
    // make sure we have the correct number of pixels
    if ((SpriteGif->SWidth % wwidth != 0) && SpriteGif->SHeight != 21)
    {
        fprintf (stderr, "Error: Incorrect dimensions: %dx%d\n", SpriteGif->SWidth, SpriteGif->SHeight);
        return 1;
    }

    // iterate over the raster bits
    unsigned char *raster = SpriteGif->SavedImages->RasterBits;

    int wscale = SpriteGif->SWidth / wwidth;
    int i, j, m = 0, row = 0; // iterators
    int colors[4] = { -1, -1, -1, -1 }; // palette values to store
    int cur, k, l; // current color, array indices
    for (m = 0; m < wscale; m++)
    {
        if (wscale > 1)
        {
            printf ("\n; sprite %x\n", m % 21);
        }
        for (i = 0; i < 252; i += 12)
        {
            printf ("\n\n\t; row %x", row++);
            for (j = 0; j < 12; j++)
            {
                if (j % 4 == 0) fputs ("\n\t.byte %", stdout);
                int index = (i * wscale + m * 12) + j;
                // world_is_a_fuck(wscale,index,12,21);
                // fprintf(stderr,"index %d\n",index);
                cur = raster[index];
                k = in_array (colors, cur);
                if (k == -1)
                {
                    l = in_array (colors, -1);
                    if (l == -1)
                    {
                        fputs ("ERROR: more than 4 colors in the palette\n", stderr);
                        fputs ("Color cache: { ", stderr);
                        int z;
                        for (z = 0; z < 4; z++)
                        {
                            fprintf (stderr, "%d, ", colors[z]);
                        }
                        fputs ("}\n", stderr);
                        return 1;
                    }
                    colors[l] = cur;
                    printf (bin (l), stdout);
                }
                else
                {
                    printf (bin (k), stdout);
                }
            }
        }

        fputs ("\n\t; padding byte\n\t.byte $00\n", stdout);
    }
    fputs ("\n", stdout);

    return 0;
}
Esempio n. 7
0
int index(int l, int r) {
    int b = lg2(r - l);
    return cmp(rmq[b][l], rmq[b][r - bin(b)]);
}
Esempio n. 8
0
MalieExec::MalieExec(char *lpFileName)
{
	execstream bin(lpFileName);
	DWORD dwCnt = bin.readdw();
	for (;dwCnt;--dwCnt)//skip var
	{
		DWORD szLen = bin.readdw();
		bin.seek(szLen&0x7FFFFFFF,FILE_CURRENT);
		GetNext(&bin);
		bin.seek(sizeof(DWORD)*4,FILE_CURRENT);	
	}
	//至于这里为啥要跳过一个DW我也忘了、最初的解析里面没有写
	//  [7/20/2013 Azure]
	bin.seek(sizeof(DWORD),FILE_CURRENT);//skip 0x3130 dwCnt = 0x5F4

	//////////////////////////////////////////////////////////////////////////
	// Function parse block
	dwCnt = bin.readdw();
//	freopen("functionList.txt","wt,ccs=UNICODE",stdout);
	for (;dwCnt;--dwCnt)//skip function
	{
		DWORD szLen;char temp[1000];DWORD ch[3];
		VM_FUNCTION func;
		szLen = bin.readdw();
		bin.read(temp,(szLen&0x7FFFFFFF));
		bin.read(ch,3*sizeof(DWORD));
		func.dwID = ch[0];
		func.wstrName = (WCHAR *)temp;
		func.dwVMCodeOffset = ch[2];
		func.dwReserved0 = ch[1];
		funcList[func.wstrName] = func;
		vecFuncList.push_back(func);
//		wprintf(L"%d,%ls,%d,0x%.4X\n",ch[0],temp,ch[1],ch[2]);
	}

	fprintf(stderr,"VM_FUNCTION:%d\n",funcList.size());

	//////////////////////////////////////////////////////////////////////////
	// Label parse block
	dwCnt = bin.readdw();
	for (;dwCnt;--dwCnt)//skip label
	{
		DWORD szLen;char temp[1000];DWORD ch;
		MALIE_LABEL label;
		szLen = bin.readdw();
		bin.read(temp,(szLen&0x7FFFFFFF));
		ch = bin.readdw();
		label.wstrName = (WCHAR *)temp;
		label.dwVMCodeOffset = ch;
		labelList[label.wstrName] = label;
	}

	fprintf(stderr,"LABEL:%d\n",labelList.size());

	//////////////////////////////////////////////////////////////////////////
	// VM_DATA : just read to new area

	szVM_DATA = bin.readdw();
	//dump original scene
	pVM_DATA = new unsigned char[szVM_DATA];
	bin.read(pVM_DATA,szVM_DATA);

	fprintf(stderr,"VM_DATA size: %8X\n",szVM_DATA);

	//////////////////////////////////////////////////////////////////////////
	// VM_CODE : just read to new area
	szVM_CODE = bin.readdw();
	pVM_CODE = new unsigned char [szVM_CODE];
	bin.read(pVM_CODE,szVM_CODE);

	fprintf(stderr,"VM_CODE size: %8X\n",szVM_CODE);

//	fprintf(stderr,"system_onInit:0x%X\n",func_List.find(L"system_onInit")->second.dwVMCodeOffset);
	//////////////////////////////////////////////////////////////////////////
	// strTable

	DWORD unkSize = bin.readdw();
	if (unkSize*8 >bin.GetFileSize()-bin.seek(0,FILE_CURRENT))
	{
		szStrTable = unkSize;//ziped crypted
		pStrTable = new unsigned char[unkSize];
		bin.read(pStrTable,szStrTable);

		cntStrIndex = bin.readdw();
		vStrIndex.reserve(cntStrIndex/2+1);
		DWORD offset = bin.readdw();
		for (size_t idx = 1;idx<cntStrIndex;++idx)
		{
			DWORD tmpOffset = bin.readdw();
			vStrIndex.push_back(STRING_INFO(offset,tmpOffset-offset));
			offset = tmpOffset;
		}
	}
	else
	{
		cntStrIndex = unkSize;//normal
		vStrIndex.resize(cntStrIndex);
		bin.read(&vStrIndex[0],cntStrIndex*sizeof(STRING_INFO));

		szStrTable = bin.readdw();
		pStrTable = new unsigned char[szStrTable];
		bin.read(pStrTable,szStrTable);		
	}
}
Esempio n. 9
0
 variant json::from_file( const fc::path& p, parse_type ptype, uint32_t max_depth )
 {
    fc::istream_ptr in( new fc::ifstream( p ) );
    fc::buffered_istream bin( in );
    return from_stream( bin, ptype, max_depth );
 }
Esempio n. 10
0
void buildtupledata(TString code)//(TString collision = "PbPbBJet", TString jetalgo = "akVs4PFJetAnalyzer")
{
  if (!dt(code)) { cout<<"Not data: "<<code<<", exiting..."<<endl; return;}
  
  bool PbPb = isPbPb(code);
  TString sample = getSample(code);
  jettree = getjettree(code);
  subTag = subTagging(code);

  Init(PbPb, sample);

  TString outputfilenamedj = outputfolder+"/"+code+"_djt.root";
  TString outputfilenameinc = outputfolder+"/"+code+"_inc.root";
  TString outputfilenameevt = outputfolder+"/"+code+"_evt.root";

  TString djvars = TString("run:lumi:event:prew:triggermatched:bin:vz:hiHF:hltCSV60:hltCSV80:hltCaloJet40:hltCaloJet60:hltCaloJet80:hltPFJet60:hltPFJet80:dijet:")+
      "hltCalo60jtpt:hltCalo60jtphi:hltCalo60jteta:hltCalo80jtpt:hltCalo80jtphi:hltCalo80jteta:hltCSV60jtpt:hltCSV60jtphi:hltCSV60jteta:hltCSV80jtpt:hltCSV80jtphi:hltCSV80jteta:"+
      "rawpt1:jtpt1:jtphi1:jteta1:discr_csvV1_1:svtxm1:discr_prob1:svtxdls1:svtxpt1:svtxntrk1:nsvtx1:nselIPtrk1:"+
      "rawpt2:jtpt2:jtphi2:jteta2:discr_csvV1_2:svtxm2:discr_prob2:svtxdls2:svtxpt2:svtxntrk2:nsvtx2:nselIPtrk2:dphi21:"+
      "rawpt3:jtpt3:jtphi3:jteta3:discr_csvV1_3:svtxm3:discr_prob3:svtxdls3:svtxpt3:svtxntrk3:nsvtx3:nselIPtrk3:dphi31:dphi32:"+
      "SLord:rawptSL:jtptSL:jtphiSL:jtetaSL:discr_csvV1_SL:svtxmSL:discr_probSL:svtxdlsSL:svtxptSL:svtxntrkSL:nsvtxSL:nselIPtrkSL:dphiSL1";





  for (auto w:weights) cout<<w<<"\t";
  cout<<endl;

  int totentries = 0;

  //now fill histos
  TFile *foutdj = new TFile(outputfilenamedj,"recreate");
  TNtuple *ntdj = new TNtuple("nt","ntdj",djvars);

  TFile *foutinc = new TFile(outputfilenameinc,"recreate");
  TNtuple *ntinc = new TNtuple("nt","ntinc","prew:goodevent:bin:vz:hiHF:hltCSV60:hltCSV80:hltCaloJet40:hltCaloJet60:hltCaloJet80:hltPFJet60:hltPFJet80:rawpt:jtpt:jtphi:jteta:discr_csvV1:svtxm:discr_prob:svtxdls:svtxpt:svtxntrk:nsvtx:nselIPtrk");
  TFile *foutevt = new TFile(outputfilenameevt,"recreate");
  TNtuple *ntevt = new TNtuple("nt","ntinc","prew:bin:vz:hiHF:hltCSV60:hltCSV80");
  
  for (unsigned i=0;i<subfoldernames.size();i++) {
    //get all files for unmerged forests
    auto files = list_files(TString::Format("%s/%s/",samplesfolder.Data(),subfoldernames[i].Data()));

    for (auto filename:files) {
    cout<<endl<<"Processing file "<<filename<<endl;

    TFile *f = new TFile(filename);
    TString treename = jettree;//f->Get(jettree) != 0 ? jettree : "ak3PFJetAnalyzer";
    TTreeReader reader(treename,f);
    TTreeReaderValue<int> nref(reader, "nref");
    TTreeReaderArray<float> rawpt(reader, "rawpt");
    TTreeReaderArray<float> jtpt(reader, "jtpt");
    TTreeReaderArray<float> jteta(reader, "jteta");
    TTreeReaderArray<float> jtphi(reader, "jtphi");
    TTreeReaderArray<float> discr_csvV1(reader, "discr_csvV1");

    TTreeReaderArray<float> discr_prob(reader, "discr_prob");
    TTreeReaderArray<float> svtxm(reader, "svtxm");
    TTreeReaderArray<float> svtxdls(reader, "svtxdls");
    TTreeReaderArray<float> svtxpt(reader, "svtxpt");

    TTreeReaderArray<int> svtxntrk(reader, "svtxntrk");
    TTreeReaderArray<int> nsvtx(reader, "nsvtx");
    TTreeReaderArray<int> nselIPtrk(reader, "nselIPtrk");

    TTreeReaderArray<float> *muMax=0, *muMaxTRK=0, *muMaxGBL=0;
    if (PbPb) {
      muMax = new TTreeReaderArray<float> (reader, "muMax");
      muMaxTRK = new TTreeReaderArray<float>(reader, "muMaxTRK");
      muMaxGBL = new TTreeReaderArray<float>(reader, "muMaxGBL");
    }


    //HLT_HIPuAK4CaloBJetCSV80_Eta2p1_v1 HLT_HIPuAK4CaloJet80_Eta5p1_v1

    TString calojet40trigger = !PbPb ? "HLT_AK4CaloJet40_Eta5p1_v1" : "HLT_HIPuAK4CaloJet40_Eta5p1_v1";
    TString calojet40triggerv2 = !PbPb ? "HLT_AK4CaloJet40_Eta5p1_v1" : "HLT_HIPuAK4CaloJet40_Eta5p1_v2";
    TString calojet60trigger = !PbPb ? "HLT_AK4CaloJet60_Eta5p1_v1" : "HLT_HIPuAK4CaloJet60_Eta5p1_v1";
    TString calojet80trigger = !PbPb ? "HLT_AK4CaloJet80_Eta5p1_v1" : "HLT_HIPuAK4CaloJet80_Eta5p1_v1";
    //dummy vars in PbPb case
    TString pfjet60trigger = !PbPb ? "HLT_AK4PFJet60_Eta5p1_v1" : "LumiBlock";
    TString pfjet80trigger = !PbPb ? "HLT_AK4PFJet80_Eta5p1_v1" : "LumiBlock";
    TString csv60trigger = !PbPb ? "HLT_AK4PFBJetBCSV60_Eta2p1_v1"  : "HLT_HIPuAK4CaloBJetCSV60_Eta2p1_v1";
    TString csv80trigger = !PbPb ? "HLT_AK4PFBJetBCSV80_Eta2p1_v1"  : "HLT_HIPuAK4CaloBJetCSV80_Eta2p1_v1";

    //PbPb pprimaryVertexFilter && pclusterCompatibilityFilter do nothing
    vector<TString> filterNames;
    if (PbPb) filterNames = {"pcollisionEventSelection", "HBHENoiseFilterResultRun2Loose"};
    else filterNames = {"pPAprimaryVertexFilter", "HBHENoiseFilterResultRun2Loose", "pBeamScrapingFilter"}; 

    TTreeReader readerhlt("hltanalysis/HltTree",f);
    TTreeReaderValue<int> PFJet60(readerhlt, pfjet60trigger);
    TTreeReaderValue<int> PFJet80(readerhlt, pfjet80trigger);


    TTreeReaderValue<int> CaloJet40(readerhlt, calojet40trigger);
    TTreeReaderValue<int> CaloJet40v2(readerhlt, calojet40triggerv2);
    TTreeReaderValue<int> CaloJet60(readerhlt, calojet60trigger);
    TTreeReaderValue<int> CaloJet80(readerhlt, calojet80trigger);

    TTreeReaderValue<int> CSV60(readerhlt, csv60trigger);
    TTreeReaderValue<int> CSV80(readerhlt, csv80trigger);

    TTreeReader readercsv60object("hltobject/HLT_HIPuAK4CaloBJetCSV60_Eta2p1_v",f);
    TTreeReaderValue<vector<Double_t> > csv60pt(readercsv60object, "pt");
    TTreeReaderValue<vector<Double_t> > csv60eta(readercsv60object, "eta");
    TTreeReaderValue<vector<Double_t> > csv60phi(readercsv60object, "phi");
    
    TTreeReader readercsv80object("hltobject/HLT_HIPuAK4CaloBJetCSV80_Eta2p1_v",f);
    TTreeReaderValue<vector<Double_t> > csv80pt(readercsv80object, "pt");
    TTreeReaderValue<vector<Double_t> > csv80eta(readercsv80object, "eta");
    TTreeReaderValue<vector<Double_t> > csv80phi(readercsv80object, "phi");
    
    TTreeReader readerCalo60object("hltobject/HLT_HIPuAK4CaloJet60_Eta5p1_v",f);
    TTreeReaderValue<vector<Double_t> > calo60pt(readerCalo60object, "pt");
    TTreeReaderValue<vector<Double_t> > calo60eta(readerCalo60object, "eta");
    TTreeReaderValue<vector<Double_t> > calo60phi(readerCalo60object, "phi");
    
    TTreeReader readerCalo80object("hltobject/HLT_HIPuAK4CaloJet80_Eta5p1_v",f);
    TTreeReaderValue<vector<Double_t> > calo80pt(readerCalo80object, "pt");
    TTreeReaderValue<vector<Double_t> > calo80eta(readerCalo80object, "eta");
    TTreeReaderValue<vector<Double_t> > calo80phi(readerCalo80object, "phi");


    TTreeReader readerevt("hiEvtAnalyzer/HiTree",f);
    TTreeReaderValue<float> vz(readerevt, "vz");
    TTreeReaderValue<int> bin(readerevt, "hiBin");
    TTreeReaderValue<float> hiHF(readerevt, "hiHF");
    
    TTreeReaderValue<unsigned int> run(readerevt, "run");
    TTreeReaderValue<unsigned int> lumi(readerevt, "lumi");
    TTreeReaderValue<unsigned long long> event(readerevt, "evt");

    TTreeReader readerskim("skimanalysis/HltTree",f);

    vector<TTreeReaderValue<int> *>filters;
    for (auto f:filterNames)
      filters.push_back(new TTreeReaderValue<int>(readerskim, f));
      
    cout<<"added filters"<<endl;
    
    int nev = reader.GetEntries(true); cout<<nev<<endl;
    totentries+=nev;
    int onep = nev/100;
    int evCounter = 0;
    TTimeStamp t0;
    
    //for testing - only 10% of data
    //while (evCounter<2*onep && reader.Next()) {
    //go full file
    while (reader.Next()) {
      readerhlt.Next();
      readerevt.Next();
      readerskim.Next();
      readercsv60object.Next();
      readercsv80object.Next();
      readerCalo60object.Next();
      readerCalo80object.Next();

      evCounter++;
      if (evCounter%onep==0) {
        std::cout << std::fixed;
        TTimeStamp t1; 
        cout<<" \r"<<evCounter/onep<<"%   "<<" total time "<<(int)round((t1-t0)*nev/(evCounter+.1))<<" s "<<flush;
      }


      int bPFJet60 = !PbPb ? *PFJet60 : 1;
      int bPFJet80 = !PbPb ? *PFJet80 : 1;

      //int jet40 = *CaloJet40 || *CaloJet40v2;

      float weight = 1;

      if (!PbPb)
        weight = getweight(subfoldernames[i], bPFJet60, bPFJet80);


      if (PbPb && sample=="j60")
        weight = *CaloJet60;//only calojet 40

      ntevt->Fill(weight, *bin, *vz, *hiHF, *CSV60, *CSV80);

      if (weight==0) continue;

      //good event is vertex cut and noise cuts
      bool goodevent = abs(*vz)<15;
      for (auto f:filters) 
        goodevent&=*(*f);

      int ind1=-1, ind2=-1, ind3=-1, indSL=-1; //indices of leading/subleading jets in jet array
      int indTrigCSV60=-1, indTrigCSV80=-1, indTrigCalo60=-1, indTrigCalo80=-1;
      int SLord = 0;
      bool foundJ1=false, foundJ2 = false, foundJ3 = false, foundSL = false; //found/not found yet, for convenience

      bool triggermatched = false;

      if (goodevent)
        for (int j=0;j<*nref;j++) {
          //acceptance selection
          if (abs(jteta[j])>1.5) continue;
          //muon cuts
          if (PbPb) {
            if((*muMax)[j]/rawpt[j]>0.95) continue;
            if( ((*muMaxTRK)[j]-(*muMaxGBL)[j]) / ((*muMaxTRK)[j]+(*muMaxGBL)[j]) > 0.1) continue;
          }
  
          if (!foundJ1) { //looking for the leading jet
              ind1 = j;
              foundJ1=true;

	      if (PbPb) {
		indTrigCSV60 = triggeredLeadingJetCSV(jtphi[j], jteta[j], *csv60pt, *csv60phi, *csv60eta);
		indTrigCSV80 = triggeredLeadingJetCSV(jtphi[j], jteta[j], *csv80pt, *csv80phi, *csv80eta);
		indTrigCalo60 = triggeredLeadingJetCalo(jtphi[j], jteta[j], *calo60pt, *calo60phi, *calo60eta);
		indTrigCalo80 = triggeredLeadingJetCalo(jtphi[j], jteta[j], *calo80pt, *calo80phi, *calo80eta);
	      }
             
	      triggermatched = !PbPb || indTrigCSV60!=-1 || indTrigCSV80!=-1;
	  } else
            if (foundJ1 && !foundJ2) {
              ind2 = j;
              foundJ2 = true;
            } else
            if (foundJ1 && foundJ2 && !foundJ3) {
              ind3 = j;
              foundJ3 = true;
            }

          //we need ordinal number of SL jets, so counting until found
          //indSL != SLord because some jets are not in acceptance region
            if (!foundSL) SLord++;

          //ind1!=j otherwise SL will be = J1
            if (foundJ1 && ind1!=j && !foundSL && discr_csvV1[j]>0.9) {
              indSL = j;
              foundSL = true;
            }  




          //at this point foundLJ = true always, so triggermatched is determined
          vector<float> vinc = {weight, (float)triggermatched, (float) *bin, *vz, *hiHF,(float)*CSV60, (float)*CSV80,(float)*CaloJet40, (float)*CaloJet60, (float)*CaloJet80,
            (float)bPFJet60,(float)bPFJet80, rawpt[j], jtpt[j], jtphi[j], jteta[j], discr_csvV1[j],svtxm[j],discr_prob[j],
            svtxdls[j],svtxpt[j],(float)svtxntrk[j],(float)nsvtx[j],(float)nselIPtrk[j]};
  
          ntinc->Fill(&vinc[0]);
        }

      //fill dijet ntuple
      vector<float> vdj;

      vdj = {(float)*run, (float)*lumi, (float)*event, weight, (float)triggermatched, (float)*bin, *vz,*hiHF,
        (float)*CSV60, (float)*CSV80,(float)*CaloJet40,(float)*CaloJet60, (float)*CaloJet80,(float)bPFJet60,(float)bPFJet80, 
        foundJ1 && foundJ2 ? (float)1 : (float)0,

        indTrigCalo60!=-1 ? (float)(*calo60pt)[indTrigCalo60] : NaN,
        indTrigCalo60!=-1 ? (float)(*calo60phi)[indTrigCalo60] : NaN,
        indTrigCalo60!=-1 ? (float)(*calo60eta)[indTrigCalo60] : NaN,

        indTrigCalo80!=-1 ? (float)(*calo80pt)[indTrigCalo80] : NaN,
        indTrigCalo80!=-1 ? (float)(*calo80phi)[indTrigCalo80] : NaN,
        indTrigCalo80!=-1 ? (float)(*calo80eta)[indTrigCalo80] : NaN,

        indTrigCSV60!=-1  ? (float)(*csv60pt)[indTrigCSV60] : NaN,
        indTrigCSV60!=-1  ? (float)(*csv60phi)[indTrigCSV60] : NaN,
        indTrigCSV60!=-1  ? (float)(*csv60eta)[indTrigCSV60] : NaN,

        indTrigCSV80!=-1  ? (float)(*csv80pt)[indTrigCSV80] : NaN,
        indTrigCSV80!=-1  ? (float)(*csv80phi)[indTrigCSV80] : NaN,
        indTrigCSV80!=-1  ? (float)(*csv80eta)[indTrigCSV80] : NaN,
                                
        foundJ1 ? rawpt[ind1] : NaN,
        foundJ1 ? jtpt[ind1] : NaN,
        foundJ1 ? jtphi[ind1] : NaN,
        foundJ1 ? jteta[ind1] : NaN,
        foundJ1 ? discr_csvV1[ind1] : NaN,
        foundJ1 ? svtxm[ind1] : NaN,
        foundJ1 ? discr_prob[ind1] : NaN,
        foundJ1 ? svtxdls[ind1] : NaN,
        foundJ1 ? svtxpt[ind1] : NaN,
        foundJ1 ? (float)svtxntrk[ind1] : NaN,
        foundJ1 ? (float)nsvtx[ind1] : NaN,
        foundJ1 ? (float)nselIPtrk[ind1] : NaN,

        foundJ2 ? rawpt[ind2] : NaN,
        foundJ2 ? jtpt[ind2] : NaN,
        foundJ2 ? jtphi[ind2] : NaN,
        foundJ2 ? jteta[ind2] : NaN,
        foundJ2 ? discr_csvV1[ind2] : NaN,
        foundJ2 ? svtxm[ind2] : NaN,
        foundJ2 ? discr_prob[ind2] : NaN,
        foundJ2 ? svtxdls[ind2] : NaN, 
        foundJ2 ? svtxpt[ind2] : NaN,
        foundJ2 ? (float)svtxntrk[ind2] : NaN,
        foundJ2 ? (float)nsvtx[ind2] : NaN,
        foundJ2 ? (float)nselIPtrk[ind2] : NaN,
        foundJ2 && foundJ1 ? acos(cos(jtphi[ind2]-jtphi[ind1])) : NaN,
    
        foundJ3 ? rawpt[ind3] : NaN,
        foundJ3 ? jtpt[ind3] : NaN,
        foundJ3 ? jtphi[ind3] : NaN,
        foundJ3 ? jteta[ind3] : NaN,
        foundJ3 ? discr_csvV1[ind3] : NaN,
        foundJ3 ? svtxm[ind3] : NaN,
        foundJ3 ? discr_prob[ind3] : NaN,
        foundJ3 ? svtxdls[ind3] : NaN, 
        foundJ3 ? svtxpt[ind3] : NaN,
        foundJ3 ? (float)svtxntrk[ind3] : NaN,
        foundJ3 ? (float)nsvtx[ind3] : NaN,
        foundJ3 ? (float)nselIPtrk[ind3] : NaN,
        foundJ3 && foundJ1 ? acos(cos(jtphi[ind3]-jtphi[ind1])) : NaN,
        foundJ3 && foundJ2 ? acos(cos(jtphi[ind3]-jtphi[ind2])) : NaN,

        foundSL ? (float)SLord : NaN,
        foundSL ? rawpt[indSL] : NaN,
        foundSL ? jtpt[indSL] : NaN,
        foundSL ? jtphi[indSL] : NaN,
        foundSL ? jteta[indSL] : NaN,
        foundSL ? discr_csvV1[indSL] : NaN,
        foundSL ? svtxm[indSL] : NaN,
        foundSL ? discr_prob[indSL] : NaN,
        foundSL ? svtxdls[indSL] : NaN, 
        foundSL ? svtxpt[indSL] : NaN,
        foundSL ? (float)svtxntrk[indSL] : NaN,
        foundSL ? (float)nsvtx[indSL] : NaN,
        foundSL ? (float)nselIPtrk[indSL] : NaN,
        foundSL && foundJ1 ? acos(cos(jtphi[indSL]-jtphi[ind1])) : NaN};


      ntdj->Fill(&vdj[0]);



    }

    f->Close();
    }
  }
  
  foutevt->cd();
  ntevt->Write();
  foutevt->Close();

  foutdj->cd();
  ntdj->Write();
  foutdj->Close();

  foutinc->cd();
  ntinc->Write();
  foutinc->Close();

  cout<<endl;
  cout<<"Total input entries "<<totentries<<endl;

  //making centrality-dependent ntuples
  //PutInCbins(outputfolder, code, {{0,40}, {80,200}});

  if (PbPb && sample=="bjt"){
    auto w = calculateWeightsBjet(outputfilenamedj);

    updatePbPbBtriggerweight(outputfilenamedj,w);
    updatePbPbBtriggerweight(outputfilenameinc,w);
    updatePbPbBtriggerweight(outputfilenameevt,w);
  } else {
    updateweight(outputfilenamedj);
    updateweight(outputfilenameinc);
    updateweight(outputfilenameevt);
    }

}
Esempio n. 11
0
bool
HdStGLSLProgram::Link()
{
    HD_TRACE_FUNCTION();
    HF_MALLOC_TAG_FUNCTION();

    if (!glLinkProgram) return false; // glew initialized

    GLuint program = _program.GetId();
    if (program == 0) {
        TF_CODING_ERROR("At least one shader has to be compiled before linking.");
        return false;
    }

    bool dumpShaderBinary = TfDebug::IsEnabled(HD_DUMP_SHADER_BINARY);

    if (dumpShaderBinary) {
        // set RETRIEVABLE_HINT to true for getting program binary length.
        // note: Actually the GL driver may recompile the program dynamically on
        // some state changes, so the size of program could be inaccurate.
        glProgramParameteri(program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT,
                            GL_TRUE);
    }

    // link
    glLinkProgram(program);

    std::string logString;
    bool success = true;
    if (!HdStGLUtils::GetProgramLinkStatus(program, &logString)) {
        // XXX:validation
        TF_WARN("Failed to link shader: %s", logString.c_str());
        success = false;
    }

    // initial program size
    GLint size;
    glGetProgramiv(program, GL_PROGRAM_BINARY_LENGTH, &size);

    // update the program resource allocation
    _program.SetAllocation(program, size);

    // create an uniform buffer
    GLuint uniformBuffer = _uniformBuffer.GetId();
    if (uniformBuffer == 0) {
        glGenBuffers(1, &uniformBuffer);
        _uniformBuffer.SetAllocation(uniformBuffer, 0);
    }

    // binary dump out
    if (dumpShaderBinary) {
        std::vector<char> bin(size);
        GLsizei len;
        GLenum format;
        glGetProgramBinary(program, size, &len, &format, &bin[0]);
        static int id = 0;
        std::stringstream fname;
        fname << "program" << id++ << ".bin";

        std::fstream output(fname.str().c_str(), std::ios::out|std::ios::binary);
        output.write(&bin[0], size);
        output.close();

        std::cout << "Write " << fname.str() << " (size=" << size << ")\n";
    }

    return success;
}
Esempio n. 12
0
int main()
{
	int i,p,t=0;
	printf("Enter the text\n");
	//for(i=0;i<16;i++)
	scanf("%s",text);
	char str[100];
	int str1[100];
	for(i=0;i<strlen(text);i++)
		str1[i]=(int)(text[i]);
	
	printf("Enter the crossover key\n");
	for(i=0;i<2;i++){
		scanf("%d",&c[i]);
	}
	printf("Enter the mutation key\n");
	for(i=0;i<2;i++){
		scanf("%d",&m[i]);
	}	
	key[0]=c[0];  
	key[1]=c[1];
	key[2]=m[0];
	key[3]=m[1];	
	c1[0]=key[0];
	c1[1]=key[1];
	m1[0]=key[2];
	m1[1]=key[3];	
	for(i=0;i<strlen(text);i++)
		bin(str1[i]);
	k=0;	
	int j;
	while(k<g)
	{
		for(i=0;i<8;i++)
			a[i]=d[k++];
		j=0;
		for(i=8;i<16;i++)
		{
			b[j]=d[k++];
			j++;	
		}
		encrp();
			//k=k+16;
	}
	int l=0,v=0,dec[10],dec1[10],w[100],w1[100],o=0,o1=0;
	char st[100];
	printf("Text:");
	for(i=0;i<g;i++)
		printf("%d",d[i]);
	printf("\nEncrypted text:");
	for(i=0;i<g;i++)
		printf("%d",enc[i]);
	
	while(v<g1)
	{
		for(i=0;i<7;i++)
		{
			dec1[i]=enc[v++];
		}
		w1[o1++]=binary_decimal(dec1);
		
	}
	for(i=0;i<o1;i++)
	{
		st[i]=(char)(w1[i]);
	}
	st[i+1]='\0';
	printf("\n%s\n",st);
	k=0;
	while(k<g1)
	{
		for(i=0;i<8;i++)
			a[i]=enc[k++];
		j=0;
		for(i=8;i<16;i++)
		{
			b[j]=enc[k++];
			j++;	
		}
		decry();
		//k=k+16;
	}
	printf("\nDecrypted text:");
	for(i=0;i<g;i++)
		printf("%d",decr[i]);
	//printf("\n%d\t%d\t%d\n",g,g1,g2);
	
	while(l<g2)
	{
		for(i=0;i<7;i++)
		{
			dec[i]=decr[l++];
		}
		w[o++]=binary_decimal(dec);
		
	}
	for(i=0;i<o;i++)
	{
		str[i]=(char)(w[i]);
	}
	str[i+1]='\0';
	printf("\nDecrypted text=%s\n",str);
				
	return 0;
}
    __forceinline void SpatialSplit::BinInfo::bin(Scene* scene, TriRefList& prims, const PrimInfo& pinfo, const Mapping& mapping)
    {
      TriRefList::iterator i=prims;
      while (TriRefList::item* block = i.next())
	bin(scene,block->base(),block->size(),pinfo,mapping);
    }
Esempio n. 14
0
int main()
{
  mem_filesystem fs;
  //REV: Make fake filesystem

  std::string bname="memfiletest.binary";
  std::string tname="memfiletest.txt";
  
  std::ofstream bin( bname, std::ios::binary | std::ios::out );
  double xd=3.0, yd=2.5, zd=5.0;
  int xi=1, yi=15, zi=30000;
  long int xl=5999333, yl=1, zl=483;

  //bin << xd << yd << zd << xi << yi << zi << xl << yl << zl;
  bin.write( (char*)&xd, sizeof(xd) );
  bin.write( (char*)&yd, sizeof(yd) );
  bin.write( (char*)&zd, sizeof(zd) );
  bin.write( (char*)&xi, sizeof(xi) );
  bin.write( (char*)&yi, sizeof(yi) );
  bin.write( (char*)&zi, sizeof(zi) );
  bin.write( (char*)&xl, sizeof(xl) );
  bin.write( (char*)&yl, sizeof(yl) );
  bin.write( (char*)&zl, sizeof(zl) );

  bin.close();

  std::ofstream txt( tname );

  txt << xd << " " << yd << " " << zd << " " << xi << " " << yi << " " << zi <<
    " " << xl << " " << yl << " " << zl; //no endl.

  txt.close();
  
  //make a double then int file.
  fs.add_file_from_disk( bname );
  fs.add_file_from_disk( tname );
  
  memfile_ptr binptr = fs.get_ptr( bname );
  memfile_ptr txtptr = fs.get_ptr( tname );

  
  
  xd=binptr.consume_from_binary<double>(), yd=binptr.consume_from_binary<double>(), zd=binptr.consume_from_binary<double>(), xi=binptr.consume_from_binary<int>(), yi=binptr.consume_from_binary<int>(), zi=binptr.consume_from_binary<int>(), xl=binptr.consume_from_binary<long int>(), yl=binptr.consume_from_binary<long int>(), zl=binptr.consume_from_binary<long int>();
  //REV: HOLY SHIT, fprintf optional args are read in opposite order (maybe)!!!!!!!!!!
  
  //fprintf( stdout, "From binary: %lf %lf %lf %d %d %d %ld %ld %ld", binptr.consume_from_binary<double>(), binptr.consume_from_binary<double>(), binptr.consume_from_binary<double>(), binptr.consume_from_binary<int>(), binptr.consume_from_binary<int>(), binptr.consume_from_binary<int>(), binptr.consume_from_binary<long int>(), binptr.consume_from_binary<long int>(), binptr.consume_from_binary<long int>() );
  fprintf( stdout, "From binary: %lf %lf %lf %d %d %d %ld %ld %ld\n", xd,yd,zd,xi,yi,zi,xl,yl,zl);

  std::istringstream iss = txtptr.get_string_stream();

  double ds[3];
  int di[3];
  long int dl[3];

  
  iss >> xd  >> yd  >> zd  >> xi  >> yi  >> zi >> xl  >> yl  >> zl;

  fprintf(stdout, "FROM TXT:\n");
  std::cout << xd << " " << yd << " " << zd << " " << xi << " " << yi << " " << zi << " " << xl << " " << yl << " " << zl << std::endl;


  fs.add_file( mem_file("testout.out", false) );
  memfile_ptr outptr = fs.get_ptr( "testout.out" );

  outptr.print( "HERE IS THE DATA:\n" );

  //std::ostringstream ss = outptr.get_out_string_stream();
  //ss << xd << " " << yd << " " << zd << " " << xi << " " << yi << " " << zi << " " << xl << " " << yl << " " << zl << std::endl;

  outptr.printf("%lf %lf %lf %d %d %d %ld %ld %ld\n", xd,yd,zd,xi,yi,zi,xl,yl,zl);
  
  outptr.mfile->tofile( ".", outptr.mfile->filename );
  
  
}
inline void ArrayBigBlobs::insert_string(std::size_t ndx, StringData value)
{
    BinaryData bin(value.data(), value.size());
    bool add_zero_term = true;
    insert(ndx, bin, add_zero_term);
}
inline void ArrayBigBlobs::add_string(StringData value)
{
    BinaryData bin(value.data(), value.size());
    bool add_zero_term = true;
    add(bin, add_zero_term);
}
Esempio n. 17
0
TEST(BinaryMatrix, manipulation)
{
	BinaryMatrix<uint8_t> bin(3, 9);
	bin.set_cell(0, 0, 1);

	EXPECT_EQ(1, bin.get_cell(0, 0));
	EXPECT_EQ(0, bin.get_cell(0, 1));
	EXPECT_EQ(true, bin.get_bit(0, 0));
	EXPECT_EQ(false, bin.get_bit(0, 1));
#ifndef NDEBUG
	EXPECT_ANY_THROW(bin.get_cell(0, 2));
	EXPECT_ANY_THROW(bin.get_bit(0, 9));
#endif
	
	EXPECT_TRUE(bin.row_vec(0).get_bit(0));
	EXPECT_TRUE(bin.row_vec(0).get_cell(0));
	EXPECT_FALSE(bin.row_vec(0).get_bit(1));
	EXPECT_FALSE(bin.row_vec(0).get_cell(1));

	BinaryVector<uint8_t> vec(9);
	vec.set_bit(1);

	EXPECT_EQ(2, vec.get_cell(0));
	EXPECT_EQ(0, vec.get_cell(1));
	EXPECT_EQ(true, vec.get_bit(1));
	EXPECT_EQ(false, vec.get_bit(0));
#ifndef NDEBUG
	EXPECT_ANY_THROW(vec.get_cell(2));
	EXPECT_ANY_THROW(vec.get_bit(9));
#endif

	bin.write_vec(1, vec);

	EXPECT_EQ(2, bin.get_cell(1, 0));
	EXPECT_EQ(0, bin.get_cell(1, 1));
	EXPECT_EQ(true, bin.get_bit(1, 1));
	EXPECT_EQ(false, bin.get_bit(1, 0));

	EXPECT_FALSE(bin.row_vec(1).get_bit(0));
	EXPECT_TRUE(bin.row_vec(1).get_cell(0));
	EXPECT_TRUE(bin.row_vec(1).get_bit(1));
	EXPECT_FALSE(bin.row_vec(1).get_cell(1));

	vec = bin.row_vec(1);
	EXPECT_EQ(2, vec.get_cell(0));
	EXPECT_EQ(0, vec.get_cell(1));
	EXPECT_EQ(true, vec.get_bit(1));
	EXPECT_EQ(false, vec.get_bit(0));

	vec = bin.row_vec(0);
	EXPECT_EQ(1, vec.get_cell(0));
	EXPECT_EQ(0, vec.get_cell(1));
	EXPECT_EQ(true, vec.get_bit(0));
	EXPECT_EQ(false, vec.get_bit(1));

#ifndef NDEBUG
	BinaryVector<uint8_t> vec_big(10);
	BinaryVector<uint8_t> vec_small(7);
	EXPECT_ANY_THROW(bin.write_vec(1, vec_big));
	EXPECT_ANY_THROW(bin.write_vec(1, vec_small));
#endif
	
	BinaryVector<uint8_t> vec2(3), vec3(3);
	vec2.set_bit(1);
	vec3.set_bit(0).set_bit(1);
	EXPECT_TRUE(vec2.VectorMult(vec2).get_bit(1));
	EXPECT_FALSE(vec2.VectorMult(vec2).get_bit(0));
	EXPECT_TRUE(vec2.VectorMult(vec3).get_bit(1));
	EXPECT_FALSE(vec2.VectorMult(vec3).get_bit(0));
	
	
	BinaryMatrix<uint8_t> mat(3,3);
	cypress::Vector<uint8_t> hector({1,0,1});
	EXPECT_EQ(1, hector[0]);
	EXPECT_EQ(0, hector[1]);
	EXPECT_EQ(1, hector[2]);
	mat.write_col_vec(1,hector);
	EXPECT_EQ(0, mat.get_bit(0,0));
	EXPECT_EQ(1, mat.get_bit(0,1));
	EXPECT_EQ(0, mat.get_bit(0,2));
	EXPECT_EQ(0, mat.get_bit(1,0));
	EXPECT_EQ(0, mat.get_bit(1,1));
	EXPECT_EQ(0, mat.get_bit(1,2));
	EXPECT_EQ(0, mat.get_bit(2,0));
	EXPECT_EQ(1, mat.get_bit(2,1));
	EXPECT_EQ(0, mat.get_bit(2,2));
	mat.write_col_vec(2,hector);
	EXPECT_EQ(0, mat.get_bit(0,0));
	EXPECT_EQ(1, mat.get_bit(0,1));
	EXPECT_EQ(1, mat.get_bit(0,2));
	EXPECT_EQ(0, mat.get_bit(1,0));
	EXPECT_EQ(0, mat.get_bit(1,1));
	EXPECT_EQ(0, mat.get_bit(1,2));
	EXPECT_EQ(0, mat.get_bit(2,0));
	EXPECT_EQ(1, mat.get_bit(2,1));
	EXPECT_EQ(1, mat.get_bit(2,2));
	
}
Esempio n. 18
0
        typename property_traits<CoreMap>::value_type
        core_numbers_impl(Graph& g, CoreMap c, PositionMap pos, Visitor vis)
        {
            typedef typename graph_traits<Graph>::vertices_size_type size_type;
            typedef typename graph_traits<Graph>::degree_size_type degree_type;
            typedef typename graph_traits<Graph>::vertex_descriptor vertex;
            typename graph_traits<Graph>::vertex_iterator vi,vi_end;

            // store the vertex core numbers
            typename property_traits<CoreMap>::value_type v_cn = 0;

            // compute the maximum degree (degrees are in the coremap)
            typename graph_traits<Graph>::degree_size_type max_deg = 0;
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                max_deg = (std::max<typename graph_traits<Graph>::degree_size_type>)(max_deg, get(c,*vi));
            }

            // store the vertices in bins by their degree
            // allocate two extra locations to ease boundary cases
            std::vector<size_type> bin(max_deg+2);
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                ++bin[get(c,*vi)];
            }

            // this loop sets bin[d] to the starting position of vertices
            // with degree d in the vert array for the bucket sort
            size_type cur_pos = 0;
            for (degree_type cur_deg = 0; cur_deg < max_deg+2; ++cur_deg) {
                degree_type tmp = bin[cur_deg];
                bin[cur_deg] = cur_pos;
                cur_pos += tmp;
            }

            // perform the bucket sort with pos and vert so that
            // pos[0] is the vertex of smallest degree
            std::vector<vertex> vert(num_vertices(g));
            for (boost::tie(vi,vi_end) = vertices(g); vi!=vi_end; ++vi) {
                vertex v=*vi;
                size_type p=bin[get(c,v)];
                put(pos,v,p);
                vert[p]=v;
                ++bin[get(c,v)];
            }
            // we ``abused'' bin while placing the vertices, now,
            // we need to restore it
            std::copy(boost::make_reverse_iterator(bin.end()-2),
                boost::make_reverse_iterator(bin.begin()),
                boost::make_reverse_iterator(bin.end()-1));
            // now simulate removing the vertices
            for (size_type i=0; i < num_vertices(g); ++i) {
                vertex v = vert[i];
                vis.examine_vertex(v,g);
                v_cn = get(c,v);
                typename graph_traits<Graph>::out_edge_iterator oi,oi_end;
                for (boost::tie(oi,oi_end) = out_edges(v,g); oi!=oi_end; ++oi) {
                    vis.examine_edge(*oi,g);
                    vertex u = target(*oi,g);
                    // if c[u] > c[v], then u is still in the graph,
                    if (get(c,u) > v_cn) {
                        degree_type deg_u = get(c,u);
                        degree_type pos_u = get(pos,u);
                        // w is the first vertex with the same degree as u
                        // (this is the resort operation!)
                        degree_type pos_w = bin[deg_u];
                        vertex w = vert[pos_w];
                        if (u!=v) {
                            // swap u and w
                            put(pos,u,pos_w);
                            put(pos,w,pos_u);
                            vert[pos_w] = u;
                            vert[pos_u] = w;
                        }
                        // now, the vertices array is sorted assuming
                        // we perform the following step
                        // start the set of vertices with degree of u
                        // one into the future (this now points at vertex
                        // w which we swapped with u).
                        ++bin[deg_u];
                        // we are removing v from the graph, so u's degree
                        // decreases
                        put(c,u,get(c,u)-1);
                    }
                }
                vis.finish_vertex(v,g);
            }
            return v_cn;
        }
Esempio n. 19
0
static void lb_create_bin(const par::communicator& comm, unsigned int dimen,
                          const list_type& pl, LBData& lbd)
{
        const unsigned int dim = point_type::dim;
        const unsigned int my_rank = comm.rank();
        const unsigned int num_proc = comm.size();

        const std::vector<real>::size_type num_cut = lbd.cut.size();

        // Count the number of points in each global bin
        std::vector<int> bin(num_cut + 1);
        unsigned int i = 0;
        for (const point_type& p : pl) {
                while (p[dimen] >= lbd.cut[i] && i < num_cut)
                        i++;
                if (i >= num_cut) break;
                bin[i]++;
        }
        const unsigned int no_last =
                std::accumulate(bin.begin(), --bin.end(), 0);

        const unsigned int num_point = lbd.size[my_rank];

        bin.back() = num_point - no_last;
        // std::cout << "mybin: ";
        // for (const auto& p : bin) std::cout << p << " ";
        // std::cout << std::endl;

        lbd.bin.resize(num_cut + 1);
        comm.allreduce(bin.data(), lbd.bin.data(), par::sum(), lbd.bin.size());

        // std::cout << "point: ";
        // for (const auto& p : pl) std::cout << p << " ";
        // std::cout << std::endl;
        // std::cout << "bin: ";
        // for (const auto& p : lbd.pointbin) std::cout << p << " ";
        // std::cout << std::endl;
        // std::cout << "cut: ";
        // for (const auto& c : lbd.pointcut) std::cout << c << " ";
        // std::cout << std::endl;

        const list_type::size_type glob_num_point =
                std::accumulate(lbd.size.begin(), lbd.size.end(), 0);

        // Bin up pointbins into procbins
        // const real target_avg = static_cast<real>(glob_num_point) / num_proc;
        // std::cout << "target_avg = " << target_avg << std::endl;
        unsigned int point_so_far = 0;
        unsigned int ibin = 0;
        for (unsigned int iproc=0; iproc<num_proc; iproc++) {
                // Loop until adding the next bin would bring us further from
                // the target number of points
                const unsigned int target =
                        std::round((glob_num_point - point_so_far) / (num_proc - iproc));
                // std::cout << "procbin target = " << target << std::endl;
                unsigned int np = 0, my_np = 0;
                while (std::abs(static_cast<real>(np) - target) >=
                       std::abs(static_cast<real>(np + lbd.bin[ibin]) - target)) {
                        np += lbd.bin[ibin];
                        my_np += bin[ibin];
                        ibin++;
                        if (ibin >= num_cut + 1) break;
                }
                // Record sendcount
                lbd.new_size[iproc] = np;
                lbd.sendcounts[iproc] = my_np * dim;
                point_so_far += np;
        }
}
Esempio n. 20
0
void CotMapCtrl::LoadGWF(LPCTSTR filename)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());
    
	//打开工程文件
	CFile file;
	if(!file.Open(filename,CFile::modeRead))
	{
        return;
	}

	//关闭之前的map
	if(m_pGeomap)
	{
		m_pGeomap.reset();
	}
    CString PrjPath =filename;
	CString basePath =PrjPath.Left(PrjPath.ReverseFind(_T('\\'))+1);

	_bstr_t strPath =basePath;
	//设置参考路径
	SYSTEM::CRelativePath::SetBasePath(strPath);

	CArchive ar(&file,CArchive::load);

	unsigned long Size;
	ar >> Size;

	BYTE * pStart = new BYTE[Size];

	ar.Read( pStart , Size );

	SYSTEM::CBinArchive bin( pStart , Size );

	bin.SetReadState();

	serialization(bin,SERIEALIZE_MAP);

	ar.Close ();
	file.Close ();

	//读取图元
	CString strELFPath = filename;
	int iResult = strELFPath.Replace( _T("GWF"), _T("ELF"));

	if ( iResult == 1 && _waccess( strELFPath, 0) == 0 )
	{
		CFile fileElF(strELFPath,CFile::modeRead);
		CArchive arELF(&fileElF,CArchive::load);

		
		arELF >> Size;

		BYTE * pbuffer = new BYTE[Size];

		arELF.Read( pbuffer , Size );

		SYSTEM::CBinArchive ebin( pbuffer , Size );

		ebin.SetReadState();

		serialization(ebin,SERIEALIZE_MAPELEMENT);

		arELF.Close ();
		fileElF.Close ();

		
	}
Esempio n. 21
0
QString runHof(const QString& file,
               const QString& input,
               bool* ok,
               bool verbose = false,
               int msecsToTimeout = 5000,
               Expectation e = Expectation::Normal)
{
    QDir bin(QCoreApplication::applicationDirPath());

    QProcess hof;
    hof.setProgram(bin.path() + QDir::separator() + "hof");

    QStringList args = QStringList()
      << "--file"
      << file
      << "--input"
      << input;

    if (verbose) {
        args.append("--verbose");
        hof.setProcessChannelMode(QProcess::ForwardedErrorChannel);
    }

    hof.setArguments(args);
    hof.start();
    bool finished = hof.waitForFinished(msecsToTimeout);
    if (!finished) {
        hof.kill();
        hof.waitForFinished();
    }

    /* special value used to indicate stack depth exceeded */
    switch (e) {
    case Expectation::Normal:
        {
            *ok = finished && hof.exitStatus() == QProcess::NormalExit &&
                  (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2);
            break;
        }
    case Expectation::NoCrash:
        {
            *ok = !finished || (hof.exitStatus() == QProcess::NormalExit &&
                  (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2));
            break;
        }
    case Expectation::Timeout:
        {
            *ok = !finished;
            break;
        }
    default:
        *ok = false;
        break;
    }

    if (!*ok) {
        qDebug() << "exit status:" << hof.exitStatus()
                 << " code:" << hof.exitCode()
                 << " error:" << hof.error();
    }

    return hof.readAll().trimmed();
}
Esempio n. 22
0
SECStatus
AddKeyFromFile(const char* basePath, const char* filename)
{
  const char* PRIVATE_KEY_HEADER = "-----BEGIN PRIVATE KEY-----";
  const char* PRIVATE_KEY_FOOTER = "-----END PRIVATE KEY-----";

  char buf[16384] = { 0 };
  SECStatus rv = ReadFileToBuffer(basePath, filename, buf);
  if (rv != SECSuccess) {
    return rv;
  }
  if (strncmp(buf, PRIVATE_KEY_HEADER, strlen(PRIVATE_KEY_HEADER)) != 0) {
    PR_fprintf(PR_STDERR, "invalid key - not importing\n");
    return SECFailure;
  }
  const char* bufPtr = buf + strlen(PRIVATE_KEY_HEADER);
  size_t bufLen = strlen(buf);
  char base64[16384] = { 0 };
  char* base64Ptr = base64;
  while (bufPtr < buf + bufLen) {
    if (strncmp(bufPtr, PRIVATE_KEY_FOOTER, strlen(PRIVATE_KEY_FOOTER)) == 0) {
      break;
    }
    if (*bufPtr != '\r' && *bufPtr != '\n') {
      *base64Ptr = *bufPtr;
      base64Ptr++;
    }
    bufPtr++;
  }

  unsigned int binLength;
  UniquePORTString bin(
    reinterpret_cast<char*>(ATOB_AsciiToData(base64, &binLength)));
  if (!bin || binLength == 0) {
    PrintPRError("ATOB_AsciiToData failed");
    return SECFailure;
  }
  ScopedSECItem secitem(::SECITEM_AllocItem(nullptr, nullptr, binLength));
  if (!secitem) {
    PrintPRError("SECITEM_AllocItem failed");
    return SECFailure;
  }
  PORT_Memcpy(secitem->data, bin.get(), binLength);
  ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
  if (!slot) {
    PrintPRError("PK11_GetInternalKeySlot failed");
    return SECFailure;
  }
  if (PK11_NeedUserInit(slot)) {
    if (PK11_InitPin(slot, nullptr, nullptr) != SECSuccess) {
      PrintPRError("PK11_InitPin failed");
      return SECFailure;
    }
  }
  SECKEYPrivateKey* privateKey;
  if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, secitem, nullptr, nullptr,
                                               true, false, KU_ALL,
                                               &privateKey, nullptr)
        != SECSuccess) {
    PrintPRError("PK11_ImportDERPrivateKeyInfoAndReturnKey failed");
    return SECFailure;
  }
  SECKEY_DestroyPrivateKey(privateKey);
  return SECSuccess;
}
Esempio n. 23
0
int main(void)
{
	printf("\n");
	printf("This is hardly exhaustive...\n");


	printf("WriteMasked...\n");

	uint8_t orig = bin(0,0,0,0,1,1,1,1);
	uint8_t val  = bin(0,0,1,1,0,0,1,1);
	uint8_t mask = bin(0,1,0,1,0,1,0,1);
	uint8_t wm   = orig;

	writeMasked(val, mask, wm);

	printf("original: 0x%02"PRIx8" = ", orig); printBin8(orig);
	printf("value:    0x%02"PRIx8" = ", val); printBin8(val);
	printf("mask:     0x%02"PRIx8" = ", mask); printBin8(mask);
	printf("---------------------------------\n");
	printf("output:   0x%02"PRIx8" = ", wm); printBin8(wm);

	printf("\n");


	
	
	
	
	
	
	
	printf("&PORTA = "HEX8"\n"
		    "&DDR_FROM_PORT(PORTA) = "HEX8"\n"
			 "&PIN_FROM_PORT(PORTA) = "HEX8"\n",
			 (uint8_t)(&PORTA), (uint8_t)(&DDR_FROM_PORT(PORTA)), 
			 (uint8_t)(&PIN_FROM_PORT(PORTA)));


	printf("\n");


	FAKE_PORT = 0x55;

	printf("FAKE_PORT = 0x55; -> FAKE_PORT=="HEX8" ", FAKE_PORT);
	printBin8(FAKE_PORT);

	printf("(FAKE_PORT -> portStuff[2]=="HEX8")\n", portStuff[2]);
	
	DDR_FROM_PORT(FAKE_PORT)=0x44;
	PIN_FROM_PORT(FAKE_PORT)=0x33;

	printf("FAKE_DDR=="HEX8", portStuff[1]=="HEX8" ",
												FAKE_DDR, portStuff[1]);

	printBin8(FAKE_DDR);

	printf("FAKE_PIN=="HEX8", portStuff[0]=="HEX8" ",
												FAKE_PIN, portStuff[0]);
	printBin8(FAKE_PIN);


	printf("\n");
	printf("setPORToutMasked(FAKE_PORT, 0x3f):\n");
	setPORToutMasked(FAKE_PORT, 0x3f);
	printPortState();

	printf("\n");
	printf("setPORTinpuMasked(FAKE_PORT, 0x3f):\n");
	setPORTinpuMasked(FAKE_PORT, 0x3f);
	printPortState();

	printf("\n");
	printf("PORTin(FAKE_PORT)=="HEX8"\n", PORTin(FAKE_PORT));
	printPortState();

	printf("\n");
	printf("setPORTout(FAKE_PORT)\n");
	setPORTout(FAKE_PORT);
	printPortState();

	printf("\n");
	printf("setPORTinPU(FAKE_PORT)\n");
	setPORTinpu(FAKE_PORT);
	printPortState();
}
Esempio n. 24
0
CORASMA_BER_Test::CORASMA_BER_Test()
{
    modem=new Modem_CORASMA();
    int L=1;
    int OF=1;

    cmat fading;
    cvec channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,channel9,channel10,channel11,channel12,channel13,channel14,channel15,channel16;
    bvec transmitted_bits;
    bvec received_bits;
    cvec sum_chips;
    cvec transmitted_symbols;
    cvec received_chips;
    double norm_fading;
    BERC berc,berc1,berc2;
    AWGN_Channel channel;

    vec EbN0dB = linspace(1000, 1000, 1);
    vec EbN0 = pow(10, EbN0dB / 10);
    double Eb = 1.0;
    vec N0 = Eb * pow(EbN0, -1.0);
    int NumOfBits = modem->nb_bits;
    int MaxIterations = 10;
    int MaxNrOfErrors = 200;
    int MinNrOfErrors = 5;
    vec ber;
    ber.set_size(EbN0dB.size(), false);
    ber.clear();
    RNG_randomize();



    for (int i=0;i<EbN0dB.length();i++){

        cout << endl << "Simulating point nr " << i + 1 << endl;
        berc.clear();
        berc1.clear();
        berc2.clear();
        channel.set_noise(N0(i));

        for (int j=0;j<MaxIterations;j++) {

            transmitted_bits = randb(NumOfBits);
            sum_chips=modem->modulate(transmitted_bits);


            transmitted_symbols.set_length(sum_chips.length()+L+1);
            transmitted_symbols.zeros();

            fading.set_size(L,sum_chips.length());
            fading.zeros();

            channel1.set_length(sum_chips.length());
/*          channel2.set_length(sum_chips.length());
            channel3.set_length(sum_chips.length());
            channel4.set_length(sum_chips.length());
            channel5.set_length(sum_chips.length());
            channel6.set_length(sum_chips.length());
            channel7.set_length(sum_chips.length());
            channel8.set_length(sum_chips.length());
            channel9.set_length(sum_chips.length());
            channel10.set_length(sum_chips.length());
            channel11.set_length(sum_chips.length());
            channel12.set_length(sum_chips.length());
            channel13.set_length(sum_chips.length());
            channel14.set_length(sum_chips.length());
            channel15.set_length(sum_chips.length());
            channel16.set_length(sum_chips.length());*/


            for(int k=0;k<sum_chips.length()/OF;k++){


                channel1.replace_mid(k*OF,ones_c(OF));

/*              channel1.replace_mid(k*OF,randn_c()*ones(OF));
                channel2.replace_mid(k*OF,randn_c()*ones(OF));
                channel3.replace_mid(k*OF,randn_c()*ones(OF));
                channel4.replace_mid(k*OF,randn_c()*ones(OF));
                channel5.replace_mid(k*OF,randn_c()*ones(OF));
                channel6.replace_mid(k*OF,randn_c()*ones(OF));
                channel7.replace_mid(k*OF,randn_c()*ones(OF));
                channel8.replace_mid(k*OF,randn_c()*ones(OF));
                channel9.replace_mid(k*OF,randn_c()*ones(OF));
                channel10.replace_mid(k*OF,randn_c()*ones(OF));
                channel11.replace_mid(k*OF,randn_c()*ones(OF));
                channel12.replace_mid(k*OF,randn_c()*ones(OF));
                channel13.replace_mid(k*OF,randn_c()*ones(OF));
                channel14.replace_mid(k*OF,randn_c()*ones(OF));
                channel15.replace_mid(k*OF,randn_c()*ones(OF));
                channel16.replace_mid(k*OF,randn_c()*ones(OF));*/

            }


            norm_fading=1./sqrt(inv_dB(0)*norm(channel1)*norm(channel1)/sum_chips.length()/*+inv_dB(0)*norm(channel2)*norm(channel2)/sum_chips.length()+inv_dB(0)*norm(channel3)*norm(channel3)/sum_chips.length()+inv_dB(0)*norm(channel4)*norm(channel4)/sum_chips.length()+inv_dB(0)*norm(channel5)*norm(channel5)/sum_chips.length()+inv_dB(0)*norm(channel6)*norm(channel6)/sum_chips.length()+inv_dB(0)*norm(channel7)*norm(channel7)/sum_chips.length()+inv_dB(0)*norm(channel8)*norm(channel8)/sum_chips.length()+inv_dB(0)*norm(channel9)*norm(channel9)/sum_chips.length()+inv_dB(0)*norm(channel10)*norm(channel10)/sum_chips.length()+inv_dB(0)*norm(channel11)*norm(channel11)/sum_chips.length()+inv_dB(0)*norm(channel12)*norm(channel12)/sum_chips.length()+inv_dB(0)*norm(channel13)*norm(channel13)/sum_chips.length()+inv_dB(0)*norm(channel14)*norm(channel14)/sum_chips.length()+inv_dB(0)*norm(channel15)*norm(channel15)/sum_chips.length()+inv_dB(0)*norm(channel16)*norm(channel16)/sum_chips.length()*/);
            fading.set_row(0,norm_fading*channel1);
/*          fading.set_row(1,norm_fading*channel2);
            fading.set_row(2,norm_fading*channel3);
            fading.set_row(3,norm_fading*channel4);
            fading.set_row(4,norm_fading*channel5);
            fading.set_row(5,norm_fading*channel6);
            fading.set_row(6,norm_fading*channel7);
            fading.set_row(7,norm_fading*channel8);
            fading.set_row(8,norm_fading*channel9);
            fading.set_row(9,norm_fading*channel10);
            fading.set_row(10,norm_fading*channel11);
            fading.set_row(11,norm_fading*channel12);
            fading.set_row(12,norm_fading*channel13);
            fading.set_row(13,norm_fading*channel14);
            fading.set_row(14,norm_fading*channel15);
            fading.set_row(15,norm_fading*channel16);*/

            for (int k=0;k<L;k++){
                transmitted_symbols+=concat(zeros_c(k),elem_mult(to_cvec(sum_chips),fading.get_row(k)),zeros_c(L+1-k));
            }
            received_chips = channel(/*transmitted_symbols*/sum_chips);

            cvec constellation;
            int time_offset_estimate;
            received_bits=modem->demodulate(received_chips,constellation,time_offset_estimate);
            bvec received_bits_inverted=received_bits+bin(1);
            //Generic Transmitter + First Receiver M&M + Costas
            berc1.count(transmitted_bits, received_bits);
            ber(i) = berc1.get_errorrate();
            berc=berc1;
            berc2.count(transmitted_bits, received_bits_inverted);
            if(berc2.get_errorrate()<ber(i)){
                ber(i) = berc2.get_errorrate();
                berc=berc2;
            }
            cout << "   Iteration " << j + 1 << ": ber = " << berc.get_errorrate() << endl;
            if (berc.get_errors() > MaxNrOfErrors) {
                cout << "Breaking on point " << i + 1 << " with " << berc.get_errors() << " errors." << endl;
                break;
            }

        }

        if (berc.get_errors() < MinNrOfErrors) {
            cout << "Exiting Simulation on point " << i + 1 << endl;
            break;
        }

    }

    //Print results:
    cout << endl;
    cout << "EbN0dB = " << EbN0dB << endl;
    cout << "ber = " << ber << endl;

}
Esempio n. 25
0
 variant json::from_string( const std::string& utf8_str, parse_type ptype, uint32_t max_depth )
 { try {
    fc::istream_ptr in( new fc::stringstream( utf8_str ) );
    fc::buffered_istream bin( in );
    return from_stream( bin, ptype, max_depth );
 } FC_RETHROW_EXCEPTIONS( warn, "", ("str",utf8_str) ) }
Esempio n. 26
0
MLP::Vector RankClassifier::BinarizeImageSV( const QImage& img, float maxSaturation, float minValue ) {
  MLP::Vector bin( img.width() * img.height() );

  float sumX = 0.0f;
  float sumY = 0.0f;
  int area = 0;

  for( int y = 0; y < img.height(); y++ ) {
    for( int x = 0; x < img.width(); x++ ) {
      int idx = y * img.width() + x;

      QRgb pixel = img.pixel( x, y );

      int h, s, v;
      QColor( pixel ).getHsv( &h, &s, &v );

      h = std::max(0, h);
      s = int(float(s) / 255.0f * 100.0f);
      v = int(float(v) / 255.0f * 100.0f);

      bool white = ( s <= maxSaturation && v >= minValue );
      bin[ idx ] = white ? 1.0f : 0.0f;

      if( white ) {
        sumX += (float(x) + 0.5f);
        sumY += (float(y) + 0.5f);
        area++;
      }
    }
  }

  MLP::Vector binCentered( img.width() * img.height(), 0.0f );

  float imageCenterX = img.width() * 0.5f;
  float imageCenterY = img.height() * 0.5f;

  float gravityX = area ? sumX / area : imageCenterX;
  float gravityY = area ? sumY / area : imageCenterY;

  int offsetX = std::round(imageCenterX - gravityX);
  int offsetY = std::round(imageCenterY - gravityY);

  for( int y = 0; y < img.height(); y++ ) {
    for( int x = 0; x < img.width(); x++ ) {
      int idx = y * img.width() + x;
      float val = bin[ idx ];

      int newX = x + offsetX;
      int newY = y + offsetY;

      if( newX >= 0 && newX < img.width() &&
          newY >= 0 && newY < img.height() )
      {
        int newIdx = newY * img.width() + newX;
        binCentered[ newIdx ] = val;
      }
    }
  }

  return binCentered;
}
Esempio n. 27
0
RMatrixXf SeedFeature::computeObjFeatures( const ImageOverSegmentation & ios ) {
	Image rgb_im = ios.image();
	const RMatrixXs & s = ios.s();
	const Edges & g = ios.edges();
	const int Ns = ios.Ns();
	
	RMatrixXf r = RMatrixXf::Zero( Ns, N_OBJ_F );
	if( N_OBJ_F<=1 ) return r;
	VectorXf area  = bin( s, 1, [&](int x, int y){ return 1.f; } );
	VectorXf norm = (area.array()+1e-10).cwiseInverse();
	
	r.col(0).setOnes();
	int o = 1;
	if (N_OBJ_COL>=6) {
		Image lab_im;
		rgb2lab( lab_im, rgb_im );
		r.middleCols(o,6) = norm.asDiagonal() * bin( s, 6, [&](int x, int y){ return makeArray<6>( lab_im(y,x,0), lab_im(y,x,1), lab_im(y,x,2), lab_im(y,x,0)*lab_im(y,x,0), lab_im(y,x,1)*lab_im(y,x,1), lab_im(y,x,2)*lab_im(y,x,2) ); } );
		RMatrixXf col = r.middleCols(o,3);
		if( N_OBJ_COL >= 9)
			r.middleCols(o+6,3) = col.array().square();
		o += N_OBJ_COL;
		
		// Add color difference features
		if( N_OBJ_COL_DIFF ) {
			RMatrixXf bcol = RMatrixXf::Ones( col.rows(), col.cols()+1 );
			bcol.leftCols(3) = col;
			for( int it=0; it*3+2<N_OBJ_COL_DIFF; it++ ) {
				// Apply a box filter on the graph
				RMatrixXf tmp = bcol;
				for( const auto & e: g ) {
					tmp.row(e.a) += bcol.row(e.b);
					tmp.row(e.b) += bcol.row(e.a);
				}
				bcol = tmp.col(3).cwiseInverse().asDiagonal()*tmp;
				r.middleCols(o,3) = (bcol.leftCols(3)-col).array().abs();
				o += 3;
			}
		}
	}
	if( N_OBJ_POS >= 2 ) {
		RMatrixXf xy = norm.asDiagonal() * bin( s, 2, [&](int x, int y){ return makeArray<2>( 1.0*x/(s.cols()-1)-0.5, 1.0*y/(s.rows()-1)-0.5 ); } );
		r.middleCols(o,2) = xy;
		o+=2;
		if( N_OBJ_POS >=4 ) {
			r.middleCols(o,2) = xy.array().square();
			o+=2;
		}
	}
	if( N_OBJ_EDGE ) {
		RMatrixXf edge_map = DirectedSobel().detect( rgb_im );
		for( int j=0; j<s.rows(); j++ )
			for( int i=0; i<s.cols(); i++ ) {
				const int id = s(j,i);
				int bin = edge_map(j,i)*N_OBJ_EDGE;
				if ( bin < 0 ) bin = 0;
				if ( bin >= N_OBJ_EDGE ) bin = N_OBJ_EDGE-1;
				r(id,o+bin) += norm[id];
			}
		o += N_OBJ_EDGE;
	}
	const int N_BASIC = o-1;
	// Add in context features
	for( int i=0; i<N_OBJ_CONTEXT; i++ ) {
		const int o0 = o - N_BASIC;
		// Box filter the edges
		RMatrixXf f = RMatrixXf::Ones( Ns, N_BASIC+1 ), bf = RMatrixXf::Zero( Ns, N_BASIC+1 );
		f.rightCols( N_BASIC ) = r.middleCols(o0,N_BASIC);
		for( Edge e: g ) {
			bf.row(e.a) += f.row(e.b);
			bf.row(e.b) += f.row(e.a);
		}
		r.middleCols(o,N_BASIC) = bf.col(0).array().max(1e-10f).inverse().matrix().asDiagonal() * bf.rightCols(N_BASIC);
		o += N_BASIC;
	}
	return r;
}
Esempio n. 28
0
template<> str *bin(__ss_bool b) { return bin(b.value); }
Esempio n. 29
0
	void core_numbers(const Graph& g, KCoreMap kcm, PositionMap pos)
	{
		typedef typename graph_traits<Graph>::vertex_descriptor vertex;
		typedef typename graph_traits<Graph>::degree_size_type size_type;

		BGL_FORALL_VERTICES_T(v,g,Graph)
		{
			kcm[v] = 0;
		}

		// compute the degree of all vertices
		BGL_FORALL_EDGES_T(e,g,Graph)
		{
			++kcm[source(e,g)];
		}

		size_type max_deg = 0;

		// compute the maximum degree
		BGL_FORALL_VERTICES_T(v,g,Graph)
		{
			if (kcm[v] > max_deg)
			{
				max_deg = kcm[v];
			}
		}

		// now we sort vertices into bins by their degree 
		// (we buffer this vector by 2 extra spots to make
		// some of the computations easier.
		//   1.  because deg > 0, we need max_deg+1 to index w/ deg itself
		//   2.  because we want to make things really easy, we extend
		//       the array one past degree to make computing partial_sums
		//       trivial
		std::vector<size_type> bin(max_deg+2);

		// compute the size of each bin
		BGL_FORALL_VERTICES_T(v,g,Graph)
		{
			++bin[kcm[v]];
		}

		// this loop sets bin[d] to the starting position of vertices
		// with degree d in the vert array
		size_type cur_pos = 0;
		for (size_type cur_deg = 0; cur_deg < max_deg+2; ++cur_deg)
		{
			size_type tmp = bin[cur_deg];
			bin[cur_deg] = cur_pos;
			cur_pos += tmp;
		}

		// place the vertices
		std::vector<vertex> vert(num_vertices(g));

		BGL_FORALL_VERTICES_T(v,g,Graph)
		{
			pos[v] = bin[kcm[v]];
			vert[pos[v]] = v;

			++bin[kcm[v]];
		}
Esempio n. 30
0
int DecodeMultiColorCharacterGraphics (GifFileType *SpriteGif)
{
    // character graphics
    int wwidth = 4; // wanted width
    if ((SpriteGif->SWidth % wwidth != 0) || (SpriteGif->SHeight % 21 != 0))
    {
        fprintf (stderr, "Error: Incorrect dimensions: %dx%d\n", SpriteGif->SWidth, SpriteGif->SHeight);
        return 1;
    }

    // iterate over the raster bits
    unsigned char *raster = SpriteGif->SavedImages->RasterBits;

    int wscale = SpriteGif->SWidth / wwidth;
    int hscale = SpriteGif->SHeight / 8;
    int i, j, m, h; // iterators
    int colors[4] = { -1, -1, -1, -1 }; // palette values to store
    int cur, k, l; // current color, array indices
    for (h = 0; h < hscale; h++)
    {
        for (m = 0; m < wscale; m++)
        {
            if (wscale > 1)
            {
                printf ("\n; character %x\n", m + h * 8);
            }
            for (i = 0; i < 32; i += 4)
            {
                for (j = 0; j < 4; j++)
                {
                    if (j % 4 == 0) fputs ("\n\t.byte %", stdout);
                    int index = (i * wscale + m * 4 + h * 8 * 4 * wscale) + j;
                    // world_is_a_fuck(wscale,index,4,8*hscale);
                    // fprintf(stderr,"index %d\n",index);
                    // usleep(100);
                    cur = raster[index];
                    k = in_array (colors, cur);
                    if (k == -1)
                    {
                        l = in_array (colors, -1);
                        if (l == -1)
                        {
                            fputs ("ERROR: more than 4 colors in the palette\n", stderr);
                            fputs ("Color cache: { ", stderr);
                            int z;
                            for (z = 0; z < 4; z++)
                            {
                                fprintf (stderr, "%d, ", colors[z]);
                            }
                            fputs ("}\n", stderr);
                            return 1;
                        }
                        colors[l] = cur;
                        printf (bin (l), stdout);
                    }
                    else
                    {
                        printf (bin (k), stdout);
                    }
                }
            }
        }
    }

    return 0;
}