示例#1
0
文件: rule.cpp 项目: xurongs/unisdm
RuleMerge& RuleMerge::append(const Rule& rule)
{
	return append(rule.clone());
}
示例#2
0
int main(int argc, char *argv[]) {
    struct emokit_device* d;
    struct emokit_frame c;

    int32_t i, j, k, nsamp = 0, nblk=0, si=0, status = 0, verbose = 1;
    int32_t putdatrequestsize=0;
    long int elapsedusec=0, printtime=0;
    struct timeval starttime, curtime;
    host_t buffhost;

    /* these represent the acquisition system properties */
    int nchans         = NCHANS;
    int fsample        = FSAMPLE;
    int blocksize      = roundf(fsample/((float)BUFFRATE));
    int channamesize   = 0;
    char *labelsbuf    = NULL;

    /* these are used in the communication and represent statefull information */
    int serverfd             = -1;
    message_t     request;
    char          *requestbuf = NULL;
    data_t        data;
    emokit_samp_t *samples=NULL;
    message_t     *response = NULL;
    messagedef_t  responsedef;
    header_t      header;
    ft_chunkdef_t chunkdef; // for holding the channel names

    if ( argc==1 ) usage();
    if ( argc>1 && (strcmp(argv[1],"-help")==0 || strcmp(argv[1],"-h")==0) ) {
        usage();
        sig_handler(0);
    }

    if (argc>1) {
        char *fname=argv[1];
        int ci=0;
        /* find the which splits the host and port info */
        for (ci=0; fname[ci]!=0; ci++) {
            if ( fname[ci]==':' ) { /* parse the port info */
                buffhost.port=atoi(&(fname[ci+1]));
                break;
            }
        }
        memcpy(buffhost.name,fname,ci);
        buffhost.name[ci]=0; /* copy hostname out and null-terminate */
    }
    else {
        sprintf(buffhost.name, "%s", DEFAULT_HOSTNAME);
        buffhost.port = DEFAULT_PORT;
    }

    if (verbose>0) fprintf(stderr, "emokit2ft: buffer = %s:%d\n", buffhost.name,buffhost.port);

    if ( argc>2 ) {
        BUFFRATE = atoi(argv[2]);
        blocksize = (int)(roundf(fsample/((float)BUFFRATE)));
    }
    if (verbose>0) fprintf(stderr, "emokit2ft: BUFFRATE = %d\n", BUFFRATE);
    if (verbose>0) fprintf(stderr, "emokit2ft: blocksize = %d\n", blocksize);

    //-------------------------------------------------------------------------------
    // open the emotive device
    d = emokit_create();
    k = emokit_get_count(d, EMOKIT_VID, EMOKIT_PID);
    printf("Current epoc devices connected: %d\n", k);
    status=-1;
    if ( k>0 ) {
        for ( i=k-1; i>=0 & i<k; i--) {
            status = emokit_open(d, EMOKIT_VID, EMOKIT_PID, i);
            if(status == 0 ) {
                printf("Connected : %d:%d\n",i,status);
                break;
            } else {
                printf("CANNOT CONNECT: %d:%d\n", i,status);
            }
        }
    }
    if ( status != 0 ) {
        printf("Could not connect to any device\nDo you have permission to read from : /dev/hidrawX\nsee https://github.com/openyou/emokit/issues/89\n");
        return 1;
    }

    //-------------------------------------------------------------------------------
    /* allocate the elements that will be used in the buffer communication */
    request.def = malloc(sizeof(messagedef_t));
    request.buf = NULL;
    request.def->version = VERSION;
    request.def->bufsize = 0;

    header.def = malloc(sizeof(headerdef_t));
    header.buf = NULL; /* header buf contains the channel names */
    //header.buf = labels;

    /* define the header */
    header.def->nchans    = nchans;
    header.def->nsamples  = 0;
    header.def->nevents   = 0;
    header.def->fsample   = fsample;
    header.def->data_type = DATATYPE_EMOKIT;
    header.def->bufsize   = 0;

    //-------------------------------------------------------------------------------
    /* define the stuff for the channel names */
    /* compute the size of the channel names set */
    channamesize=0;
    for( i=0; i<nchans; i++) {
        for ( j=0; labels[i][j]!='\0'; j++);
        j++;
        channamesize+=j;
    }
    /* allocate the memory for the channel names, and copy them into
      it */
    labelsbuf = malloc(WORDSIZE_CHAR*channamesize);
    k=0;
    for( i=0; i<nchans; i++) {
        for ( j=0; labels[i][j]!='\0'; j++,k++) {
            labelsbuf[k]=labels[i][j];
        }
        labelsbuf[k]=labels[i][j];
        k++;
    }
    chunkdef.type = FT_CHUNK_CHANNEL_NAMES;
    chunkdef.size = k;
    // add this info to the header buffer
    header.def->bufsize = append(&header.buf, header.def->bufsize, &chunkdef, sizeof(ft_chunkdef_t));
    header.def->bufsize = append(&header.buf, header.def->bufsize, labelsbuf, chunkdef.size);

    //-------------------------------------------------------------------------------
    /* initialization phase, send the header */
    request.def->command = PUT_HDR;
    request.def->bufsize = append(&request.buf, request.def->bufsize, header.def, sizeof(headerdef_t));
    request.def->bufsize = append(&request.buf, request.def->bufsize, header.buf, header.def->bufsize);

    fprintf(stderr,"emokit2ft: Attempting to open connection to buffer....");
    while ( (serverfd = open_connection(buffhost.name,buffhost.port)) < 0 ) {
        fprintf(stderr, "emokit2ft; failed to create socket. waiting\n");
        usleep(1000000);/* sleep for 1second and retry */
    }
    fprintf(stderr,"done.\nSending header...");
    status = tcprequest(serverfd, &request, &response);
    if (status) {
        fprintf(stderr, "emokit2ft: put header error = %d\n",status);
        sig_handler(-1);
    }
    fprintf(stderr, "done\n");
    free(request.buf);
    free(request.def);
    if (response->def->command != PUT_OK) {
        fprintf(stderr, "emokit2ft: error in 'put header' request.\n");
        sig_handler(-1);
    }
    FREE(response->buf);
    free(response->def);
    free(response);

    /* add a small pause between writing header + first data block */
    usleep(200000);


    //-------------------------------------------------------------------------------
    /* allocate space for the putdata request as 1 block, this contains
      [ request_def data_def data ] */
    putdatrequestsize = sizeof(messagedef_t) + sizeof(datadef_t) + WORDSIZE_EMOKIT*nchans*blocksize;
    requestbuf  = malloc(putdatrequestsize);
    /* define the constant part of the send-data request and allocate space for the variable part */
    request.def = requestbuf ;
    request.buf = request.def + 1; /* N.B. cool pointer arithemetic trick for above! */
    request.def->version = VERSION;
    request.def->command = PUT_DAT;
    request.def->bufsize = putdatrequestsize - sizeof(messagedef_t);
    /* setup the data part of the message */
    data.def            = request.buf;
    data.buf            = data.def + 1; /* N.B. cool pointer arithemetic trick for above */
    samples             = data.buf;     /* version with correct type */
    /* define the constant part of the data */
    data.def->nchans    = nchans;
    data.def->nsamples  = blocksize;
    data.def->data_type = DATATYPE_EMOKIT;
    data.def->bufsize   = WORDSIZE_EMOKIT * nchans * blocksize;

    //-------------------------------------------------------------------------------
    // Loop sending the data in blocks as it becomes available
    gettimeofday(&starttime,NULL); /* get time we started to compute delay before next sample */
    while (1) {

        //-------------------------------------------------------------------------------
        for ( si=0; si<blocksize; si++) { // get a block's worth of samples
            // wait until new data to get, 4 milliSec N.B. inter-sample ~= 8 milliSec
            while( emokit_read_data(d)<=0 ) {
                usleep(2000);
            }
            /* get the new data */
            c = emokit_get_next_frame(d);
            if ( verbose>1 ) {
                printf("%5d) %5d\t%5d\t%5d\t%5d\t%5d\t%5d\n", nsamp, c.counter, c.gyroX, c.gyroY, c.F3, c.FC6, c.P7);
                fflush(stdout);
            }
            // copy the samples into the data buffer, in the order we
            // *said* they should be
            samples[(si*nchans)+0] =c.counter;
            samples[(si*nchans)+1] =(c.AF3 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+2] =(c.F7  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+3] =(c.F3  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+4] =(c.FC5 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+5] =(c.T7  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+6] =(c.P7  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+7] =(c.O1  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+8] =(c.O2  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+9] =(c.P8  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+10]=(c.T8  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+11]=(c.FC6 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+12]=(c.F4  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+13]=(c.F8  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+14]=(c.AF4 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+15]=c.gyroX;
            samples[(si*nchans)+16]=c.gyroY;
            nsamp+=1;/*nsamp; */
        }

        //-------------------------------------------------------------------------------
        /* send the data to the buffer */
        /* 0. If send data already read response to previous put-data */
        if ( nblk > 0 ) {
            if ( readresponse(serverfd,&responsedef) !=0 ||
                    responsedef.command != PUT_OK ) {
                fprintf(stderr,"emokit2ft: Error writing samples.\n");
            }
        }

        /* 1. Send the new data, but don't wait for a response */
        if ((k = bufwrite(serverfd, request.def, putdatrequestsize)) != putdatrequestsize) {
            fprintf(stderr, "write size = %d, should be %d\n", k, putdatrequestsize);
            sig_handler(-1);
        }

        /* do some logging */
        gettimeofday(&curtime,NULL);
        elapsedusec=(curtime.tv_usec + 1000000 * curtime.tv_sec) - (starttime.tv_usec + 1000000 * starttime.tv_sec);
        if ( elapsedusec / 1000000 >= printtime ) {
            fprintf(stderr,"%d %d %d %f (blk,samp,event,sec)\r",nblk,nsamp,0,elapsedusec/1000000.0);
            printtime+=10;
        }
        nblk+=1;
    } /* while(1) */

    // free all the stuff we've allocated
    free(labelsbuf);
    free(requestbuf);
}
/** \brief Create a "choice" constraint that postpones the resolution of a calc proof step.

    By delaying it, we can perform quick fixes such as:
      - adding symmetry
      - adding !
      - adding subst
*/
constraint mk_calc_proof_cnstr(environment const & env, options const & opts,
                               old_local_context const & _ctx, expr const & m, expr const & _e,
                               constraint_seq const & cs, unifier_config const & cfg,
                               info_manager * im, update_type_info_fn const & fn) {
    justification j         = mk_failed_to_synthesize_jst(env, m);
    auto choice_fn = [=](expr const & meta, expr const & _meta_type, substitution const & _s) {
        old_local_context ctx = _ctx;
        expr e            = _e;
        substitution s    = _s;
        expr meta_type    = _meta_type;
        type_checker_ptr tc = mk_type_checker(env);
        constraint_seq new_cs = cs;
        expr e_type = tc->infer(e, new_cs);
        e_type      = s.instantiate(e_type);
        tag g       = e.get_tag();
        bool calc_assistant = get_elaborator_calc_assistant(opts);

        if (calc_assistant) {
            // add '!' is needed
            while (is_norm_pi(*tc, e_type, new_cs)) {
                binder_info bi = binding_info(e_type);
                if (!bi.is_implicit() && !bi.is_inst_implicit()) {
                    if (!has_free_var(binding_body(e_type), 0)) {
                        // if the rest of the type does not reference argument,
                        // then we also stop consuming arguments
                        break;
                    }
                }
                expr imp_arg = ctx.mk_meta(some_expr(binding_domain(e_type)), g);
                e            = mk_app(e, imp_arg, g);
                e_type       = instantiate(binding_body(e_type), imp_arg);
            }
            if (im)
                fn(e);
        }
        e_type = head_beta_reduce(e_type);

        expr const & meta_type_fn = get_app_fn(meta_type);
        expr const & e_type_fn    = get_app_fn(e_type);
        if (is_constant(meta_type_fn) && (!is_constant(e_type_fn) || const_name(e_type_fn) != const_name(meta_type_fn))) {
            // try to make sure meta_type and e_type have the same head symbol
            if (!try_normalize_to_head(env, const_name(meta_type_fn), e_type, new_cs) &&
                is_constant(e_type_fn)) {
                try_normalize_to_head(env, const_name(e_type_fn), meta_type, new_cs);
            }
        }

        auto try_alternative = [&](expr const & e, expr const & e_type, constraint_seq fcs, bool conservative) {
            justification new_j = mk_type_mismatch_jst(e, e_type, meta_type);
            if (!tc->is_def_eq(e_type, meta_type, new_j, fcs))
                throw unifier_exception(new_j, s);
            buffer<constraint> cs_buffer;
            fcs.linearize(cs_buffer);
            metavar_closure cls(meta);
            cls.add(meta_type);
            cls.mk_constraints(s, j, cs_buffer);

            unifier_config new_cfg(cfg);
            new_cfg.m_discard      = false;
            new_cfg.m_kind         = conservative ? unifier_kind::Conservative : unifier_kind::Liberal;
            unify_result_seq seq   = unify(env, cs_buffer.size(), cs_buffer.data(), substitution(), new_cfg);
            auto p = seq.pull();
            lean_assert(p);
            substitution new_s     = p->first.first;
            constraints  postponed = map(p->first.second,
                                         [&](constraint const & c) {
                                             // we erase internal justifications
                                             return update_justification(c, j);
                                         });
            expr new_e = new_s.instantiate(e);
            if (conservative && has_expr_metavar_relaxed(new_s.instantiate_all(e)))
                throw_elaborator_exception("solution contains metavariables", e);
            if (im)
                im->instantiate(new_s);
            constraints r = cls.mk_constraints(new_s, j);
            buffer<expr> locals;
            expr mvar  = get_app_args(meta, locals);
            expr val   = Fun(locals, new_e);
            r = cons(mk_eq_cnstr(mvar, val, j), r);
            return append(r, postponed);
        };

        if (!get_elaborator_calc_assistant(opts)) {
            bool conservative = false;
            return try_alternative(e, e_type, new_cs, conservative);
        } else {
            // TODO(Leo): after we have the simplifier and rewriter tactic, we should revise
            // this code. It is "abusing" the higher-order unifier.

            {
                // Try the following possible intrepretations using a "conservative" unification procedure.
                // That is, we only unfold definitions marked as reducible.
                // Assume pr is the proof provided.

                // 1. pr
                bool conservative = true;
                try { return try_alternative(e, e_type, new_cs, conservative); } catch (exception & ex) {}

                // 2. eq.symm pr
                constraint_seq symm_cs = new_cs;
                auto symm  = apply_symmetry(env, ctx, tc, e, e_type, symm_cs, g);
                if (symm) {
                    try { return try_alternative(symm->first, symm->second, symm_cs, conservative); } catch (exception &) {}
                }

                // 3. subst pr (eq.refl lhs)
                constraint_seq subst_cs = new_cs;
                if (auto subst = apply_subst(env, ctx, tc, e, e_type, meta_type, subst_cs, g)) {
                    try { return try_alternative(subst->first, subst->second, subst_cs, conservative); } catch (exception&) {}
                }

                // 4. subst (eq.symm pr) (eq.refl lhs)
                if (symm) {
                    constraint_seq subst_cs = symm_cs;
                    if (auto subst = apply_subst(env, ctx, tc, symm->first, symm->second,
                                                 meta_type, subst_cs, g)) {
                        try { return try_alternative(subst->first, subst->second, subst_cs, conservative); }
                        catch (exception&) {}
                    }
                }
            }

            {
                // Try the following possible insterpretations using the default unification procedure.

                // 1. pr
                bool conservative = false;
                std::unique_ptr<throwable> saved_ex;
                try {
                    return try_alternative(e, e_type, new_cs, conservative);
                } catch (exception & ex) {
                    saved_ex.reset(ex.clone());
                }

                // 2. eq.symm pr
                constraint_seq symm_cs = new_cs;
                auto symm  = apply_symmetry(env, ctx, tc, e, e_type, symm_cs, g);
                if (symm) {
                    try { return try_alternative(symm->first, symm->second, symm_cs, conservative); }
                    catch (exception &) {}
                }

                // We use the exception for the first alternative as the error message
                saved_ex->rethrow();
                lean_unreachable();
            }
        }
    };
    bool owner = false;
    return mk_choice_cnstr(m, choice_fn, to_delay_factor(cnstr_group::Epilogue), owner, j);
}
	void UString::append(const char* str)
	{
		append(str, strlen(str));
	}
