Example #1
0
void RegisterKeyboardControls(KeyboardControls* controls){
	keyboardControls.push_back(controls);
}
int PointFloatShapeFeatureExtractor::extractFeatures(const LTKTraceGroup& inTraceGroup,
                                   vector<LTKShapeFeaturePtr>& outFeatureVec)
{
    LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
        "PointFloatShapeFeatureExtractor::extractFeatures()" << endl;
    
    PointFloatShapeFeature *featurePtr = NULL;
	float x,y,deltax;
	int numPoints=0;						// number of pts
	int count=0;
	int currentStrokeSize;
	float sintheta, costheta,sqsum;
	int i;

    int numberOfTraces = inTraceGroup.getNumTraces();

    if (numberOfTraces == 0 )
    {
        LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << 
            EEMPTY_TRACE_GROUP << " : " << getErrorMessage(EEMPTY_TRACE_GROUP)<<
            " PointFloatShapeFeatureExtractor::extractFeatures" <<endl;
        
        LTKReturnError(EEMPTY_TRACE_GROUP);
    }
    
	LTKTraceVector allTraces = inTraceGroup.getAllTraces();
	LTKTraceVector::iterator traceIter = allTraces.begin();
	LTKTraceVector::iterator traceEnd = allTraces.end();


	//***CONCATENTATING THE STROKES***
	for (; traceIter != traceEnd ; ++traceIter)
	{
		floatVector tempxVec, tempyVec;
		
		(*traceIter).getChannelValues("X", tempxVec);

		(*traceIter).getChannelValues("Y", tempyVec);

		// Number of points in the stroke
		numPoints = numPoints + tempxVec.size(); 
	}	

	//***THE CONCATENATED FULL STROKE***
	floatVector xVec(numPoints);
	floatVector yVec(numPoints);	


	traceIter = allTraces.begin();
	traceEnd  = allTraces.end();

	boolVector penUp;
	// Add the penUp here	
	for (; traceIter != traceEnd ; ++traceIter)
	{
		floatVector tempxVec, tempyVec;
		
		(*traceIter).getChannelValues("X", tempxVec);

		(*traceIter).getChannelValues("Y", tempyVec);

		currentStrokeSize = tempxVec.size();

        if (currentStrokeSize == 0)
        {
            LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << 
            EEMPTY_TRACE << " : " << getErrorMessage(EEMPTY_TRACE) <<
            " PointFloatShapeFeatureExtractor::extractFeatures" <<endl;
            
            LTKReturnError(EEMPTY_TRACE);
        }
        
		for( int point=0; point < currentStrokeSize ; point++ )
		{
			xVec[count] = tempxVec[point];
			yVec[count] = tempyVec[point];
			count++;
            
			if(point == currentStrokeSize - 1 )
            {         
				penUp.push_back(true);
            }
			else
            {         
				penUp.push_back(false);
            }
		}	

	}
	//***CONCATENTATING THE STROKES***

	vector<float> theta(numPoints);
	vector<float> delta_x(numPoints-1);
	vector<float> delta_y(numPoints-1);

	for(i=0; i<numPoints-1; ++i)
	{  
		delta_x[i]=xVec[i+1]-xVec[i];
		delta_y[i]=yVec[i+1]-yVec[i];

	}

	//Add the controlInfo here
	sqsum = sqrt( pow(xVec[0],2)+ pow(yVec[0],2))+ EPS;
    
	sintheta = (1+yVec[0]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;
    
	costheta = (1+xVec[0]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;

    featurePtr = new PointFloatShapeFeature(xVec[0],
                                             yVec[0],
                                             sintheta,
                                             costheta,
                                             penUp[0]);

	outFeatureVec.push_back(LTKShapeFeaturePtr(featurePtr));
	featurePtr = NULL;

    
	for( i=1; i<numPoints; ++i)
	{  

		//Add the controlInfo here

		sqsum = sqrt(pow(delta_x[i-1],2) + pow(delta_y[i-1],2))+EPS;
		sintheta = (1+delta_y[i-1]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;
		costheta = (1+delta_x[i-1]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;

        featurePtr = new PointFloatShapeFeature(xVec[i],
                                               yVec[i],
                                               sintheta,
                                               costheta,
                                               penUp[i]);
		//***POPULATING THE FEATURE VECTOR***
		outFeatureVec.push_back(LTKShapeFeaturePtr(featurePtr));
		featurePtr = NULL;
    
	}

    LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
        "PointFloatShapeFeatureExtractor::extractFeatures()" << endl;
    
	return SUCCESS;
}
Example #3
0
void MaxHeapInsert(vector<int>& A, int key) {
	A.push_back(INT_MIN);
	HeapIncreaseKey(A, A.size() - 1, key);
}
Example #4
0
  void ParseCommandLine(int argc, char **argv) {
    static const char *help = "Bitcoin-seeder\n"
                              "Usage: %s -h <host> -n <ns> [-m <mbox>] [-t <threads>] [-p <port>]\n"
                              "\n"
                              "Options:\n"
                              "-s <seed>       Seed node to collect peers from (replaces default)\n"
                              "-h <host>       Hostname of the DNS seed\n"
                              "-n <ns>         Hostname of the nameserver\n"
                              "-m <mbox>       E-Mail address reported in SOA records\n"
                              "-t <threads>    Number of crawlers to run in parallel (default 24)\n"
                              "-d <threads>    Number of DNS server threads (default 24)\n"
                              "-p <port>       UDP port to listen on (default 53)\n"
                              "-o <ip:port>    Tor proxy IP/Port\n"
                              "--p2port <port> P2P port to connect to\n"
                              "--magic <hex>   Magic string/network prefix\n"
                              "--wipeban       Wipe list of banned nodes\n"
                              "--wipeignore    Wipe list of ignored nodes\n"
                              "-?, --help      Show this text\n"
                              "\n";
    bool showHelp = false;

    while(1) {
      static struct option long_options[] = {
        {"seed", required_argument, 0, 's'},
        {"host", required_argument, 0, 'h'},
        {"ns",   required_argument, 0, 'n'},
        {"mbox", required_argument, 0, 'm'},
        {"threads", required_argument, 0, 't'},
        {"dnsthreads", required_argument, 0, 'd'},
        {"port", required_argument, 0, 'p'},
        {"onion", required_argument, 0, 'o'},
        {"p2port", required_argument, 0, 'b'},
        {"magic", required_argument, 0, 'k'},
        {"wipeban", no_argument, &fWipeBan, 1},
        {"wipeignore", no_argument, &fWipeBan, 1},
        {"help", no_argument, 0, 'h'},
        {0, 0, 0, 0}
      };
      int option_index = 0;
      int c = getopt_long(argc, argv, "s:h:n:m:t:p:d:o:b:k:", long_options, &option_index);
      if (c == -1) break;
      switch (c) {
        case 's': {
          vSeeds.push_back(optarg);
          break;
        }

        case 'h': {
          host = optarg;
          break;
        }
        
        case 'm': {
          mbox = optarg;
          break;
        }
        
        case 'n': {
          ns = optarg;
          break;
        }
        
        case 't': {
          int n = strtol(optarg, NULL, 10);
          if (n > 0 && n < 1000) nThreads = n;
          break;
        }

        case 'd': {
          int n = strtol(optarg, NULL, 10);
          if (n > 0 && n < 1000) nDnsThreads = n;
          break;
        }

        case 'p': {
          int p = strtol(optarg, NULL, 10);
          if (p > 0 && p < 65536) nPort = p;
          break;
        }
        
        case 'o': {
          tor = optarg;
          break;
        }

        case 'b': {
          int p = strtol(optarg, NULL, 10);
          if (p > 0 && p < 65536) nP2Port = p;
          break;
        }

        case 'k': {
          long int n;
          unsigned int c;
          magic = optarg;
          if (strlen(magic)!=8)
            break;
          n = strtol(magic, NULL, 16);
          if (n==0 && strcmp(magic, "00000000"))
            break;
          for (n=0; n<4; ++n) {
            sscanf(&magic[n*2], "%2x", &c);
            pchMessageStart[n] = (unsigned char) (c & 0xff);
          }
          break;
        }

        case '?': {
          showHelp = true;
          break;
        }
      }
    }
    if (host != NULL && ns == NULL) showHelp = true;
    if (showHelp) fprintf(stderr, help, argv[0]);
  }
Example #5
0
void Assign_element::add_cond(string &c)
{
  cond.push_back(c);
}
Example #6
0
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
{
    CScript::const_iterator pc = script.begin();
    CScript::const_iterator pend = script.end();
    CScript::const_iterator pbegincodehash = script.begin();
    opcodetype opcode;
    valtype vchPushValue;
    vector<bool> vfExec;
    vector<valtype> altstack;
    if (script.size() > 10000)
        return false;
    int nOpCount = 0;

    try
    {
        while (pc < pend)
        {
            bool fExec = !count(vfExec.begin(), vfExec.end(), false);

            //
            // Read instruction
            //
            if (!script.GetOp(pc, opcode, vchPushValue))
                return false;
            if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
                return false;

            // Note how OP_RESERVED does not count towards the opcode limit.
            if (opcode > OP_16 && ++nOpCount > 201)
                return false;

            if (opcode == OP_CAT ||
                opcode == OP_SUBSTR ||
                opcode == OP_LEFT ||
                opcode == OP_RIGHT ||
                opcode == OP_INVERT ||
                opcode == OP_AND ||
                opcode == OP_OR ||
                opcode == OP_XOR ||
                opcode == OP_2MUL ||
                opcode == OP_2DIV ||
                opcode == OP_MUL ||
                opcode == OP_DIV ||
                opcode == OP_MOD ||
                opcode == OP_LSHIFT ||
                opcode == OP_RSHIFT)
                return false; // Disabled opcodes.

            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
                stack.push_back(vchPushValue);
            else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
            switch (opcode)
            {
                //
                // Push value
                //
                case OP_1NEGATE:
                case OP_1:
                case OP_2:
                case OP_3:
                case OP_4:
                case OP_5:
                case OP_6:
                case OP_7:
                case OP_8:
                case OP_9:
                case OP_10:
                case OP_11:
                case OP_12:
                case OP_13:
                case OP_14:
                case OP_15:
                case OP_16:
                {
                    // ( -- value)
                    CScriptNum bn((int)opcode - (int)(OP_1 - 1));
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Control
                //
                case OP_NOP:
                case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
                case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
                break;

                case OP_IF:
                case OP_NOTIF:
                {
                    // <expression> if [statements] [else [statements]] endif
                    bool fValue = false;
                    if (fExec)
                    {
                        if (stack.size() < 1)
                            return false;
                        valtype& vch = stacktop(-1);
                        fValue = CastToBool(vch);
                        if (opcode == OP_NOTIF)
                            fValue = !fValue;
                        popstack(stack);
                    }
                    vfExec.push_back(fValue);
                }
                break;

                case OP_ELSE:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.back() = !vfExec.back();
                }
                break;

                case OP_ENDIF:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.pop_back();
                }
                break;

                case OP_VERIFY:
                {
                    // (true -- ) or
                    // (false -- false) and return
                    if (stack.size() < 1)
                        return false;
                    bool fValue = CastToBool(stacktop(-1));
                    if (fValue)
                        popstack(stack);
                    else
                        return false;
                }
                break;

                case OP_RETURN:
                {
                    return false;
                }
                break;


                //
                // Stack ops
                //
                case OP_TOALTSTACK:
                {
                    if (stack.size() < 1)
                        return false;
                    altstack.push_back(stacktop(-1));
                    popstack(stack);
                }
                break;

                case OP_FROMALTSTACK:
                {
                    if (altstack.size() < 1)
                        return false;
                    stack.push_back(altstacktop(-1));
                    popstack(altstack);
                }
                break;

                case OP_2DROP:
                {
                    // (x1 x2 -- )
                    if (stack.size() < 2)
                        return false;
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_2DUP:
                {
                    // (x1 x2 -- x1 x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch1 = stacktop(-2);
                    valtype vch2 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_3DUP:
                {
                    // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
                    if (stack.size() < 3)
                        return false;
                    valtype vch1 = stacktop(-3);
                    valtype vch2 = stacktop(-2);
                    valtype vch3 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                    stack.push_back(vch3);
                }
                break;

                case OP_2OVER:
                {
                    // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    valtype vch1 = stacktop(-4);
                    valtype vch2 = stacktop(-3);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2ROT:
                {
                    // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
                    if (stack.size() < 6)
                        return false;
                    valtype vch1 = stacktop(-6);
                    valtype vch2 = stacktop(-5);
                    stack.erase(stack.end()-6, stack.end()-4);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2SWAP:
                {
                    // (x1 x2 x3 x4 -- x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    swap(stacktop(-4), stacktop(-2));
                    swap(stacktop(-3), stacktop(-1));
                }
                break;

                case OP_IFDUP:
                {
                    // (x - 0 | x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    if (CastToBool(vch))
                        stack.push_back(vch);
                }
                break;

                case OP_DEPTH:
                {
                    // -- stacksize
                    CScriptNum bn(stack.size());
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_DROP:
                {
                    // (x -- )
                    if (stack.size() < 1)
                        return false;
                    popstack(stack);
                }
                break;

                case OP_DUP:
                {
                    // (x -- x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.push_back(vch);
                }
                break;

                case OP_NIP:
                {
                    // (x1 x2 -- x2)
                    if (stack.size() < 2)
                        return false;
                    stack.erase(stack.end() - 2);
                }
                break;

                case OP_OVER:
                {
                    // (x1 x2 -- x1 x2 x1)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-2);
                    stack.push_back(vch);
                }
                break;

                case OP_PICK:
                case OP_ROLL:
                {
                    // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
                    // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
                    if (stack.size() < 2)
                        return false;
                    int n = CScriptNum(stacktop(-1)).getint();
                    popstack(stack);
                    if (n < 0 || n >= (int)stack.size())
                        return false;
                    valtype vch = stacktop(-n-1);
                    if (opcode == OP_ROLL)
                        stack.erase(stack.end()-n-1);
                    stack.push_back(vch);
                }
                break;

                case OP_ROT:
                {
                    // (x1 x2 x3 -- x2 x3 x1)
                    //  x2 x1 x3  after first swap
                    //  x2 x3 x1  after second swap
                    if (stack.size() < 3)
                        return false;
                    swap(stacktop(-3), stacktop(-2));
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_SWAP:
                {
                    // (x1 x2 -- x2 x1)
                    if (stack.size() < 2)
                        return false;
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_TUCK:
                {
                    // (x1 x2 -- x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.insert(stack.end()-2, vch);
                }
                break;


                case OP_SIZE:
                {
                    // (in -- in size)
                    if (stack.size() < 1)
                        return false;
                    CScriptNum bn(stacktop(-1).size());
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Bitwise logic
                //
                case OP_EQUAL:
                case OP_EQUALVERIFY:
                //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
                {
                    // (x1 x2 - bool)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    bool fEqual = (vch1 == vch2);
                    // OP_NOTEQUAL is disabled because it would be too easy to say
                    // something like n != 1 and have some wiseguy pass in 1 with extra
                    // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
                    //if (opcode == OP_NOTEQUAL)
                    //    fEqual = !fEqual;
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fEqual ? vchTrue : vchFalse);
                    if (opcode == OP_EQUALVERIFY)
                    {
                        if (fEqual)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;


                //
                // Numeric
                //
                case OP_1ADD:
                case OP_1SUB:
                case OP_NEGATE:
                case OP_ABS:
                case OP_NOT:
                case OP_0NOTEQUAL:
                {
                    // (in -- out)
                    if (stack.size() < 1)
                        return false;
                    CScriptNum bn(stacktop(-1));
                    switch (opcode)
                    {
                    case OP_1ADD:       bn += bnOne; break;
                    case OP_1SUB:       bn -= bnOne; break;
                    case OP_NEGATE:     bn = -bn; break;
                    case OP_ABS:        if (bn < bnZero) bn = -bn; break;
                    case OP_NOT:        bn = (bn == bnZero); break;
                    case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
                    default:            assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_ADD:
                case OP_SUB:
                case OP_BOOLAND:
                case OP_BOOLOR:
                case OP_NUMEQUAL:
                case OP_NUMEQUALVERIFY:
                case OP_NUMNOTEQUAL:
                case OP_LESSTHAN:
                case OP_GREATERTHAN:
                case OP_LESSTHANOREQUAL:
                case OP_GREATERTHANOREQUAL:
                case OP_MIN:
                case OP_MAX:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    CScriptNum bn1(stacktop(-2));
                    CScriptNum bn2(stacktop(-1));
                    CScriptNum bn(0);
                    switch (opcode)
                    {
                    case OP_ADD:
                        bn = bn1 + bn2;
                        break;

                    case OP_SUB:
                        bn = bn1 - bn2;
                        break;

                    case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
                    case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
                    case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
                    case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
                    case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
                    case OP_LESSTHAN:            bn = (bn1 < bn2); break;
                    case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
                    case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
                    case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
                    case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
                    case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
                    default:                     assert(!"invalid opcode"); break;
                    }
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(bn.getvch());

                    if (opcode == OP_NUMEQUALVERIFY)
                    {
                        if (CastToBool(stacktop(-1)))
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_WITHIN:
                {
                    // (x min max -- out)
                    if (stack.size() < 3)
                        return false;
                    CScriptNum bn1(stacktop(-3));
                    CScriptNum bn2(stacktop(-2));
                    CScriptNum bn3(stacktop(-1));
                    bool fValue = (bn2 <= bn1 && bn1 < bn3);
                    popstack(stack);
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fValue ? vchTrue : vchFalse);
                }
                break;


                //
                // Crypto
                //
                case OP_RIPEMD160:
                case OP_SHA1:
                case OP_SHA256:
                case OP_HASH160:
                case OP_HASH256:
                {
                    // (in -- hash)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
                    if (opcode == OP_RIPEMD160)
                        CRIPEMD160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_SHA1)
                        CSHA1().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_SHA256)
                        CSHA256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_HASH160)
                        CHash160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    else if (opcode == OP_HASH256)
                        CHash256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
                    popstack(stack);
                    stack.push_back(vchHash);
                }
                break;

                case OP_CODESEPARATOR:
                {
                    // Hash starts after the code separator
                    pbegincodehash = pc;
                }
                break;

                case OP_CHECKSIG:
                case OP_CHECKSIGVERIFY:
                {
                    // (sig pubkey -- bool)
                    if (stack.size() < 2)
                        return false;

                    valtype& vchSig    = stacktop(-2);
                    valtype& vchPubKey = stacktop(-1);

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signature, since there's no way for a signature to sign itself
                    scriptCode.FindAndDelete(CScript(vchSig));

                    bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
                        CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);

                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
                    if (opcode == OP_CHECKSIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_CHECKMULTISIG:
                case OP_CHECKMULTISIGVERIFY:
                {
                    // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)

                    int i = 1;
                    if ((int)stack.size() < i)
                        return false;

                    int nKeysCount = CScriptNum(stacktop(-i)).getint();
                    if (nKeysCount < 0 || nKeysCount > 20)
                        return false;
                    nOpCount += nKeysCount;
                    if (nOpCount > 201)
                        return false;
                    int ikey = ++i;
                    i += nKeysCount;
                    if ((int)stack.size() < i)
                        return false;

                    int nSigsCount = CScriptNum(stacktop(-i)).getint();
                    if (nSigsCount < 0 || nSigsCount > nKeysCount)
                        return false;
                    int isig = ++i;
                    i += nSigsCount;
                    if ((int)stack.size() < i)
                        return false;

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signatures, since there's no way for a signature to sign itself
                    for (int k = 0; k < nSigsCount; k++)
                    {
                        valtype& vchSig = stacktop(-isig-k);
                        scriptCode.FindAndDelete(CScript(vchSig));
                    }

                    bool fSuccess = true;
                    while (fSuccess && nSigsCount > 0)
                    {
                        valtype& vchSig    = stacktop(-isig);
                        valtype& vchPubKey = stacktop(-ikey);

                        // Check signature
                        bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
                            CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);

                        if (fOk) {
                            isig++;
                            nSigsCount--;
                        }
                        ikey++;
                        nKeysCount--;

                        // If there are more signatures left than keys left,
                        // then too many signatures have failed
                        if (nSigsCount > nKeysCount)
                            fSuccess = false;
                    }

                    // Clean up stack of actual arguments
                    while (i-- > 1)
                        popstack(stack);

                    // A bug causes CHECKMULTISIG to consume one extra argument
                    // whose contents were not checked in any way.
                    //
                    // Unfortunately this is a potential source of mutability,
                    // so optionally verify it is exactly equal to zero prior
                    // to removing it from the stack.
                    if (stack.size() < 1)
                        return false;
                    if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
                        return error("CHECKMULTISIG dummy argument not null");
                    popstack(stack);

                    stack.push_back(fSuccess ? vchTrue : vchFalse);

                    if (opcode == OP_CHECKMULTISIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                default:
                    return false;
            }

            // Size limits
            if (stack.size() + altstack.size() > 1000)
                return false;
        }
    }
    catch (...)
    {
        return false;
    }

    if (!vfExec.empty())
        return false;

    return true;
}
Example #7
0
    Value ParseFactor()
    {
        switch (lex.token)
        {
            case T_INT:   { int i    = atoi(lex.sattr.c_str()); lex.Next(); return Value(i); }
            case T_FLOAT: { double f = atof(lex.sattr.c_str()); lex.Next(); return Value((float)f); }
            case T_STR:   { string s = lex.sattr;               lex.Next(); auto str = g_vm->NewString(s);
                                                                            allocated.push_back(str);
                                                                            return Value(str); }     
            case T_NIL:   {                                     lex.Next(); return Value(0, V_NIL); }

            case T_MINUS:
            {
                lex.Next(); 
                Value v = ParseFactor();
                switch (v.type)
                {
                    case V_INT:   v.ival *= -1; break;
                    case V_FLOAT: v.fval *= -1; break;
                    default: lex.Error("numeric value expected");
                }
                return v;
            }

            case T_LEFTBRACKET:
            {
                lex.Next();
                Gobble(T_LINEFEED);
                vector<Value> elems;
                if (lex.token == T_RIGHTBRACKET) lex.Next();
                else
                {
                    for (;;)
                    {
                        elems.push_back(ParseFactor());
                        bool haslf = lex.token == T_LINEFEED;
                        if (haslf) lex.Next();
                        if (lex.token == T_RIGHTBRACKET) break;
                        if (!haslf) Expect(T_COMMA);
                    }
                    lex.Next();
                }

                int type = -1;
                if (lex.token == T_COLON)
                {
                    lex.Next();
                    string sname = lex.sattr;
                    Expect(T_IDENT);
                    size_t reqargs = 0;
                    int idx = g_vm->StructIdx(sname, reqargs);
                    if (idx >= 0)   // if unknown type, becomes regular vector
                    {
                        // pad with NIL if current type has more fields
                        while (elems.size() < reqargs) { elems.push_back(Value(0, V_NIL)); }
                        // drop elements if current type has less fields
                        while (elems.size() > reqargs) { elems.back().DEC(); elems.pop_back(); }
                        type = idx;
                    }
                }

                auto vec = g_vm->NewVector(elems.size(), type);
                allocated.push_back(vec);
                for (auto &e : elems) vec->push(e.INC());
                return Value(vec);
            }

            default:
                lex.Error("illegal start of expression: " + lex.TokStr());
                return Value();
        }
    }
Example #8
0
		unsigned int push_object(const PlaneObject& obj)
		{
			objects.push_back(PlaneObjectInSpace(obj));
			return objects.size()-1;
		}
Example #9
0
		unsigned int push_object(const PlaneObject& obj, double x, double y, double z)
		{
			objects.push_back(PlaneObjectInSpace(obj, Coordenate(x,y,z)));
			return objects.size()-1;
		}
// @@@ Note:
// The only criteria we apply for these points is that they are
// on or within the boundary and not too close to a corner or to
// each other. However, these may not make useful triangles if
// too close to an edge. Deeper in the interior may be better.
//
static void SetInternalVertices(
	vector<vertex>			&vinside,
	vector<uint8>			&map,
	int						w,
	int						h,
	const vector<lineseg>	&edges,
	int						rclear,
	FILE*					flog )
{
/* --------------------------------------------- */
/* Clear map in neighborhood of existing corners */
/* --------------------------------------------- */

	int	ne = edges.size(),
		np = w * h;

	for( int i = 0; i < ne; ++i )
		RemoveFromMap( map, w, h, edges[i].v[0], rclear );

/* ----------------------------------- */
/* Find well-separated internal points */
/* ----------------------------------- */

	for( int i = 0; i < np; ++i ) {

		if( map[i] ) {

			/* -------------------------------------------- */
			/* Clear neighborhood around prospective vertex */
			/* -------------------------------------------- */

			int	y = i / w;
			int	x = i - w * y;

			fprintf( flog,
			"Add internal vertex at (%4d %4d).\n", x, y );

			vertex	newv( x, y );

			RemoveFromMap( map, w, h, newv, rclear );

			/* -------------------------- */
			/* Apply simple 'inside' test */
			/* -------------------------- */

			// Make guaranteed outside point and count edge
			// crossings from there to proposed inside point.

			vertex	outside( -10, y );

			int	m = CountCrossings( edges, newv, outside );

			if( m & 1 )
				vinside.push_back( newv );
			else if( m ) {

				fprintf( flog,
				"Warning: Supposedly internal point is outside"
				" - %d crossings. Continuing.\n", m );
			}
		}
	}
}
Example #11
0
		unsigned int push_object(const PlaneObject& obj, const Coordenate& pos)
		{
			objects.push_back(PlaneObjectInSpace(obj, pos));
			return objects.size()-1;
		}
// Divide bounding box B into regular array of triangles.
// Fill in vector of triangles and control points.
//
// Return 0 always (no error).
//
int MeshCreateX(
	vector<triangle>	&tri,
	vector<vertex>		&ctl,
	const vector<Point>	&pts,
	const IBox			&B,
	FILE*				flog )
{
	clock_t	t0 = StartTiming();

	tri.clear();
	ctl.clear();

/* --------------- */
/* Regular spacing */
/* --------------- */

	double	Dx	= GBL.mch.MNL,
			Dy	= GBL.mch.MNL;
	int		Lx	= B.R - B.L,
			Ly	= B.T - B.B,
			Nx,
			Ny;

	if( !Dx || Dx >= Lx ) {
		Nx = 1;
		Dx = Lx;
	}
	else {
		Nx = int(ceil( Lx / Dx ));
		Dx = Lx / Nx;
	}

	if( !Dy || Dy >= Ly ) {
		Ny = 1;
		Dy = Ly;
	}
	else {
		Ny = int(ceil( Ly / Dy ));
		Dy = Ly / Ny;
	}

/* ----------------------------------------- */
/* Reduce tri count while Atri > GBL.mch.MTA */
/* ----------------------------------------- */

	if( GBL.A.z != GBL.B.z ) {

		while( Nx*Ny > 1 && (Lx*Ly) / (Nx*Ny * 2) < GBL.mch.MTA ) {

			if( Nx >= Ny )
				Dx = Lx / --Nx;
			else
				Dy = Ly / --Ny;
		}
	}

/* ----------------------- */
/* Report basic grid specs */
/* ----------------------- */

	fprintf( flog, "Lx Dx Nx: %5d %8.2f %3d\n", Lx, Dx, Nx );
	fprintf( flog, "Ly Dy Ny: %5d %8.2f %3d\n", Ly, Dy, Ny );

/* ---------- */
/* Create ctl */
/* ---------- */

	for( int iy = 0; iy <= Ny; ++iy ) {

		int	y = (iy < Ny ? B.B + int(iy*Dy) : B.T);

		for( int ix = 0; ix <= Nx; ++ix ) {

			int	x = (ix < Nx ? B.L + int(ix*Dx) : B.R);

			ctl.push_back( vertex( x, y ) );
		}
	}

/* ---------- */
/* Create tri */
/* ---------- */

	int	w = Nx + 1;

	for( int iy = 0; iy < Ny; ++iy ) {

		for( int ix = 0; ix < Nx; ++ix ) {

			triangle	t;

			t.v[0] = ix + w * iy;
			t.v[1] = t.v[0] + 1;
			t.v[2] = t.v[0] + w;
			tri.push_back( t );

			t.v[0] = t.v[2];
			t.v[2] = t.v[0] + 1;
			tri.push_back( t );
		}
	}

/* ---------------- */
/* Remove empty tri */
/* ---------------- */

	const double	occ = 0.75;

	int	ntri = tri.size(),
		npnt = pts.size();

// map pts into their triangles

	vector<int>	in( ntri, 0 );

	for( int i = 0; i < npnt; ++i ) {

		vertex	v( int(pts[i].x), int(pts[i].y) );

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

			const triangle& T = tri[j];

			if( InTriangle(
				ctl[T.v[0]], ctl[T.v[1]], ctl[T.v[2]], v ) ) {

				++in[j];
				break;
			}
		}
	}

// remove tri with low occupancy

	for( int i = ntri - 1; i >= 0; --i ) {

		const triangle&	T = tri[i];

		if( !in[i] ||
			in[i] <= occ * AreaOfTriangle(
			ctl[T.v[0]], ctl[T.v[1]], ctl[T.v[2]] ) ) {

			tri.erase( tri.begin() + i );
			--ntri;
		}
	}

/* ----------------------- */
/* Remove unreferenced ctl */
/* ----------------------- */

	if( ntri < in.size() ) {

		fprintf( flog,
		"\nOf %ld triangles, %d were above %3d%% occupancy.\n",
		in.size(), ntri, int(occ*100.0) );

		for( int i = ctl.size() - 1; i >= 0; --i ) {

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

				const triangle&	T = tri[j];

				if( T.v[0] == i || T.v[1] == i || T.v[2] == i )
					goto next_i;
			}

			// not ref'd

			ctl.erase( ctl.begin() + i );

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

				triangle&	T = tri[j];

				if( T.v[0] > i ) --T.v[0];
				if( T.v[1] > i ) --T.v[1];
				if( T.v[2] > i ) --T.v[2];
			}
next_i:;
		}
	}

/* ------------ */
/* Final report */
/* ------------ */

	fprintf( flog,
	"\nSTAT: From %ld pts, got %ld triangles, %ld control points.\n",
	pts.size(), tri.size(), ctl.size() );

	StopTiming( flog, "MeshCreate", t0 );

	return 0;
}
Example #13
0
// create label for each vertex by Dijkstra algorithm on extended graphs;
void HD::findPath(VertexID source, VertexID target, vector<VertexID>& path, double& d){
	if (source == target) {
		path.push_back(source);
		return;
	}
	
	//cout << "Test: source = " << source << ", target = " << target << "." << endl; 
	int nodesize = graph.num_vertices();
	
	vector<double> dist (nodesize);
	for (int vid = 0; vid < nodesize; vid++) dist[vid] = DBL_INFINITY;
	dist[source] = 0.0;
	
	vector<VertexID> father(nodesize, numeric_limits<unsigned int>::max());
	
	priority_queue<pair<double, VertexID>, vector<pair<double, VertexID> >, QueueComp> Queue;
	Queue.push(make_pair(0.0, source));
	
	VertexList nodelist(nodesize);	
	for (int vid = 0; vid < nodesize; vid++) {
		nodelist[vid].flaga = false;
		// nodelist[vid].rank = graph[vid].rank;
	}
	
	int i = 0;
	while (Queue.size() > 0) {
		//cout << i++ << endl;
		double min_dist = Queue.top().first;
		VertexID vid = Queue.top().second;
		//cout << "vid = " << vid << ", min_dist = " << min_dist << endl;

		Queue.pop();
		if (min_dist > dist[vid]) {/*cout << "Greater!?" << endl;*/ continue;} // lazy update; 
		else nodelist[vid].flaga = true; // settle vertex vid;
		
		if (vid == target) break; // find the target node;
		
		forall_outneighbors(graph, vid, eit){
			if (nodelist[eit->target].flaga) continue; // settled;
			// if (/*vid != source &&*/ nodelist[eit->target].rank < nodelist[vid].rank) continue;
			if (dist[eit->target] > min_dist + eit->weight) {
				dist[eit->target] = min_dist + eit->weight;
				Queue.push(make_pair(dist[eit->target], eit->target)); 
				father[eit->target] = vid;
			}	
		}
		
		// forall_outshortcuts(graph, vid, eit){
			// if (nodelist[eit->target].flaga) continue; // settled;
			// if (/*vid != source &&*/ nodelist[eit->target].rank < nodelist[vid].rank) continue;			
			// if (dist[eit->target] > min_dist + eit->weight) {
				// dist[eit->target] = min_dist + eit->weight;
				// Queue.push(make_pair(dist[eit->target], eit->target)); 
				// father[eit->target] = vid;
			// }	
		// }		
	}
	
	// create path information for unpacking path;
	vector<VertexID>(0).swap(path);
	path.push_back(target);
	int index = target;	
	while (index != source){
		if (father[index] != numeric_limits<unsigned int>::max()) {
			path.push_back(father[index]);
			index = father[index];
		}else break;
	}
	
	if (path.size()==1) path.push_back(source);
	
	// for test;
	for (int i = path.size()-1; i > 0; i--){
		int a = path[i];
		int b = path[i-1];
		forall_outneighbors(graph, a, eit){
			if (eit->target == b){
				d += eit->weight;
				break;
			}
		}
	}
	// cout << "d = " << d << endl;
	
	// cout << "father: " << endl;
	// for (int i = 0; i < father.size(); i++) {
		// cout << i << ": " << father[i] << endl;
	// }
	
	// cout << "~~~~~" << endl;
	// for (int i = path.size()-1; i >= 0; i--){
		// cout << path[i] << " ";
	// }
	// cout << endl;
}
Example #14
0
void RegisterMouseControls(MouseControls* controls){
	mouseControls.push_back(controls);
	UpdateMice();
}
Example #15
0
 void advance() { pos++; if (tape.size() <= pos) tape.push_back(0); }
Example #16
0
void Table::getColumnReferences(Column *column, vector<TableObject *> &refs, bool exclusion_mode)
{
	if(column && !column->isAddedByRelationship())
	{
		unsigned count, i;
		IndexElement elem;
		Column *col=nullptr, *col1=nullptr;
		vector<TableObject *>::iterator itr, itr_end;
		bool found=false;
		Index *ind=nullptr;
		Constraint *constr=nullptr;
		Trigger *trig=nullptr;

		itr=indexes.begin();
		itr_end=indexes.end();

		while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !found)))
		{
			ind=dynamic_cast<Index *>(*itr);
			itr++;

			count=ind->getIndexElementCount();
			for(i=0; i < count  && (!exclusion_mode || (exclusion_mode && !found)); i++)
			{
				elem=ind->getIndexElement(i);
				col=elem.getColumn();
				if(col && col==column)
				{
					found=true;
					refs.push_back(ind);
				}
			}
		}

		itr=constraints.begin();
		itr_end=constraints.end();

		while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !found)))
		{
			constr=dynamic_cast<Constraint *>(*itr);
			itr++;

			col=constr->getColumn(column->getName(),true);
			col1=constr->getColumn(column->getName(),false);

			if((col && col==column) || (col1 && col1==column))
			{
				found=true;
				refs.push_back(constr);
			}
		}

		itr=triggers.begin();
		itr_end=triggers.end();

		while(itr!=itr_end && (!exclusion_mode || (exclusion_mode && !found)))
		{
			trig=dynamic_cast<Trigger *>(*itr);
			itr++;

			count=trig->getColumnCount();
			for(i=0; i < count && (!exclusion_mode || (exclusion_mode && !found)); i++)
			{
				if(trig->getColumn(i)==column)
				{
					found=true;
					refs.push_back(trig);
				}
			}
		}
	}
}
Example #17
0
	void setdesc(string wrd)
	{description->push_back(wrd);}
Example #18
0
void addedge(int u,int v,int w){
	es.push_back(edge(u,v,w));
	g[u].push_back(es.size()-1);
}
int main() {
    int testcases;
    cin >> testcases;
    for (int i = 0; i < testcases; i++) {
        int pirateland;
        cin >> pirateland;
        for (int j = 0; j < pirateland; j++) {
            int times;
            cin >> times;
            string land;
            cin >> land;
            for (int k = 0; k < times; k++) {
                for (int l = 0; l < land.size(); l++)
                    tab.push_back((land[l] == '1'));
            }
        }
        sort(tab.begin(), tab.end());
        root = build(0, tab.size());
        int queries;
        cin >> queries;
        cout << queries << endl;
        int s = 1;
        for (int j = 0; j < queries; j++) {
            char l;
            int a, b;
            cin >> l >> a >> b;
            if (l == 'F') {
                cout << "F access" << endl;
                for (int k = a; k < b; k++) {
                    tab[k] = true;
                }
                lazy(root, a, b);
            }
            if (l == 'E') {
                cout << "E access" << endl;
                for (int k = a; k < b; k++) {
                    tab[k] = false;
                }
                lazy(root, a, b);
            }
            if (l == 'I') {
                cout << "I access" << endl;
                for (int k = a; k < b; k++) {
                    tab[k] = !tab[k];
                }
                lazy(root, a, b);
                //inverse pirates
            }
            if (l == 'S') {
                cout << "S access" << endl;
                propagate(root, a, b);
                //how many buccanneer from i to j
                cout << "Q" << (s++) << ": " << query(root, a, b) << endl;
            }
            for (auto s : tab)
                cout << s << " ";
            cout << endl;
            cout << root->r->val << endl;
        }
    }
}
Example #20
0
bool ConfigManagerImp::registerConfig(ConfigResetCallBack fun)
{
    registerCallbacks.push_back(fun);
    return true;
}
int main(int argc, char** argv){
	srand((unsigned)time(NULL));
	double min_stay_dur = 300;
	
	string file_name1 = "SampleStayRegion.txt";
	string file_name3 = "RankProbability.txt";

	//the input file 
	ifstream fid_in;
	fid_in.open(file_name1.c_str(), ifstream::in);
	//the output file
	FILE * fout_id2;
	fout_id2 = fopen(file_name3.c_str(), "w");

	int SSlot[96][2]={0};
	string tline;
	double num1;
	double num2;
	double num3;
	double num4;
	double num5;
	int num1_int;
	int num2_int;
	int num3_int;
	int counter = 0;
	int per_count;
	double hour_bos;
	int place_count;
	int home_count[10000] = { 0 };
	int work_count[10000] = { 0 };
	int total_count[10000] = { 0 };
	double place_lon[10000] = { 0 };
	double place_lat[10000] = { 0 };
	int home;
	int work;
	int home_num;
	int second_home_num;
	int work_num;
	double home_work_dist;
	double work_product;
	int week_day;
	int home_valid_sign;
	int work_valid_sign;
	int person_id;
	

	while (getline(fid_in, tline)){
		stringstream parse_line(tline);
		parse_line >> num1_int >> num2_int >> num3_int >> person_id;
		per_count = num2_int;
		place_count = num3_int;
		for (int i = 0; i<10000; i++){
			home_count[i] = 0;
			work_count[i] = 0;
			total_count[i] = 0;
		}
	
		counter++;

		//read in data and identify home and work
		for (int i = 0; i<per_count; i++){
			getline(fid_in, tline);
			stringstream parse_line(tline);
			parse_line >> num1_int >> num2_int >> num3_int >> num4 >> num5;
			if (num3_int>min_stay_dur){
				lons.push_back(num4);
				lats.push_back(num5);
				times.push_back(num2_int);
				durations.push_back(num3_int);
				locs.push_back(num1_int - 1); //location start with 0
				hour_bos = ((num2_int % 86400) / 3600.0) - 5;
				if (hour_bos<0){
					hour_bos += 24;
				}
				//1970/1/1 is a Thursday
				//From 0 to 6, Monday is 0.
				week_day = (int)(((num2_int - 18000) % 604800) / 86400.0) + 3;
				if (week_day>6){
					week_day -= 7;
				}
				
				total_count[num1_int - 1]++;
				if ((hour_bos<8 || hour_bos>19) && week_day<5 || week_day>5){
					home_count[num1_int - 1]++;
				}
				if (hour_bos>8 && hour_bos<19 && week_day<5){
					work_count[num1_int - 1]++;
				}
				place_lon[num1_int - 1] = num4;
				place_lat[num1_int - 1] = num5;
			}
		}
		home_num = -1;
		work_num = -1;
		second_home_num = -1;
		home = -1;
		work = -1;
		work_product = -1;
		home_work_dist = -1;
		home_valid_sign = 0;
		work_valid_sign = 0;
		for (int i = 0; i<place_count; i++){
			if (home_count[i]>home_num){
				second_home_num = home_num;
				home_num = home_count[i];
				home = i;
				if (home_num >= min_home_count){
					home_valid_sign = 1;
				}
			}
		}
		
		//only one significant home location
		if (second_home_num > home_num * second_home_ratio){
			home_valid_sign = 0;
		}
		
		//original criteria
		if (home_valid_sign == 1){
			
			//if there are too many night departures
			night_departure_count = 0;
			for (int i = 0; i < per_count; i++){
				if (locs[i]!=home){
					int eslot = ((((int)(times[i] + durations[i])) - 18000) % 86400) / 900;
					int sday = (((int)times[i]) - 18000) / 86400;
					int eday = (((int)(times[i] + durations[i])) - 18000) / 86400;
					if (eslot > night_begin_time || sday != eday){
						night_departure_count++;
					}
				}
			}
			if (night_departure_count > per_count * departure_night_ratio){
				home_valid_sign = 0;
				continue;
			}
			
	
			counter1++;
			for (int i = 0; i<place_count; i++){
				if (i != home && work_count[i] * distance(place_lat[home], place_lon[home], place_lat[i], place_lon[i], 'K')>work_product){
					work_product = work_count[i] * distance(place_lat[home], place_lon[home], place_lat[i], place_lon[i], 'K');
					work_num = work_count[i];
					home_work_dist = distance(place_lat[home], place_lon[home], place_lat[i], place_lon[i], 'K');
					work = i;
					if (work_num >= min_work_count && home_work_dist>min_home_work_dist){
						work_valid_sign = 1;
					}
					else{
						work_valid_sign = 0;
					}
				}
			}
		}
		if (!work_valid_sign){
			work = -1;
		}
		else{
			counter2++;
		}
		

		if (!home_valid_sign ){
			continue;
		}
		

		
		if (place_lat[home]>min_lat && place_lat[home]<max_lat && place_lon[home]>min_lon && place_lon[home]<max_lon){
			selected_home_latlon[accept_count][0]=place_lat[home];
			selected_home_latlon[accept_count][1]=place_lon[home];
			other_begin_end_index[accept_count][0]=other_count;
			++accept_count;
			for (int i = 0; i<place_count; i++){
				if (place_lat[i]>min_lat_big && place_lat[i]<max_lat_big && place_lon[i]>min_lon_big && place_lon[i]<max_lon_big){
					if (i==home){
						
					}
					else{
						selected_other_latlon[other_count][0]=place_lat[i];
						selected_other_latlon[other_count][1]=place_lon[i];
						other_visit_count[other_count]=total_count[i];
						
						++other_count;
					}
				}
			}
		}
		if (accept_count==PERNUM){
			break;
		}

		lons.clear();
		lats.clear();
		times.clear();
		durations.clear();
		locs.clear();
	}
	
	for (int i=0;i<PERNUM-1;i++){
		other_begin_end_index[i][1]=other_begin_end_index[i+1][0]-1;
	}
	other_begin_end_index[PERNUM][1]=other_count-1;

	
	cout<<"calculating home other distance"<<endl;
	double dist_sum;
	//distance between each home point and other location
	for (int i=0;i<PERNUM;i++){
		if (i%100==0){
			cout<<i<<endl;
		}
		dist_vec.clear();
		count_vec.clear();
		dist_sum=0;
		for (int j=0;j<other_count;j++){
			double dist_ =distance(selected_home_latlon[i][0], selected_home_latlon[i][1], selected_other_latlon[j][0], selected_other_latlon[j][1], 'K');	
			dist_sum+=dist_;
			dist_vec.push_back(make_pair(dist_,j));
			count_vec.push_back(make_pair(dist_,other_visit_count[j]));
		}
		sort(dist_vec.begin(),dist_vec.end(),sort_pred());
		sort(count_vec.begin(),count_vec.end(),sort_pred());
		int person_begin=other_begin_end_index[i][0];
		int person_end=other_begin_end_index[i][1];
		for (int j=0;j<other_count;j++){
			if (dist_vec[j].second>=person_begin&&dist_vec[j].second<=person_end){
				home_other_rank_sum[j]++;
				home_other_rank_sum_weighted[j]+=count_vec[j].second;
				home_other_rank_count++;
			}
		}
	}
	
	//output result

	for (int i=0;i<other_count;i++){
		fprintf(fout_id2, "%f ", home_other_rank_sum_weighted[i]);
	}
	fprintf(fout_id2, "\n");
	
	return 0;
}
Example #22
0
 Parser(Context& ctx, string path, size_t line)
 : ctx(ctx), stack(vector<Syntactic_Context>()),
   source(0), position(0), end(0), path(path), line(line)
 { stack.push_back(nothing); }
Example #23
0
int main(int argc, char **argv) {
  signal(SIGPIPE, SIG_IGN);
  setbuf(stdout, NULL);
  CDnsSeedOpts opts;
  opts.ParseCommandLine(argc, argv);
  nP2Port = opts.nP2Port;
  vSeeds.reserve(vSeeds.size() + opts.vSeeds.size());
  vSeeds.insert(vSeeds.end(), opts.vSeeds.begin(), opts.vSeeds.end());
  if (opts.vSeeds.empty()) {
    vSeeds.push_back("kjy2eqzk4zwi5zd3.onion");
    vSeeds.push_back("dnsseed.bluematt.me");
    vSeeds.push_back("bitseed.xf2.org");
    vSeeds.push_back("dnsseed.bitcoin.dashjr.org");
    vSeeds.push_back("seed.bitcoin.sipa.be");
  }
  if (opts.tor) {
    CService service(opts.tor, 9050);
    if (service.IsValid()) {
      printf("Using Tor proxy at %s\n", service.ToStringIPPort().c_str());
      SetProxy(NET_TOR, service);
    }
  }
  bool fDNS = true;
  if (!opts.ns) {
    printf("No nameserver set. Not starting DNS server.\n");
    fDNS = false;
  }
  if (fDNS && !opts.host) {
    fprintf(stderr, "No hostname set. Please use -h.\n");
    exit(1);
  }
  FILE *f = fopen("dnsseed.dat","r");
  if (f) {
    printf("Loading dnsseed.dat...");
    CAutoFile cf(f);
    cf >> db;
    if (opts.fWipeBan)
        db.banned.clear();
    if (opts.fWipeIgnore)
        db.ResetIgnores();
    printf("done\n");
  }
  pthread_t threadDns, threadSeed, threadDump, threadStats;
  printf("Starting seeder...");
  pthread_create(&threadSeed, NULL, ThreadSeeder, NULL);
  printf("done\n");
  printf("Starting %i crawler threads...", opts.nThreads);
  for (int i=0; i<opts.nThreads; i++) {
    pthread_t thread;
    pthread_create(&thread, NULL, ThreadCrawler, NULL);
  }
  printf("done\n");
  pthread_create(&threadDump, NULL, ThreadDumper, NULL);
  if (fDNS) {
    printf("Starting %i DNS threads for %s on %s (port %i)...", opts.nDnsThreads, opts.host, opts.ns, opts.nPort);
    dnsThread.clear();
    for (int i=0; i<opts.nDnsThreads; i++) {
      dnsThread.push_back(new CDnsThread(&opts, i));
      pthread_create(&threadDns, NULL, ThreadDNS, dnsThread[i]);
      printf(".");
      Sleep(20);
    }
    printf("done\n");
  }
  pthread_create(&threadStats, NULL, ThreadStats, NULL);
  void* res;
  pthread_join(threadDump, &res);
  return 0;
}
Example #24
0
File: pbr.cpp Project: mrdooz/pbr
//---------------------------------------------------------------------------
void Init()
{
  backbuffer = new Buffer(windowSize.x, windowSize.y);

  float lumScale = 1.f;
  Color ballDiffuse(0.1f, 0.4f, 0.4f);
  Color ballSpec(0.2f, 0.2f, 0.2f);
  Color ballEmit(0.75f, 0.75f, 0.75f);

  Color planeDiffuse(0.5, 0, 0);
  Color planeSpec(0.1f, 0.1f, 0.1f);
  ballEmit = lumScale * ballEmit;
  Color zero(0, 0, 0);

#define LOAD_MESH 0

#if LOAD_MESH
  MeshLoader loader;
  loader.Load("gfx/crystals_flat.boba");

  for (const protocol::MeshBlob* meshBlob : loader.meshes)
  {
    for (u32 i = 0; i < meshBlob->numIndices; i += 3)
    {
      u32 idx0 = meshBlob->indices[i + 0];
      u32 idx1 = meshBlob->indices[i + 1];
      u32 idx2 = meshBlob->indices[i + 2];

      Vector3 p0 = { meshBlob->verts[idx0 * 3 + 0], meshBlob->verts[idx0 * 3 + 1], meshBlob->verts[idx0 * 3 + 2] };
      Vector3 p1 = { meshBlob->verts[idx1 * 3 + 0], meshBlob->verts[idx1 * 3 + 1], meshBlob->verts[idx1 * 3 + 2] };
      Vector3 p2 = { meshBlob->verts[idx2 * 3 + 0], meshBlob->verts[idx2 * 3 + 1], meshBlob->verts[idx2 * 3 + 2] };

      tris.push_back({ p0, p1, p2 });
    }
  }

#else
#if 1
  int numBalls = 10;
  for (u32 i = 0; i < numBalls; ++i)
  {
    float angle = i * 2 * Pi / numBalls;
    Geo* g = new Sphere(Vector3(10 * cosf(angle), 0, 30 + 10 * sinf(angle)), 2);
    if (i & 1)
      g->material = new Material(ballDiffuse, ballSpec, zero);
    else
      g->material = new Material(ballDiffuse, ballSpec, ballEmit);
    objects.push_back(g);
  }

  Geo* center = new Sphere(Vector3(0, 50, 30), 15);

  center->material = new Material(ballDiffuse, zero, ballEmit);
  objects.push_back(center);
#else
  {
    Geo* g = new Sphere(Vector3(-10, 10, 30), 7);
    g->material = new Material(ballDiffuse, ballSpec, ballEmit);
    objects.push_back(g);
  }

  {
    Geo* g = new Sphere(Vector3(0, 0, 30), 5);
    g->material = new Material(ballDiffuse, ballSpec, zero);
    objects.push_back(g);
  }

  {
    Geo* g = new Sphere(Vector3(10, 0, 30), 2);
    g->material = new Material(ballDiffuse, ballSpec, zero);
    objects.push_back(g);
  }
#endif

  Geo* plane = new Plane(Vector3(0, 1, 0), 0);
  plane->material = new Material(planeDiffuse, planeSpec, zero);
  objects.push_back(plane);

  for (Geo* g : objects)
  {
    if (g->material->emissive.Max3() > 0)
      emitters.push_back(g);
  }
#endif

}
Example #25
0
int Slave::getFileList(const string& path, vector<string>& filelist)
{
   string abs_path = m_strHomeDir + path;
   struct stat s;
   if (stat(abs_path.c_str(), &s) < 0)
      return -1;

   if (!S_ISDIR(s.st_mode))
   {
      filelist.push_back(path);
      return 1;
   }

   dirent **namelist;
   int n = scandir(abs_path.c_str(), &namelist, 0, alphasort);

   if (n < 0)
      return -1;

   for (int i = 0; i < n; ++ i)
   {
      // skip "." and ".."
      if ((strcmp(namelist[i]->d_name, ".") == 0) || (strcmp(namelist[i]->d_name, "..") == 0))
      {
         free(namelist[i]);
         continue;
      }

      // check file name
      bool bad = false;
      for (char *p = namelist[i]->d_name, *q = namelist[i]->d_name + strlen(namelist[i]->d_name); p != q; ++ p)
      {
         if ((*p == 10) || (*p == 13))
         {
            bad = true;
            break;
         }
      }
      if (bad)
         continue;

      if (stat((abs_path + "/" + namelist[i]->d_name).c_str(), &s) < 0)
         continue;

      // skip system file and directory
      if (S_ISDIR(s.st_mode) && (namelist[i]->d_name[0] == '.'))
      {
         free(namelist[i]);
         continue;
      }

      if (S_ISDIR(s.st_mode))
         getFileList(path + "/" + namelist[i]->d_name, filelist);
      else
         filelist.push_back(path + "/" + namelist[i]->d_name);

      free(namelist[i]);
   }
   free(namelist);

   filelist.push_back(path);

   return filelist.size();
}
Example #26
0
Value getworkex(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "getworkex [data, coinbase]\n"
            "If [data, coinbase] is not specified, returns extended work data.\n"
        );

    if (vNodes.empty())
        throw JSONRPCError(-9, "StealthCoin is not connected!");

    if (IsInitialBlockDownload())
        throw JSONRPCError(-10, "StealthCoin is downloading blocks...");

    typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
    static mapNewBlock_t mapNewBlock;
    static vector<CBlock*> vNewBlock;
    static CReserveKey reservekey(pwalletMain);

    if (params.size() == 0)
    {
        // Update block
        static unsigned int nTransactionsUpdatedLast;
        static CBlockIndex* pindexPrev;
        static int64 nStart;
        static CBlock* pblock;
        if (pindexPrev != pindexBest ||
            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
        {
            if (pindexPrev != pindexBest)
            {
                // Deallocate old blocks since they're obsolete now
                mapNewBlock.clear();
                BOOST_FOREACH(CBlock* pblock, vNewBlock)
                    delete pblock;
                vNewBlock.clear();
            }
            nTransactionsUpdatedLast = nTransactionsUpdated;
            pindexPrev = pindexBest;
            nStart = GetTime();

            // Create new block
            pblock = CreateNewBlock(pwalletMain);
            if (!pblock)
                throw JSONRPCError(-7, "Out of memory");
            vNewBlock.push_back(pblock);
        }

        // Update nTime
        pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
        pblock->nNonce = 0;

        // Update nExtraNonce
        static unsigned int nExtraNonce = 0;
        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);

        // Save
        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);

        // Prebuild hash buffers
        char pmidstate[32];
        char pdata[128];
        char phash1[64];
        FormatHashBuffers(pblock, pmidstate, pdata, phash1);

        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

        CTransaction coinbaseTx = pblock->vtx[0];
        std::vector<uint256> merkle = pblock->GetMerkleBranch(0);

        Object result;
        result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
        result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));

        CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
        ssTx << coinbaseTx;
        result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));

        Array merkle_arr;

        BOOST_FOREACH(uint256 merkleh, merkle) {
            merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
        }

        result.push_back(Pair("merkle", merkle_arr));


        return result;
    }
Example #27
0
 void addSuccessor(Node<T>& successor)
 {
     successors.push_back(successor);
 }
Example #28
0
 Tape() {
   pos = 0;
   tape.push_back(0);
 }
Example #29
0
template<class T>void scan(vector<T>& a, int n, istream& cin) { T c; REP(i, n) { cin >> c; a.push_back(c); } }
Example #30
0
//Функция выстрела
void Fire(vector<Bullet> &bullet, Player & p){

	Vector2f coordTurret = p.turret[1].position;
	
	bullet.push_back(Bullet(coordTurret, p.player, p.test.angle));
};