示例#5
0
文件: apqueue.c 项目: BVRoot/MHT
void apqSOLUTION::partition()
{
    void *doomedRCCtag;
    ROW_COL_COST doomedRCC;
    char rowIsNotEmpty;
    char colIsNotEmpty;
    apqSOLUTION *solution;
    int i, k;

#ifdef SDBG
    for( i = 0; i < m_numRCCs; i++ )
    {
        printf("m_rcc=%d row=%d col=%d tag=%d\n",&m_rcc[i],m_rcc[i].row,m_rcc[i].col,m_rcc[i].tag);
    }
#endif

    /* loop through all the assignments in the solution (not counting the
       ones in the base solution) */

    while( m_baseSolutionSize < m_solutionSize )
    {
        /* find the ROW_COL_COST structure for this assignment -- this
           structure is "doomed" to be removed from the assignment
           problem */
        doomedRCCtag = m_solutionTag[ m_baseSolutionSize ];

#ifdef SDBG
        printf("m_baseSolnSize=%d doomedRCCtag=%d m_numRCCs=%d\n",m_baseSolutionSize,doomedRCCtag,m_numRCCs);
#endif

        for( i = 0; i < m_numRCCs; i++ )
            if( m_rcc[ i ].tag == doomedRCCtag )
            {
                break;
            }
        /*
            #ifdef TSTBUG */
        assert( i < m_numRCCs );
        //  THROW_ERR( "ASSIGNMENT_PQUEUE looking for non-existant tag" )
        /*    #endif*/

#ifdef SDBG
        printf("doomedRCC was found at i=%d\n",i);
#endif

        doomedRCC = m_rcc[ i ];
        /* a row of -1, or a column of -1, should be ignored, since these
           aren't really nodes */
        if( doomedRCC.row < 0 )
        {
            doomedRCC.row = IGNORE_THIS;
        }
        if( doomedRCC.col < 0 )
        {
            doomedRCC.col = IGNORE_THIS;
        }

        /* remove the doomed ROW_COL_COST from the assignment problem,
           maintaining the list of ROW_COL_COST's in order */
        m_numRCCs--;
        if( i < m_numRCCs )
            memmove( &m_rcc[ i ], &m_rcc[ i + 1 ],
                     (m_numRCCs - i) * sizeof( *m_rcc ) );

        /* What we have now is the problem called P' in the header comments
           for apqueue.H, after <r,c,s> has been removed. */

        /* find out if the row and column can possibly be assigned to
           other things */
        rowIsNotEmpty = (doomedRCC.row == IGNORE_THIS);
        colIsNotEmpty = (doomedRCC.col == IGNORE_THIS);
        for( i = 0; i < m_numRCCs; i++ )
        {
            if( m_rcc[ i ].row == doomedRCC.row )
            {
                rowIsNotEmpty = 1;
                if( colIsNotEmpty )
                {
                    break;
                }
            }
            if( m_rcc[ i ].col == doomedRCC.col )
            {
                colIsNotEmpty = 1;
                if( rowIsNotEmpty )
                {
                    break;
                }
            }
        }

        /* if they can, then proceed find a lower limit on the cost of
           the best solution to this problem, make a problem/solution pair,
           and place it on the list */
        if( rowIsNotEmpty && colIsNotEmpty )
        {
            /* the constructor both finds a lower limit on the cost of the
               best solution and makes the problem/solution pair */
            solution = new apqSOLUTION( m_problemTag,
                                        m_baseCost,
                                        m_cost,
                                        m_solutionTag,
                                        m_baseSolutionSize,
                                        m_rcc,
                                        m_numRCCs,
                                        m_numRows,
                                        m_numCols );

            /* the pair is invalid if no solution is possible */
            if( solution->isValid() )
            {
                append( solution );
            }
            else
            {
                delete solution;
            }
        }

        /* remove all the possible assignments for this row and column */
        if( (rowIsNotEmpty && doomedRCC.row != IGNORE_THIS) ||
                (colIsNotEmpty && doomedRCC.col != IGNORE_THIS) )
        {
            for( i = 0;
                    i < m_numRCCs &&
                    m_rcc[ i ].row != doomedRCC.row &&
                    m_rcc[ i ].col != doomedRCC.col;
                    i++ )
                ;

            k = i;
            while( i < m_numRCCs )
            {
                if( m_rcc[ i ].row != doomedRCC.row &&
                        m_rcc[ i ].col != doomedRCC.col )
                {
                    m_rcc[ k++ ] = m_rcc[ i ];
                }
                i++;
            }

            m_numRCCs = k;
        }

        /* add the "doomed" assignment to the base solution */
        m_baseCost += doomedRCC.cost;
        m_baseSolutionSize++;

#ifdef SDBG
        for( i = 0; i < m_numRCCs; i++ )
        {
            printf("m_rcc=%d row=%d col=%d tag=%d\n",&m_rcc[i],m_rcc[i].row,m_rcc[i].col,m_rcc[i].tag);
        }
#endif

    }
}
示例#6
0
Hdf::Hdf(const char *filename) : m_hdf(nullptr), m_dump(nullptr) {
  m_rawp = new HdfRaw();
  append(filename);
}
示例#7
0
void DrawMolItem::draw_orbital(int density, int wavefnctype, int wavefncspin, 
                               int wavefncexcitation, int orbid, 
                               float isovalue, 
                               int drawbox, int style, 
                               float gridspacing, int stepsize, int thickness) {
  if (!mol->numframes() || gridspacing <= 0.0f)
    return; 

  // only recalculate the orbital grid if necessary
  int regenorbital=0;
  if (density != orbgridisdensity ||
      wavefnctype != waveftype ||
      wavefncspin != wavefspin ||
      wavefncexcitation != wavefexcitation ||
      orbid != gridorbid ||
      gridspacing != orbgridspacing ||
      orbvol == NULL || 
      needRegenerate & MOL_REGEN ||
      needRegenerate & SEL_REGEN) {
    regenorbital=1;
  }

  double motime=0, voltime=0, gradtime=0;
  wkf_timerhandle timer = wkf_timer_create();
  wkf_timer_start(timer);

  if (regenorbital) {
    // XXX this needs to be fixed so that things like the
    //     draw multiple frames feature will work correctly for Orbitals
    int frame = mol->frame(); // draw currently active frame
    const Timestep *ts = mol->get_frame(frame);

    if (!ts->qm_timestep || !mol->qm_data || 
        !mol->qm_data->num_basis || orbid < 1) {
      wkf_timer_destroy(timer);
      return;
    }

    // Find the  timestep independent wavefunction ID tag
    // by comparing type, spin, and excitation with the
    // signatures of existing wavefunctions.
    int waveid = mol->qm_data->find_wavef_id_from_gui_specs(
                  wavefnctype, wavefncspin, wavefncexcitation);

    // Translate the wavefunction ID into the index the
    // wavefunction has in this timestep
    int iwave = ts->qm_timestep->get_wavef_index(waveid);

    if (iwave<0 || 
        !ts->qm_timestep->get_wavecoeffs(iwave) ||
        !ts->qm_timestep->get_num_orbitals(iwave) ||
        orbid > ts->qm_timestep->get_num_orbitals(iwave)) {
      wkf_timer_destroy(timer);
      return;
    }

    // Get the orbital index for this timestep from the orbital ID.
    int orbindex = ts->qm_timestep->get_orbital_index_from_id(iwave, orbid);

    // Build an Orbital object and prepare to calculate a grid
    Orbital *orbital = mol->qm_data->create_orbital(iwave, orbindex, 
                                                    ts->pos, ts->qm_timestep);

    // Set the bounding box of the atom coordinates as the grid dimensions
    orbital->set_grid_to_bbox(ts->pos, 3.0, gridspacing);

    // XXX needs more testing, can get stuck for certain orbitals
#if 0
    // XXX for GPU, we need to only optimize to a stepsize of 4 or more, as
    //     otherwise doing this actually slows us down rather than speeding up
    //     orbital.find_optimal_grid(0.01, 4, 8);
    // 
    // optimize: minstep 2, maxstep 8, threshold 0.01
    orbital->find_optimal_grid(0.01, 2, 8);
#endif

    // Calculate the molecular orbital
    orbital->calculate_mo(mol, density);

    motime = wkf_timer_timenow(timer);

    // query orbital grid origin, dimensions, and axes 
    const int *numvoxels = orbital->get_numvoxels();
    const float *origin = orbital->get_origin();

    float xaxis[3], yaxis[3], zaxis[3];
    orbital->get_grid_axes(xaxis, yaxis, zaxis);

    // build a VolumetricData object for rendering
    char dataname[64];
    sprintf(dataname, "molecular orbital %i", orbid);

    // update attributes of cached orbital grid
    orbgridisdensity = density;
    waveftype = wavefnctype;
    wavefspin = wavefncspin;
    wavefexcitation = wavefncexcitation;
    gridorbid = orbid;
    orbgridspacing = gridspacing;
    delete orbvol;
    orbvol = new VolumetricData(dataname, origin, 
                                xaxis, yaxis, zaxis,
                                numvoxels[0], numvoxels[1], numvoxels[2],
                                orbital->get_grid_data());
    delete orbital;

    voltime = wkf_timer_timenow(timer);

    orbvol->compute_volume_gradient(); // calc gradients: smooth vertex normals

    gradtime = wkf_timer_timenow(timer);
  } // regen the orbital grid...


  // draw the newly created VolumetricData object 
  sprintf(commentBuffer, "MoleculeID: %d ReprID: %d Beginning Orbital",
          mol->id(), repNumber);
  cmdCommentX.putdata(commentBuffer, cmdList);

  if (drawbox > 0) {
    // don't texture the box if color by volume is active
    if (atomColor->method() == AtomColor::VOLUME) {
      append(DVOLTEXOFF);
    }
    // wireframe only?  or solid?
    if (style > 0 || drawbox == 2) {
      draw_volume_box_lines(orbvol);
    } else {
      draw_volume_box_solid(orbvol);
    }
    if (atomColor->method() == AtomColor::VOLUME) {
      append(DVOLTEXON);
    }
  }

  if ((drawbox == 2) || (drawbox == 0)) {
    switch (style) {
      case 3:
        // shaded points isosurface looping over X-axis, 1 point per voxel
        draw_volume_isosurface_lit_points(orbvol, isovalue, stepsize, thickness);
        break;

      case 2:
        // points isosurface looping over X-axis, max of 1 point per voxel
        draw_volume_isosurface_points(orbvol, isovalue, stepsize, thickness);
        break;

      case 1:
        // lines implementation, max of 18 line per voxel (3-per triangle)
        draw_volume_isosurface_lines(orbvol, isovalue, stepsize, thickness);
        break;

      case 0:
      default:
        // trimesh polygonalized surface, max of 6 triangles per voxel
        draw_volume_isosurface_trimesh(orbvol, isovalue, stepsize);
        break;
    }
  }

  if (regenorbital) {
    double surftime = wkf_timer_timenow(timer);
    if (surftime > 5) {
      char strmsg[1024];
      sprintf(strmsg, "Total MO rep time: %.3f [MO: %.3f vol: %.3f grad: %.3f surf: %.2f]",
              surftime, motime, voltime - motime, gradtime - motime, surftime - gradtime);

      msgInfo << strmsg << sendmsg;
    }
  }

  wkf_timer_destroy(timer);
}
示例#8
0
void* WorldBuilder::unpack(void* buf)
{
  // unpack world database from network transfer
  // read style header
  uint16_t code, len;
  buf = nboUnpackUShort(buf, len);
  buf = nboUnpackUShort(buf, code);
  if (code != WorldCodeHeader) return NULL;

  // read style
  uint16_t gameStyle, maxPlayers, maxShots, maxFlags,serverMapVersion;
  buf = nboUnpackUShort(buf, serverMapVersion);
  if (serverMapVersion != mapVersion)
    return NULL;

  float worldSize;
  buf = nboUnpackFloat(buf, worldSize);
  BZDB.set(StateDatabase::BZDB_WORLDSIZE, string_util::format("%f", worldSize));
  buf = nboUnpackUShort(buf, gameStyle);
  setGameStyle(short(gameStyle));
  buf = nboUnpackUShort(buf, maxPlayers);
  setMaxPlayers(int(maxPlayers));
  buf = nboUnpackUShort(buf, maxShots);
  setMaxShots(int(maxShots));
  buf = nboUnpackUShort(buf, maxFlags);
  setMaxFlags(int(maxFlags));
  buf = nboUnpackFloat(buf, world->linearAcceleration);
  buf = nboUnpackFloat(buf, world->angularAcceleration);
  uint16_t shakeTimeout = 0, shakeWins;
  buf = nboUnpackUShort(buf, shakeTimeout);
  setShakeTimeout(0.1f * float(shakeTimeout));
  buf = nboUnpackUShort(buf, shakeWins);
  setShakeWins(shakeWins);
  uint32_t epochOffset;
  buf = nboUnpackUInt(buf, epochOffset);
  setEpochOffset(epochOffset);

  // read geometry
  buf = nboUnpackUShort(buf, len);
  buf = nboUnpackUShort(buf, code);
  while (code != WorldCodeEnd) {
    switch (code) {
      case WorldCodeBox: {
	float data[7];
	unsigned char tempflags;

	if (len != WorldCodeBoxSize)
	  return NULL;

	memset(data, 0, sizeof(float) * 7);
	buf = nboUnpackFloat(buf, data[0]);
	buf = nboUnpackFloat(buf, data[1]);
	buf = nboUnpackFloat(buf, data[2]);
	buf = nboUnpackFloat(buf, data[3]);
	buf = nboUnpackFloat(buf, data[4]);
	buf = nboUnpackFloat(buf, data[5]);
	buf = nboUnpackFloat(buf, data[6]);
	buf = nboUnpackUByte(buf, tempflags);
	BoxBuilding box(data, data[3], data[4], data[5], data[6],
			(tempflags & _DRIVE_THRU)!=0, (tempflags & _SHOOT_THRU)!=0);
	append(box);
	break;
      }
      case WorldCodePyramid: {
	float data[7];
	unsigned char tempflags;

	if (len != WorldCodePyramidSize)
	  return NULL;

	buf = nboUnpackFloat(buf, data[0]);
	buf = nboUnpackFloat(buf, data[1]);
	buf = nboUnpackFloat(buf, data[2]);
	buf = nboUnpackFloat(buf, data[3]);
	buf = nboUnpackFloat(buf, data[4]);
	buf = nboUnpackFloat(buf, data[5]);
	buf = nboUnpackFloat(buf, data[6]);
	buf = nboUnpackUByte(buf, tempflags);

	PyramidBuilding pyr(data, data[3], data[4], data[5], data[6],
			    (tempflags & _DRIVE_THRU)!=0, (tempflags & _SHOOT_THRU)!=0);
	if (tempflags & _FLIP_Z)
	  pyr.setZFlip();

	append(pyr);
	break;
      }
      case WorldCodeTeleporter: {
	float data[8];
	unsigned char tempflags;

	if (len != WorldCodeTeleporterSize)
	  return NULL;

	buf = nboUnpackFloat(buf, data[0]);
	buf = nboUnpackFloat(buf, data[1]);
	buf = nboUnpackFloat(buf, data[2]);
	buf = nboUnpackFloat(buf, data[3]);
	buf = nboUnpackFloat(buf, data[4]);
	buf = nboUnpackFloat(buf, data[5]);
	buf = nboUnpackFloat(buf, data[6]);
	buf = nboUnpackFloat(buf, data[7]);
	buf = nboUnpackUByte(buf, tempflags);
	Teleporter tele(data, data[3], data[4], data[5], data[6],data[7],
			(tempflags & _DRIVE_THRU)!=0, (tempflags & _SHOOT_THRU)!=0);
	append(tele);
	break;
      }
      case WorldCodeLink: {
	uint16_t data[2];

	if (len != WorldCodeLinkSize)
	  return NULL;

	buf = nboUnpackUShort(buf, data[0]);
	buf = nboUnpackUShort(buf, data[1]);
	setTeleporterTarget(int(data[0]), int(data[1]));
	break;
      }
      case WorldCodeWall: {
	float data[6];

	if (len != WorldCodeWallSize)
	  return NULL;

	buf = nboUnpackFloat(buf, data[0]);
	buf = nboUnpackFloat(buf, data[1]);
	buf = nboUnpackFloat(buf, data[2]);
	buf = nboUnpackFloat(buf, data[3]);
	buf = nboUnpackFloat(buf, data[4]);
	buf = nboUnpackFloat(buf, data[5]);
	WallObstacle wall(data, data[3], data[4], data[5]);
	append(wall);
	break;
      }
      case WorldCodeBase: {
	uint16_t team;
	float data[10];

	if (len != WorldCodeBaseSize)
	  return NULL;

	buf = nboUnpackUShort(buf, team);
	buf = nboUnpackFloat(buf, data[0]);
	buf = nboUnpackFloat(buf, data[1]);
	buf = nboUnpackFloat(buf, data[2]);
	buf = nboUnpackFloat(buf, data[3]);
	buf = nboUnpackFloat(buf, data[4]);
	buf = nboUnpackFloat(buf, data[5]);
	buf = nboUnpackFloat(buf, data[6]);
	buf = nboUnpackFloat(buf, data[7]);
	buf = nboUnpackFloat(buf, data[8]);
	buf = nboUnpackFloat(buf, data[9]);
	BaseBuilding base(data, data[3], data +4, team);
	append(base);
	setBase(TeamColor(team), data, data[3], data[4], data[5], data[6]);
	break;
      }
      case WorldCodeWeapon: {
	Weapon weapon;
        uint16_t delays; 

	buf = FlagType::unpack(buf, weapon.type);
	buf = nboUnpackFloat(buf, weapon.pos[0]);
	buf = nboUnpackFloat(buf, weapon.pos[1]);
	buf = nboUnpackFloat(buf, weapon.pos[2]);
	buf = nboUnpackFloat(buf, weapon.dir);
	buf = nboUnpackFloat(buf, weapon.initDelay);
	buf = nboUnpackUShort(buf, delays);
	
	uint16_t weapon_len = WorldCodeWeaponSize + (delays * sizeof(float));
	if (len != weapon_len) {
	  return NULL;
	}
	
	int i;
	for (i = 0; i < delays; i++) {
	  float delay;
  	  buf = nboUnpackFloat(buf, delay);
  	  weapon.delay.push_back(delay);
  	}
	append(weapon);
	break;
      }
      case WorldCodeZone: {
        EntryZone zone;
        uint16_t flags, teams, safety;

	buf = nboUnpackFloat(buf, zone.pos[0]);
	buf = nboUnpackFloat(buf, zone.pos[1]);
	buf = nboUnpackFloat(buf, zone.pos[2]);
	buf = nboUnpackFloat(buf, zone.size[0]);
	buf = nboUnpackFloat(buf, zone.size[1]);
	buf = nboUnpackFloat(buf, zone.size[2]);
	buf = nboUnpackFloat(buf, zone.rot);
	buf = nboUnpackUShort(buf, flags);
	buf = nboUnpackUShort(buf, teams);
	buf = nboUnpackUShort(buf, safety);

        uint16_t zone_len = WorldCodeZoneSize;
        zone_len += FlagType::packSize * flags;
        zone_len += sizeof(uint16_t) * teams;
        zone_len += sizeof(uint16_t) * safety;
	if (len != zone_len) {
	  return NULL;
	}

        int i;
	for (i = 0; i < flags; i++) {
	  FlagType *type;
  	  buf = FlagType::unpack (buf, type);
  	  zone.flags.push_back(type);
  	}
	for (i = 0; i < teams; i++) {
	  uint16_t team;
  	  buf = nboUnpackUShort(buf, team);
  	  zone.teams.push_back((TeamColor)team);
  	}
	for (i = 0; i < safety; i++) {
	  uint16_t safety;
  	  buf = nboUnpackUShort(buf, safety);
  	  zone.safety.push_back((TeamColor)safety);
  	}
	append(zone);
	break;
      }
      default:
	return NULL;
    }
    buf = nboUnpackUShort(buf, len);
    buf = nboUnpackUShort(buf, code);
  }

  return buf;
}
示例#9
0
std::list<CommandLine::segment> CommandLine::GetPrompt()
{
	FN_RETURN_TYPE(CommandLine::GetPrompt) Result;
	int NewPromptSize = DEFAULT_CMDLINE_WIDTH;

	const auto& PrefixColor = colors::PaletteColorToFarColor(COL_COMMANDLINEPREFIX);

	if (Global->Opt->CmdLine.UsePromptFormat)
	{
		const string_view Format = Global->Opt->CmdLine.strPromptFormat.Get();
		auto Tail = Format.cbegin();
		auto Color = PrefixColor;
		FOR_CONST_RANGE(Format, Iterator)
		{
			bool Stop;
			auto NewColor = PrefixColor;
			const auto NextIterator = colors::ExtractColorInNewFormat(Iterator, Format.cend(), NewColor, Stop);
			if (NextIterator == Iterator)
			{
				if (Stop)
					break;
				continue;
			}

			if (Iterator != Format.cbegin())
			{
				Result.emplace_back(segment{ string(Tail, Iterator), Color });
			}
			Iterator = NextIterator;
			Tail = Iterator;
			Color = NewColor;
		}
		Result.emplace_back(segment{ string(Tail, Format.cend()), Color });

		for (auto Iterator = Result.begin(); Iterator != Result.end(); ++Iterator)
		{
			const auto strExpandedDestStr = os::env::expand(Iterator->Text);
			Iterator->Text.clear();
			static const std::pair<wchar_t, wchar_t> ChrFmt[] =
			{
				{L'A', L'&'},   // $A - & (Ampersand)
				{L'B', L'|'},   // $B - | (pipe)
				{L'C', L'('},   // $C - ( (Left parenthesis)
				{L'F', L')'},   // $F - ) (Right parenthesis)
				{L'G', L'>'},   // $G - > (greater-than sign)
				{L'L', L'<'},   // $L - < (less-than sign)
				{L'Q', L'='},   // $Q - = (equal sign)
				{L'S', L' '},   // $S - (space)
				{L'$', L'$'},   // $$ - $ (dollar sign)
			};

			FOR_CONST_RANGE(strExpandedDestStr, it)
			{
				auto& strDestStr = Iterator->Text;

				if (*it == L'$' && it + 1 != strExpandedDestStr.cend())
				{
					const auto Chr = upper(*++it);

					const auto ItemIterator = std::find_if(CONST_RANGE(ChrFmt, Item)
					{
						return Item.first == Chr;
					});

					if (ItemIterator != std::cend(ChrFmt))
					{
						strDestStr += ItemIterator->second;
					}
					else
					{
						const auto& AddCollapsible = [&](string&& Str)
						{
							if (strDestStr.empty())
							{
								strDestStr = std::move(Str);
								Iterator->Collapsible = true;
							}
							else
							{
								Iterator = Result.insert(std::next(Iterator), segment{ std::move(Str), Iterator->Colour, true });
							}

							// No need to introduce a new segment if we're at the very end
							if (std::next(Iterator) != Result.end() && std::next(it) != strExpandedDestStr.cend())
							{
								Iterator = Result.insert(std::next(Iterator), segment{ {}, Iterator->Colour, false });
							}
						};

						switch (Chr)
						{
								/* эти не реaлизованы
								$E - Escape code (ASCII code 27)
								$V - Windows version number
								$_ - Carriage return and linefeed
								*/
							case L'M': // $M - Отображение полного имени удаленного диска, связанного с именем текущего диска, или пустой строки, если текущий диск не является сетевым.
							{
								string strTemp;
								if (DriveLocalToRemoteName(DRIVE_UNKNOWN, m_CurDir[0], strTemp))
								{
									AddCollapsible(std::move(strTemp));
								}
								break;
							}
							case L'+': // $+  - Отображение нужного числа знаков плюс (+) в зависимости от текущей глубины стека каталогов PUSHD, по одному знаку на каждый сохраненный путь.
							{
								strDestStr.append(ppstack.size(), L'+');
								break;
							}
							case L'H': // $H - Backspace (erases previous character)
							{
								if (!strDestStr.empty())
								{
									strDestStr.pop_back();
								}
								else
								{
									auto Prev = Iterator;
									while (Prev != Result.begin())
									{
										--Prev;
										if (!Prev->Text.empty())
										{
											Prev->Text.pop_back();
											break;
										}
									}
								}

								break;
							}
							case L'@': // $@xx - Admin
							{
								if (it + 1 != strExpandedDestStr.cend())
								{
									const auto lb = *++it;
									if (it + 1 != strExpandedDestStr.cend())
									{
										const auto rb = *++it;
										if (os::security::is_admin())
										{
											append(strDestStr, lb, msg(lng::MConfigCmdlinePromptFormatAdmin), rb);
										}
									}
								}
								break;
							}
							case L'D': // $D - Current date
							case L'T': // $T - Current time
							{
								strDestStr += MkStrFTime(Chr == L'D'? L"%D" : L"%T");
								break;
							}
							case L'N': // $N - Current drive
							{
								const auto Type = ParsePath(m_CurDir);
								if(Type == root_type::drive_letter)
									strDestStr += upper(m_CurDir[0]);
								else if(Type == root_type::unc_drive_letter)
									strDestStr += upper(m_CurDir[4]);
								else
									strDestStr += L'?';
								break;
							}
							case L'W': // $W - Текущий рабочий каталог (без указания пути)
							{
								const auto pos = FindLastSlash(m_CurDir);
								if (pos != string::npos)
								{
									AddCollapsible(m_CurDir.substr(pos + 1));
								}
								break;
							}
							case L'P': // $P - Current drive and path
							{
								AddCollapsible(string{ m_CurDir });
								break;
							}
							case L'#': //$#nn - max prompt width in %
							{
								if (it + 1 != strExpandedDestStr.end())
								{
									size_t pos;
									if (from_string(string(it + 1, strExpandedDestStr.cend()), NewPromptSize, &pos))
										it += pos;
									// else
										// bad format, NewPromptSize unchanged
										// TODO: diagnostics
								}
							}
						}

						if (it == strExpandedDestStr.cend())
						{
							break;
						}
					}
				}
				else
				{
bool handleStreamInstruction(Buffer* inputBuffer,
                            Buffer* outputBuffer,
                            OutputStream* outputStream,
                            filterCharFunction* inputFilterChar,
                            filterCharFunction* outputFilterChar) {

    if (inputBuffer == NULL) {
        writeError(DRIVER_STREAM_LISTENER_INPUT_BUFFER_NULL);
        return false;
    }
    if (outputBuffer == NULL) {
        writeError(DRIVER_STREAM_LISTENER_OUTPUT_BUFFER_NULL);
        return false;
    }

    // Try to clear the buffer if needed ('z' char)
    if (clearBufferIfNeeded(inputBuffer)) {
        return false;
    }

    // We received data
    int inputBufferCount = getBufferElementsCount(inputBuffer);

    if (inputBufferCount > 0) {

        if (filterFirstNextChar(inputBuffer, inputFilterChar)) {
            return false;
        }

        // As there is clear of char filtering, we must reload the size of the buffer
        int bufferSize = getBufferElementsCount(inputBuffer);

        if (bufferSize < DEVICE_HEADER_LENGTH) {
            return false;
        }

        // Get the header
        unsigned char deviceHeader = bufferGetCharAtIndex(inputBuffer, DEVICE_HEADER_INDEX);

        // Manage the dispatcher specifier (3 chars : Ex j01 before real command ...)
        unsigned char specifyDispatcherLength = 0;
        if (deviceHeader == DATA_DISPATCHER_DEVICE_HEADER) {
            specifyDispatcherLength += DISPATCHER_COMMAND_AND_INDEX_HEADER_LENGTH;
        }

        // Check if enough data
        if (bufferSize < specifyDispatcherLength + DEVICE_AND_COMMAND_HEADER_LENGTH) {
            return false;
        }

        // Reload the deviceHeader to take the dispatcher specifier if any
        deviceHeader = bufferGetCharAtIndex(inputBuffer, specifyDispatcherLength + DEVICE_HEADER_INDEX);
        unsigned char commandHeader = bufferGetCharAtIndex(inputBuffer, specifyDispatcherLength + COMMAND_HEADER_INDEX);

        // find the device corresponding to this header. It must at least be declared in local or in remote !
        unsigned char dataSize = bufferSize - specifyDispatcherLength;
        const Device* device = deviceDataDispatcherFindDevice(deviceHeader, commandHeader, dataSize, DEVICE_MODE_INPUT);

        // if the device was not found
        if (device == NULL) {
            return false;
        }

        // At this moment, device Interface is found
        DeviceInterface* deviceInterface = device->deviceInterface;

        // We must send device specifyDispatcherLength + Header + commandHeader + data => + 2
        int dataToTransferCount = deviceInterface->deviceGetInterface(commandHeader, DEVICE_MODE_INPUT, false) + specifyDispatcherLength + DEVICE_AND_COMMAND_HEADER_LENGTH;

        if (bufferSize < dataToTransferCount) {
            return false;
        }

        // We must receive ack + device header + command header + data => + 3
        int dataToReceiveCount = deviceInterface->deviceGetInterface(commandHeader, DEVICE_MODE_OUTPUT, false) + ACK_LENGTH + DEVICE_AND_COMMAND_HEADER_LENGTH;

        InputStream* bufferedInputStream = getInputStream(inputBuffer);
        OutputStream* bufferedOutputStream = getOutputStream(outputBuffer);

        TransmitMode transmitMode = device->transmitMode;

        // we handle locally the request
        if (specifyDispatcherLength == 0 && transmitMode == TRANSMIT_LOCAL) {

            // We need the implementation for local mode
            DeviceDescriptor* deviceDescriptor = device->descriptor;
            if (deviceDescriptor == NULL) {
                writeError(NO_DEVICE_DESC_FOUND_FOR);
                append(getErrorOutputStreamLogger(), deviceHeader);
                append(getErrorOutputStreamLogger(), commandHeader);
                return false;
            }

            // remove the first chars corresponding to the device header and command Header
            bufferClearLastChars(inputBuffer, DEVICE_AND_COMMAND_HEADER_LENGTH);

            // Call to the device
            deviceDescriptor->deviceHandleRawData(commandHeader, bufferedInputStream, bufferedOutputStream);

        } // we forward the request through Remote Operation with Dispatcher
        else if (specifyDispatcherLength > 0 || transmitMode == TRANSMIT_I2C || transmitMode == TRANSMIT_UART || transmitMode == TRANSMIT_ZIGBEE) {

            // Find dispatcher
            DriverDataDispatcher* dispatcher = NULL;

            if (specifyDispatcherLength > 0) {
                bufferClearLastChars(inputBuffer, DEVICE_HEADER_LENGTH);
                unsigned char dispatcherIndex = readHex2(bufferedInputStream);

                dispatcher = getDriverDataDispatcherByIndex(dispatcherIndex);
                if (dispatcher == NULL) {
                    writeError(NO_DISPATCHER_FOUND);
                    OutputStream* errorOutputStream = getErrorOutputStreamLogger();
                    appendStringAndDec(errorOutputStream, ", dispatcherIndex=", dispatcherIndex);
                    return false;
                }
            }
            else {
                TransmitMode transmitMode = device->transmitMode;
                int address = device->address;

                dispatcher = getDriverDataDispatcherByTransmitMode(transmitMode, address);
                
                if (dispatcher == NULL) {
                    writeError(NO_DISPATCHER_FOUND);
                    OutputStream* errorOutputStream = getErrorOutputStreamLogger();
                    appendStringAndDec(errorOutputStream, ", transmitMode=", transmitMode);
                    append(errorOutputStream, '(');
                    appendString(errorOutputStream, getTransmitModeAsString(transmitMode));
                    append(errorOutputStream, ')');
                    appendStringAndDec(errorOutputStream, ", addr=", address);
                    return false;
                }
            }

            // copy Driver buffer with remote Call
            dispatcher->driverDataDispatcherTransmitData(dispatcher,
                    inputBuffer,
                    outputBuffer,
                    dataToTransferCount,
                    dataToReceiveCount
                    );
        }
        
        // In All Cases (Local / I2C / UART / Zigbee ...)

        // Copy the data from bufferOutputStream to the outputStream
        if (outputStream != NULL) {
            copyInputToOutputStream(&(outputBuffer->inputStream), outputStream, outputFilterChar, dataToReceiveCount);
        }
        return true;
    }
    return false;
}
示例#11
0
IfElse::IfElse(spOp ifOp, spOp elseOp) {
    append(ifOp);
    elseBlock.append(elseOp);
}
示例#12
0
 void SourceMap::append(const OutputBuffer& out)
 {
   append(Offset(out.buffer));
 }
示例#13
0
typestr & typestr::append(const typestr & a_str)
{
    append(a_str.m_str ? a_str.m_str : "");
    return *this;
}
示例#14
0
文件: rule.cpp 项目: xurongs/unisdm
RuleSwitch& RuleSwitch::append(const Rule& rule)
{
	return append(rule.clone());
}
示例#15
0
static int begin_process(const lsi_session_t *session)
{
#define VALMAXSIZE 4096
#define LINEMAXSIZE (VALMAXSIZE + 50)
    char val[VALMAXSIZE], line[LINEMAXSIZE] = {0};
    int n;
    int i;
    const char *p;
    char *buf;
    mydata_t *mydata = (mydata_t *)g_api->get_module_data(session, &MNAME,
                       LSI_DATA_HTTP);
    ls_xpool_t *pPool = g_api->get_session_pool(session);

    //Create response body
    append(session, CONTENT_HEAD, 0);

    //Original request header
    n = g_api->get_req_raw_headers_length(session);
    buf = (char *)ls_xpool_alloc(pPool, n + 1);
    memset(buf, 0, n + 1);
    n = g_api->get_req_raw_headers(session, buf, n + 1);
    append(session, "Original request<table border=1><tr><td><pre>\r\n", 0);
    append(session, buf, n);
    append(session, "\r\n</pre></td></tr>\r\n", 0);
    ls_xpool_free(pPool, buf);

    append(session, "\r\n</table><br>Request headers<br><table border=1>\r\n",
           0);
    for (i = 0; i < sizeof(reqhdr_array) / sizeof(char *); ++i)
    {
        p = g_api->get_req_header(session, reqhdr_array[i],
                                  strlen(reqhdr_array[i]), &n);
        if ((p != NULL) && p[0] != 0 && n > 0)
        {
            memcpy(val, p, n);
            val[n] = '\0';
            n = snprintf(line, LINEMAXSIZE - 1, CONTENT_FORMAT, reqhdr_array[i],
                         val);
            append(session, line, n);
        }
    }


    append(session,
           "\r\n</table><br>Server req env<br><table border=1>\r\n", 0);
    //Server req env
    for (i = LSI_VAR_REMOTE_ADDR; i < LSI_VAR_COUNT; ++i)
    {
        n = g_api->get_req_var_by_id(session, i, val, VALMAXSIZE);
        if (n > 0)
        {
            val[n] = '\0';
            n = snprintf(line, LINEMAXSIZE - 1, CONTENT_FORMAT, req_array[i],
                         val);
            append(session, line, n);
        }
    }

    append(session, "\r\n</table><br>env varibles<br><table border=1>\r\n", 0);
    for (i = 0; i < sizeof(env_array) / sizeof(char *); ++i)
    {
        //env varibles
        n = g_api->get_req_env(session, env_array[i], strlen(env_array[i]), val,
                               VALMAXSIZE);
        if (n > 0)
        {
            val[n] = '\0';
            n = snprintf(line, LINEMAXSIZE - 1, CONTENT_FORMAT, env_array[i],
                         val);
            append(session, line, n);
        }
    }


    p = g_api->get_req_cookies(session, &n);
    if ((p != NULL) && p[0] != 0 && n > 0)
    {
        append(session,
               "\r\n</table><br>Request cookies<br><table border=1>\r\n", 0);
        append(session, "<tr><td>Cookie</td><td>", 0);
        append(session, p, n);
        append(session, "</td></tr>", 0);
    }

    n = g_api->get_req_cookie_count(session);
    if (n > 0)
    {
        //try get a certen cookie
        p = g_api->get_cookie_value(session, "LSWSWEBUI", 9, &n);
        if ((p != NULL) && n > 0)
        {
            append(session, "<tr><td>cookie_LSWSWEBUI</td><td>", 0);
            append(session, p, n);
            append(session, "</td></tr>", 0);
        }
    }
    append(session, "</table>", 0);

    n = get_reqbody_dealertype(session);

    mydata->req_body_len = g_api->get_req_content_length(session);
    mydata->rcvd_req_body_len = 0;
    mydata->type = n;
    sprintf(line,
            "Will deal with the req body.Type = %d, req body lenghth = %d<br>",
            n, mydata->req_body_len);

    append(session, line, 0);
    if (mydata->type == 0)
    {
        append(session, CONTENT_TAIL, 0);
        mydata->rcvd_done = 1;
        mydata->resp_done = 1;
    }

    g_api->set_status_code(session, 200);

    if (mydata->type == 3)  // Save to file
        mydata->fp = fopen("/tmp/uploadfile", "wb");
    else if (mydata->type == 2)   // Md5
        MD5_Init(&mydata->ctx);

    g_api->flush(session);

//     if ( mydata->type != 0)
    on_read(session);

    //g_api->end_resp(session);
    return 0;
}
示例#16
0
/* clean and scan input into lex table and token list */
int scan(const char* inputPath, const char* cleanInputPath,
        const char* lexTablePath, const char* tokenListPath, token* tokens) {

    // Open clean input for reading
    FILE* ifp = getCleanInput(inputPath, cleanInputPath);

    // Linked list of tokens
    token* firstToken = tokens;
    tokens->type = -1;
    int countTokens = 0;

    // Keep track of current line number
    int lineNumber = 1;

    // Loop through input as DFA simulation
    while(!feof(ifp)) {

        // Get Character from stream
        char ch = getc(ifp);

        // Copy character into a temp string
        char lexeme[12] = "";

        // Boolean to check if the current ch has been matched
        int matched = 0;

        // Check if ch is part of an Identifier or Reserved Word
        if(isalpha(ch)) {
            int couldBeReserved = 1;
            int letterCount = 0;
            matched = 1;

            // Get the next char while checking if it's alphanumeric
            while( (isalpha(ch) || isdigit(ch)) && !feof(ifp)) {

                // If token contains a digit then it's not a reserved word
                if (isdigit(ch)) {
                    couldBeReserved = 0;
                }

                // Append ch to temp token
                append(lexeme, ch);
                letterCount++;

                // Identifier can't be longer than 11 characters
                if (letterCount > 11) {
                    fprintf(stdout, "[SCANNER-ERROR] Identifiers may not be longer than 11 characters. line %d.\n", lineNumber);
                    exit(EXIT_FAILURE);
                }

                // Get next ch
                ch = getc(ifp);
            }

            // Go back 1 char
            ungetc(ch, ifp);

            token_type type;
            if (couldBeReserved) {
                type = getReservedType(lexeme);
            } else {
                type = identsym;
            }

            addToList(&tokens, lexeme, 0, type, &countTokens, lineNumber);
        } else {
            // Not alphabetic, go back
            matched = 0;
            ungetc(ch, ifp);
        }

        // Get next char
        ch = getc(ifp);

        // Check if ch is part of a Value
        if(isdigit(ch)) {

            matched = 1;
            int numCount = 0;

            while(isdigit(ch)) {
                // Append ch to temp token
                append(lexeme, ch);
                numCount++;

                // Number can't be longer than 5 digits
                if (numCount > 5) {
                    fprintf(stdout, "[SCANNER-ERROR] Numbers may not be longer than 5 digits. line %d.\n", lineNumber);
                    exit(EXIT_FAILURE);
                }

                // Get next ch
                ch = getc(ifp);

                // Identifiers can't start with numbers, throw error
                if (isalpha(ch)) {
                    fprintf(stdout, "[SCANNER-ERROR] Variable doesn't start with a letter. line %d.\n", lineNumber);
                    exit(EXIT_FAILURE);
                }
            }

            // Parse int value
            int value = atoi(lexeme);

            // Go back 1 char
            ungetc(ch, ifp);

            addToList(&tokens, lexeme, value, numbersym, &countTokens, lineNumber);
        } else {
            // Not a digit, go back
            matched = 0;
            ungetc(ch, ifp);
        }

        // Get next ch
        ch = getc(ifp);

        // Check for :=
        if (ch == ':') {
            char cha = getc(ifp);
            if (cha == '=') {
                matched = 1;
                addToList(&tokens, ":=", 0, becomesym, &countTokens, lineNumber);
            } else {
                // Not :=, go back
                matched = 0;
                ungetc(ch, ifp);
            }
        }

        // Check for =
        if(ch == '=') {
            matched = 1;
            addToList(&tokens, "=", 0, equalsym, &countTokens, lineNumber);
        }

        // Check for > and >=
        if (ch == '>') {
            matched = 1;

            // Check if >=
            ch = getc(ifp);

            if (ch == '=') {
                addToList(&tokens, ">=", 0, geqsym, &countTokens, lineNumber);
            } else {
                ungetc(ch, ifp);
                addToList(&tokens, ">", 0, gtrsym, &countTokens, lineNumber);
            }
        }

        // Check for < and <=
        if (ch == '<') {
            matched = 1;

            // Check if <= or <>
            ch = getc(ifp);

            if (ch == '=') {
                addToList(&tokens, "<=", 0, leqsym, &countTokens, lineNumber);
            } else if ( ch == '>') {
                addToList(&tokens, "<>", 0, neqsym, &countTokens, lineNumber);
            } else {
                ungetc(ch, ifp);
                addToList(&tokens, "<", 0, lessym, &countTokens, lineNumber);
            }
        }

        // Check for (
        if (ch == '(') {
            matched = 1;
            addToList(&tokens, "(", 0, lparentsym, &countTokens, lineNumber);
        }

        // Check for )
        if (ch == ')') {
            matched = 1;
            addToList(&tokens, ")", 0, rparentsym, &countTokens, lineNumber);
        }

        // Check for ,
        if (ch == ',') {
            matched = 1;
            addToList(&tokens, ",", 0, commasym, &countTokens, lineNumber);
        }

        // Check for ;
        if (ch == ';') {
            matched = 1;
            addToList(&tokens, ";", 0, semicolonsym, &countTokens, lineNumber);
        }

        // Check for .
        if (ch == '.') {
            matched = 1;
            addToList(&tokens, ".", 0, periodsym, &countTokens, lineNumber);
        }

        // Check for +
        if (ch == '+') {
            matched = 1;
            addToList(&tokens, "+", 0, plussym, &countTokens, lineNumber);
        }

        // Check for -
        if (ch == '-') {
            matched = 1;
            addToList(&tokens, "-", 0, minussym, &countTokens, lineNumber);
        }

        // Check for *
        if (ch == '*') {
            matched = 1;
            addToList(&tokens, "*", 0, multsym, &countTokens, lineNumber);
        }

        // Check for /
        if (ch == '/') {
            matched = 1;
            addToList(&tokens, "/", 0, slashsym, &countTokens, lineNumber);
        }

        // Increment line number on newline
        if (ch == '\n')
            lineNumber++;

        // Throw error for invalid character
        if (!matched && ch != ' ' && ch != '\n' && ch != '\r' && ch != -1 && ch != 9) {
            fprintf(stdout, "[SCANNER-ERROR] Invalid character '%c'. line %d.\n", ch, lineNumber);
            exit(EXIT_FAILURE);
        }
    }

    // Close input
	fclose(ifp);

    // Write lexeme table
    FILE* lexTblPtr = openFileScanner(lexTablePath, "w");
    FILE* tokLstPtr = openFileScanner(tokenListPath, "w");
    writeTokens(firstToken, lexTblPtr, tokLstPtr, countTokens);

    // Close output
    fclose(lexTblPtr);
    fclose(tokLstPtr);

	return 0;
}
示例#17
0
void Hdf::open(const char *filename) {
  close();
  append(filename);
}
示例#18
0
TextStream& TextStream::operator<<(const String& string)
{
    append(m_text, string);
    return *this;
}
示例#19
0
Hdf::Hdf(const std::string &filename) : m_hdf(nullptr), m_dump(nullptr) {
  m_rawp = new HdfRaw();
  append(filename.c_str());
}
示例#20
0
void UrlRetrievalModel::append(const QStringList &urls, const QString &pluginId) {
    foreach (const QString &url, urls) {
        append(url, pluginId);
    }
示例#21
0
	void UString::append(char c)
	{
		append(&c, 1);
	}
示例#22
0
 /** Appends an object to the vector, equals append(x). This method
 has been implemented so that this class looks and feels more
 like a typical STL container. */
 void push_back(const T & x) { append(x); }
示例#23
0
文件: PLTOC.C 项目: jbailhache/log
append (struct coroutine *k,
	expr a, expr b, expr c)
{
#ifndef OLD
	begin_decl ();
	decl_expr (&a);
	decl_expr (&b);
	decl_expr (&c);

#endif
#ifdef TRACE
	printf ("\na = "); print_expr (a);
	printf ("\nb = "); print_expr (b);
	printf ("\nc = "); print_expr (c);
#endif
	if (alt (k, 1, 0))
	/* append ([], L, L) */
	{
	expr l, var_l;
#ifndef OLD
		decl_loc (l);
		decl_loc (var_l);
#endif
		l = UNDEF;
		var_l = mk_var (&l);

		unify (k, nil, a);
		unify (k, var_l, b);
		unify (k, var_l, c);
#ifdef TRACE
	printf ("\nvar_l = "); print_expr (var_l);
#endif
		unify (k, a, nil);
		unify (k, b, var_l);
		unify (k, c, var_l);
#ifdef TRACE
	printf ("\na = "); print_expr (a);
	printf ("\nb = "); print_expr (b);
	printf ("\nc = "); print_expr (c);
#endif
		/* free (var_l); */
	}
	else
	/* append ([X|A], B, [X|C]) :- append (A, B, C) */
	{
	expr X, A, B, C, _X, _A, _B, _C, XA, XC;
#ifndef OLD
		dle(X) dle(A) dle(B) dle(X)
		dle(_X) dle(_A) dle(_B) dle(_C)
		dle(XA) dle(XC)
#endif
		X = UNDEF;
		A = UNDEF;
		B = UNDEF;
		C = UNDEF;

		_X = mk_var (&X);
		_A = mk_var (&A);
		_B = mk_var (&B);
		_C = mk_var (&C);

		XA = cons (_X, _A);
		XC = cons (_X, _C);
#ifdef TRACE
		printf ("\nXA = "); print_expr (XA);
		printf ("\n_B = "); print_expr (_B);
		printf ("\nXC = "); print_expr (XC);
		printf ("\na = "); print_expr (a);
		printf ("\nb = "); print_expr (b);
		printf ("\nc = "); print_expr (c);
#endif
		unify (k, XA, a);
		unify (k, _B, b);
		unify (k, XC, c);
#ifdef TRACE
		printf ("\nXA = "); print_expr (XA);
		printf ("\n_B = "); print_expr (_B);
		printf ("\nXC = "); print_expr (XC);
#endif

		append (k, _A, _B, _C);
#ifdef TRACE
		printf ("\n_A = "); print_expr (_A);
		printf ("\n_B = "); print_expr (_B);
		printf ("\n_C = "); print_expr (_C);

		printf ("\nXA = "); print_expr (XA);
		printf ("\n_B = "); print_expr (_B);
		printf ("\nXC = "); print_expr (XC);
#endif
		unify (k, a, XA);
		unify (k, b, _B);
		unify (k, c, XC);
#ifdef TRACE
	printf ("\na = "); print_expr (a);
	printf ("\nb = "); print_expr (b);
	printf ("\nc = "); print_expr (c);
#endif
		/*
		free (_X);
		free (_A);
		free (_B);
		free (_C);
		free (XA);
		free (XC);
		*/
	}
#ifndef OLD
	free_expr ();
#endif
}
示例#24
0
int processdir(int level, const char *base, const char *dirname, struct stat *sb,
	struct filenode *dir, struct filenode *root, int curroffset)
{
	DIR *dirfd;
	struct dirent *dp;
	struct filenode *n, *link;
	struct excludes *pe;

	if (level <= 1) {
		/* Ok, to make sure . and .. are handled correctly
		 * we add them first.  Note also that we alloc them
		 * first to get to know the real name
		 */
		link = newnode(base, ".", curroffset);
		if (!lstat(link->realname, sb)) {
			setnode(link, sb->st_dev, sb->st_ino, sb->st_mode);
			append(&dir->dirlist, link);

			/* special case for root node - '..'s in subdirs should link to
			 *   '.' of root node, not root node itself.
			 */
			dir->dirlist.owner = link;

			curroffset = alignnode(link, curroffset, 0) + spaceneeded(link);
			n = newnode(base, "..", curroffset);

			if (!lstat(n->realname, sb)) {
				setnode(n, sb->st_dev, sb->st_ino, sb->st_mode);
				append(&dir->dirlist, n);
				n->orig_link = link;
				curroffset = alignnode(n, curroffset, 0) + spaceneeded(n);
			}
		}
	}

	dirfd = opendir(dir->realname);
	while((dp = readdir(dirfd))) {
		/* don't process main . and .. twice */
		if (level <= 1 &&
		    (strcmp(dp->d_name, ".") == 0
		     || strcmp(dp->d_name, "..") == 0))
			continue;
		n = newnode(base, dp->d_name, curroffset);

		/* Process exclude list. */
		for (pe = excludelist; pe; pe = pe->next) {
			if (!nodematch(pe->pattern, n)) { freenode(n); break; }
		}
		if (pe) continue;

		if (lstat(n->realname, sb)) {
			fprintf(stderr, "ignoring '%s' (lstat failed)\n", n->realname);
			freenode(n); continue;
		}

		/* Handle special names */
		if ( n->name[0] == '@' ) {
			if (S_ISLNK(sb->st_mode)) {
				/* this is a link to follow at build time */
				n->name = n->name + 1; /* strip off the leading @ */
				memset(bigbuf, 0, sizeof(bigbuf));
				readlink(n->realname, bigbuf, sizeof(bigbuf));
				n->realname = strdup(bigbuf);

				if (lstat(n->realname, sb)) {
					fprintf(stderr, "ignoring '%s' (lstat failed)\n",
						n->realname);
					freenode(n); continue;
				}
			} else if (S_ISREG(sb->st_mode) && sb->st_size == 0) {
				/*
				 *        special file @name,[bcp..],major,minor
				 */
				char      devname[32];
				char      type;
				int       major;
				int       minor;
						
				if (sscanf(n->name, "@%[a-zA-Z0-9],%c,%d,%d",
					   devname, &type, &major, &minor) == 4 ) {
					strcpy(n->name, devname);
					sb->st_rdev = makedev(major, minor);
					sb->st_mode &= ~S_IFMT;
					switch (type) {
					case 'c':
					case 'u':
						sb->st_mode |= S_IFCHR;
						break;
					case 'b':
						sb->st_mode |= S_IFBLK;
						break;
					case 'p':
						sb->st_mode |= S_IFIFO;
						break;
					default:
						fprintf(stderr, "Invalid special device type '%c' "
							"for file %s\n", type, n->realname);
						freenode(n);
						continue;
					}
				}
			}
		}

		setnode(n, sb->st_dev, sb->st_ino, sb->st_mode);
		/* Skip unreadable files/dirs */
		if (!S_ISLNK(n->modes) && access(n->realname, R_OK)) {
			fprintf(stderr, "ignoring '%s' (access failed)\n", n->realname);
			freenode(n); continue;
		}

		/* Look up old links */
		if ( strcmp(n->name, ".") == 0 ) {
			append(&dir->dirlist, n);
			link = n->parent;
		} else if (strcmp(n->name, "..") == 0) {
			append(&dir->dirlist, n);
			link = n->parent->parent;
		} else {
			link = findnode(root, n->ondev, n->onino);
			append(&dir->dirlist, n);
		}

		if (link) {
			n->orig_link = link;
			curroffset = alignnode(n, curroffset, 0) + spaceneeded(n);
			continue;
		}
		if (S_ISREG(sb->st_mode)) {
			curroffset = alignnode(n, curroffset, spaceneeded(n));
			n->size = sb->st_size;
		} else
			curroffset = alignnode(n, curroffset, 0);
		if (S_ISLNK(sb->st_mode)) {
			n->size = sb->st_size;
		}
		curroffset += spaceneeded(n);
		if (S_ISCHR(sb->st_mode) || S_ISBLK(sb->st_mode)) {
			n->devnode = sb->st_rdev;
		}

		if (S_ISDIR(sb->st_mode)) {
			if (!strcmp(n->name, "..")) {
				curroffset = processdir(level+1, dir->realname, dp->d_name,
							sb, dir, root, curroffset);
			} else {
				curroffset = processdir(level+1, n->realname, dp->d_name,
							sb, n, root, curroffset);
			}
		}
	}
	closedir(dirfd);
	return curroffset;
}
示例#25
0
 FilePath& FilePath::operator/=(const FilePath& pOther)
 {
   append(pOther);
   return *this;
 }
示例#26
0
void DatumMapBuilder::pushBack(const bslstl::StringRef& key,
                               const Datum&             value)
{
    DatumMapEntry entry(key, value);
    append(&entry, 1);
}
示例#27
0
// Inserts at the end postion (tailer).
UtlContainable* UtlSList::insert(UtlContainable* obj)
{
    return append(obj);
}
示例#28
0
static int on_read(const lsi_session_t *session)
{
    unsigned char md5[16];
    char buf[8192];
    int ret, i;
    int readbytes = 0, written = 0;
    mydata_t *mydata = (mydata_t *)g_api->get_module_data(session, &MNAME,
                       LSI_DATA_HTTP);
    if (mydata == NULL || mydata->type == 0)
    {
        g_api->end_resp(session);
        return 0;
    }

    while ((ret = g_api->read_req_body(session, buf, sizeof(buf))) > 0)
    {
        mydata->rcvd_req_body_len += ret;
        readbytes += ret;

        if (mydata->type == 1)
        {
            append(session, buf, ret);
            written += ret;
        }
        else if (mydata->type == 2)
            MD5_Update(&mydata->ctx, buf, ret);
        else
            fwrite(buf, 1, ret, mydata->fp);

        if (mydata->rcvd_req_body_len >= mydata->req_body_len)
        {
            mydata->rcvd_done = 1;
            break;
        }
    }
    if (ret == 0)
        mydata->rcvd_done = 1;

    if (mydata->rcvd_done == 1)
    {
        if (mydata->type == 2)
        {
            MD5_Final(md5, &mydata->ctx);
            for (i = 0; i < 16; ++i)
                sprintf(buf + i * 2, "%02X", md5[i]);
            append(session, "MD5 is<br>", 10);
            append(session, buf, 32);
            written += 42;
        }
        else if (mydata->type == 3)
        {
            if (mydata->fp != NULL)
            {
                fclose(mydata->fp);
                mydata->fp = NULL;
                append(session, "File uploaded.<br>", 18);
                written += 18;
            }
        }
        mydata->resp_done = 1;
    }

    if (written > 0)
        g_api->flush(session);
    g_api->set_handler_write_state(session, 1);
    //g_api->end_resp(session);
    return readbytes;
}
示例#29
0
void str::append(int x)
{
    char intValString[16];
    sprintf(intValString, "%i", x);
    append(intValString);
}
示例#30
0
static void DefDomain(struct net_object *netobj, struct net_object *unf_netobj)
{
struct place_object *place;
char *great_domain, *class_name = UNCOLORED_CLASS_NAME;
list curr=NULL, l=NULL;
int i=1;
int cardinality;
ClassObjPTR c;
DomainObjPTR d;
markPTR m;


init_list(&gListDomain);
init_list(&gListMarking);


for( place = netobj->places; place != NULL; place = place->next)
 {
  YACCobj_name = place->tag;
  /* definizione dominio */
  if((great_domain = READ_DOMAIN(place)) != NULL) // se dominio colorato
  {
   LEXtoParsifyString = NewStringCat("~w ", great_domain); 
   EraseFinalCR(LEXtoParsifyString);

   yyparse();   
   
   #if DEBUG_UNFOLD
//    TEST PLACE DOMAIN         
     curr = NULL;
     printf("\n%s) ", YACCparsedDomain->place_name);
     while ( (curr = list_iterator(YACCparsedDomain->class_list, curr)) != NULL ){
       printf("%s ", ((ClassObjPTR) DATA(curr))->name);        
     }
     printf("\n");
   #endif
   
   cardinality =1;   
   curr = NULL;
   while ( (curr = list_iterator(YACCparsedDomain->class_list, curr)) != NULL )
     cardinality *=  ((ClassObjPTR) DATA(curr))->num_el;
      
   init_set(YACCparsedDomain->create_place, cardinality);
   append(&gListDomain, (generic_ptr) YACCparsedDomain);
   
   
   if(place->cmark!=NULL) {
          
     YACCobj_name = place->cmark->tag;
     LEXtoParsifyString = NewStringCat("~m ",place->cmark->text);
     EraseFinalCR(LEXtoParsifyString);    
     yyparse();
     YACCparsedMarking->place = place;
//      evalMarking(YACCparsedMarking, &p_MS);
     append(&gListMarking, (generic_ptr) YACCparsedMarking);
     
     
     #if DEBUG_UNFOLD
       printf("Marking: %s\n", PrintMarking(YACCparsedMarking)); 
//        printMultiset(p_MS);
     #endif
   
   }   
  }
  else { // dominio non colorato
    init_list(&l);    
    
    if((find_key(gListClasses, (generic_ptr) class_name, CmpClassName, &curr))==ERROR)
      Error(CLASS_DEF_ERR, "DefDomain", NULL);
    else
    { 
      head_insert(&l, DATA(curr));      
      YACCparsedDomain = NewDomain(place->tag, l, 1);     
      init_set(YACCparsedDomain->create_place, 1);
      append(&gListDomain, (generic_ptr) YACCparsedDomain);
    }
    #if DEBUG_UNFOLD
//  TEST PLACE DOMAIN         
    curr = NULL;
    printf("\n%s) ", YACCparsedDomain->place_name);
    while ( (curr = list_iterator(YACCparsedDomain->class_list, curr)) != NULL ){
      printf("%s ", ((ClassObjPTR) DATA(curr))->name);        
    }
    printf("\n");
    #endif   
        
    if(place->mpar!=NULL){
      
      YACCparsedMarking = NewMarking(place->mpar->tag, (generic_ptr) place->mpar);
      YACCparsedMarking->type = 1;
      
    }
    else{
      YACCobj_name = ""; 
      LEXtoParsifyString = EmptyString();
      
      sprintf(LEXtoParsifyString, "~m <%d S>",place->m0);       
      yyparse();  
      YACCparsedMarking->type = 0;
    } 
    YACCparsedMarking->place = place;                 
//     evalMarking(YACCparsedMarking, &p_MS);
    head_insert(&gListMarking, (generic_ptr) YACCparsedMarking);
            
  }  

     
 }
  


}