/** branches the searching tree, branching nodes are selected in decreasing order of their apriori bound, * returns the level to which we should backtrack, or INT_MAX for continuing normally */ static int branch( TCLIQUE_GETNNODES((*getnnodes)), /**< user function to get the number of nodes */ TCLIQUE_GETWEIGHTS((*getweights)), /**< user function to get the node weights */ TCLIQUE_ISEDGE((*isedge)), /**< user function to check for existence of an edge */ TCLIQUE_SELECTADJNODES((*selectadjnodes)),/**< user function to select adjacent edges */ TCLIQUE_GRAPH* tcliquegraph, /**< pointer to graph data structure */ TCLIQUE_NEWSOL((*newsol)), /**< user function to call on every new solution */ TCLIQUE_DATA* tcliquedata, /**< user data to pass to user callback function */ BMS_CHKMEM* mem, /**< block memory */ CLIQUEHASH* cliquehash, /**< clique hash table */ int* buffer, /**< buffer of size nnodes */ int level, /**< level of b&b tree */ int* V, /**< non-zero weighted nodes for branching */ int nV, /**< number of non-zero weighted nodes for branching */ int* Vzero, /**< zero weighted nodes */ int nVzero, /**< number of zero weighted nodes */ NBC* gsd, /**< neighbour color information of all nodes */ TCLIQUE_Bool* iscolored, /**< coloring status of all nodes */ int* K, /**< nodes from the b&b tree */ TCLIQUE_WEIGHT weightK, /**< weight of the nodes from b&b tree */ int* maxcliquenodes, /**< pointer to store nodes of the maximum weight clique */ int* nmaxcliquenodes, /**< pointer to store number of nodes in the maximum weight clique */ TCLIQUE_WEIGHT* maxcliqueweight, /**< pointer to store weight of the maximum weight clique */ int* curcliquenodes, /**< pointer to store nodes of currenct clique */ int* ncurcliquenodes, /**< pointer to store number of nodes in current clique */ TCLIQUE_WEIGHT* curcliqueweight, /**< pointer to store weight of current clique */ int* tmpcliquenodes, /**< buffer for storing the temporary clique */ TCLIQUE_WEIGHT maxfirstnodeweight, /**< maximum weight of branching nodes in level 0; 0 if not used * (for cliques with at least one fractional node) */ int* ntreenodes, /**< pointer to store number of nodes of b&b tree */ int maxntreenodes, /**< maximal number of nodes of b&b tree */ int backtrackfreq, /**< frequency to backtrack to first level of tree (0: no premature backtracking) */ int maxnzeroextensions, /**< maximal number of zero-valued variables extending the clique */ int fixednode, /**< node that is forced to be in the clique, or -1; must have positive weight */ TCLIQUE_STATUS* status /**< pointer to store the status of the solving call */ ) { TCLIQUE_Bool isleaf; const TCLIQUE_WEIGHT* weights; TCLIQUE_WEIGHT* apbound; TCLIQUE_WEIGHT subgraphweight; TCLIQUE_WEIGHT weightKold; TCLIQUE_WEIGHT tmpcliqueweight; int backtracklevel; int ntmpcliquenodes; int i; assert(getnnodes != NULL); assert(getweights != NULL); assert(selectadjnodes != NULL); assert(mem != NULL); assert(V != NULL); assert(gsd != NULL); assert(iscolored != NULL); assert(K != NULL); assert(maxcliqueweight != NULL); assert(curcliquenodes != NULL); assert(ncurcliquenodes != NULL); assert(curcliqueweight != NULL); assert(ntreenodes != NULL); assert(maxfirstnodeweight >= 0); assert(*ntreenodes >= 0); assert(maxntreenodes >= 0); assert(status != NULL); /* increase the number of nodes, and stop solving, if the node limit is exceeded */ (*ntreenodes)++; #ifdef TCLIQUE_DEBUG debugMessage("(level %d, treenode %d) maxclique = %d, curclique = %d [mem=%"SCIP_LONGINT_FORMAT" (%"SCIP_LONGINT_FORMAT"), cliques=%d]\n", level, *ntreenodes, *maxcliqueweight, *curcliqueweight, BMSgetChunkMemoryUsed(mem), BMSgetMemoryUsed(), cliquehash == NULL ? 0 : cliquehash->ncliques); debugMessage(" -> current branching (weight %d):", weightK); for( i = 0; i < level; ++i ) debugPrintf(" %d", K[i]); debugPrintf("\n"); debugMessage(" -> branching candidates:"); for( i = 0; i < nV; ++i ) debugPrintf(" %d", V[i]); debugPrintf("\n"); #endif if( *ntreenodes > maxntreenodes ) { *status = TCLIQUE_NODELIMIT; return TRUE; } weights = getweights(tcliquegraph); backtracklevel = INT_MAX; isleaf = TRUE; /* allocate temporary memory for a priori bounds */ ALLOC_ABORT( BMSallocMemoryArray(&apbound, nV) ); BMSclearMemoryArray(apbound, nV); /* use coloring relaxation to generate an upper bound for the current subtree and a heuristic solution */ subgraphweight = boundSubgraph(getnnodes, getweights, isedge, selectadjnodes, tcliquegraph, mem, buffer, V, nV, gsd, iscolored, apbound, tmpcliquenodes, &ntmpcliquenodes, &tmpcliqueweight); #ifndef NDEBUG /* check correctness of V and apbound arrays */ for( i = 0; i < nV; ++i ) { assert(0 <= V[i] && V[i] < getnnodes(tcliquegraph)); assert(i == 0 || V[i-1] < V[i]); assert(apbound[i] >= 0); assert((apbound[i] == 0) == (weights[V[i]] == 0)); } #endif /* check, whether the heuristic solution is better than the current subtree's solution; * if the user wanted to have a fixed variable inside the clique and we are in level 0, we first have to * fix this variable in this level (the current clique might not contain the fixed node) */ if( weightK + tmpcliqueweight > *curcliqueweight && (level > 0 || fixednode == -1) ) { /* install the newly generated clique as current clique */ for( i = 0; i < level; ++i ) curcliquenodes[i] = K[i]; for( i = 0; i < ntmpcliquenodes; ++i ) curcliquenodes[level+i] = tmpcliquenodes[i]; *ncurcliquenodes = level + ntmpcliquenodes; *curcliqueweight = weightK + tmpcliqueweight; #ifdef TCLIQUE_DEBUG debugMessage(" -> new current clique with weight %d at node %d in level %d:", *curcliqueweight, *ntreenodes, level); for( i = 0; i < *ncurcliquenodes; ++i ) debugPrintf(" %d", curcliquenodes[i]); debugPrintf("\n"); #endif } /* discard subtree, if the upper bound is not better than the weight of the currently best clique; * if only 2 nodes are left, the maximal weighted clique was already calculated in boundSubgraph() and nothing * more has to be done; * however, if the user wanted to have a fixed node and we are in the first decision level, we have to continue */ if( weightK + subgraphweight > *maxcliqueweight && (nV > 2 || (fixednode >= 0 && level == 0)) ) { int* Vcurrent; int nVcurrent; int nValive; int branchingnode; assert(nV > 0); /* process current subtree */ level++; /* set up data structures */ ALLOC_ABORT( BMSallocMemoryArray(&Vcurrent, nV-1) ); nValive = nV; weightKold = weightK; debugMessage("============================ branching level %d ===============================\n", level); /* branch on the nodes of V by decreasing order of their apriori bound */ while( backtracklevel >= level && nValive > 0 ) { int branchidx; /* check if we meet the backtracking frequency - in this case abort the search until we have reached first level */ if( level > 1 && backtrackfreq > 0 && (*ntreenodes) % backtrackfreq == 0 ) { backtracklevel = 1; break; } /* get next branching node */ if( level == 1 && fixednode >= 0 ) { /* select the fixed node as first "branching" candidate */ for( branchidx = 0; branchidx < nValive && V[branchidx] != fixednode; branchidx++ ) {} assert(branchidx < nValive); assert(V[branchidx] == fixednode); } else if( level == 1 && maxfirstnodeweight > 0 ) branchidx = getMaxApBoundIndexNotMaxWeight(V, nValive, apbound, weights, maxfirstnodeweight); else branchidx = getMaxApBoundIndex(nValive, apbound); if( branchidx < 0 ) break; assert(0 <= branchidx && branchidx < nValive && nValive <= nV); assert(apbound[branchidx] > 0); assert(weights[V[branchidx]] > 0); /* test a priori bound */ if( (weightKold + apbound[branchidx]) <= *maxcliqueweight ) break; debugMessage("%d. branching in level %d (treenode %d): bidx=%d, node %d, weight %d, upperbound: %d+%d = %d, maxclique=%d\n", nV-nValive+1, level, *ntreenodes, branchidx, V[branchidx], weights[V[branchidx]], weightKold, apbound[branchidx], weightKold + apbound[branchidx], *maxcliqueweight); /* because we branch on this node, the node is no leaf in the tree */ isleaf = FALSE; /* update the set of nodes from the b&b tree * K = K & {branchingnode} */ branchingnode = V[branchidx]; K[level-1] = branchingnode; weightK = weightKold + weights[branchingnode]; /* update the set of nodes for branching * V = V \ {branchingnode} */ nValive--; for( i = branchidx; i < nValive; ++i ) { V[i] = V[i+1]; apbound[i] = apbound[i+1]; } /* set the nodes for the next level of b&b tree * Vcurrent = nodes of V, that are adjacent to branchingnode */ nVcurrent = selectadjnodes(tcliquegraph, branchingnode, V, nValive, Vcurrent); /* process the selected subtree */ backtracklevel = branch(getnnodes, getweights, isedge, selectadjnodes, tcliquegraph, newsol, tcliquedata, mem, cliquehash, buffer, level, Vcurrent, nVcurrent, Vzero, nVzero, gsd, iscolored, K, weightK, maxcliquenodes, nmaxcliquenodes, maxcliqueweight, curcliquenodes, ncurcliquenodes, curcliqueweight, tmpcliquenodes, maxfirstnodeweight, ntreenodes, maxntreenodes, backtrackfreq, maxnzeroextensions, -1, status); /* if all other candidates stayed in the candidate list, the current branching was optimal and * there is no need to try the remaining ones */ if( nVcurrent == nValive ) { debugMessage("branching on node %d was optimal - ignoring remaining candidates\n", branchingnode); nValive = 0; } /* if we had a fixed node, ignore all other nodes */ if( fixednode >= 0 ) nValive = 0; } debugMessage("========================== branching level %d end =============================\n\n", level); /* free data structures */ BMSfreeMemoryArray(&Vcurrent); } /* check, whether any branchings have been applied, or if this node is a leaf of the branching tree */ if( isleaf ) { /* the current clique is the best clique found on the path to this leaf * -> check, whether it is an improvement to the currently best clique */ if( *curcliqueweight > *maxcliqueweight ) { TCLIQUE_Bool stopsolving; debugMessage("found clique of weight %d at node %d in level %d\n", *curcliqueweight, *ntreenodes, level); newSolution(selectadjnodes, tcliquegraph, newsol, tcliquedata, cliquehash, buffer, Vzero, nVzero, maxnzeroextensions, curcliquenodes, *ncurcliquenodes, *curcliqueweight, maxcliquenodes, nmaxcliquenodes, maxcliqueweight, &stopsolving); if( stopsolving ) { debugMessage(" -> solving terminated by callback method\n"); backtracklevel = 0; } } /* discard the current clique */ *ncurcliquenodes = 0; *curcliqueweight = 0; } #ifdef TCLIQUE_DEBUG if( level > backtracklevel ) { debugMessage("premature backtracking after %d nodes - level %d\n", *ntreenodes, level); } #endif /* free data structures */ BMSfreeMemoryArray(&apbound); return backtracklevel; }
void createEntry(TString infostream, std::vector<TString> fileList_, bool save, unsigned int verbose){ // extract relavant information from infostream TString recoTreeLocation =getStringEntry(infostream,1,":"); TString genTreeLocation =getStringEntry(infostream,2,":"); TString outputRecoFolderLocation=getStringEntry(infostream,3,":"); TString outputGenFolderLocation =getStringEntry(infostream,4,":"); TString newVarName =getStringEntry(infostream,5,":"); TString newVarBinning =getStringEntry(infostream,6,":"); TString fillFrom =getStringEntry(infostream,7,":"); TString eventWeight =getStringEntry(infostream,8,":"); TString withCondition =getStringEntry(infostream,9,":"); //loop files for(unsigned int fileix=0; fileix<fileList_.size(); ++fileix){ TString name=fileList_[fileix]; if(verbose>1) std::cout << std::endl << "processing file " << name << std::endl; // check if ttbarSG file is processed bool ttbarSG= (name.Contains("Sig")) ? true : false; bool ttbarCentral = (ttbarSG&&!(name.Contains("Up")||name.Contains("Down")||name.Contains("Mcatnlo")||name.Contains("Powheg"))) ? true : false; // container for values read from tree std::map< TString, float > value_; // A open file TFile* file = TFile::Open(name, "Update"); if(!file||file->IsZombie()) std::cout << "ERROR: file " << name << " does not exist or is broken" << std::endl; else{ file->cd(); // B1 open reco tree TTree* recotree=(TTree*)(file->Get(recoTreeLocation+"/tree")->Clone()); if(!recotree||recotree->IsZombie()){ std::cout << "ERROR: can not load the chosen recotree " << recoTreeLocation+"/tree in file " << name << std::endl; } else{ // info output if(fileix==0&&verbose>1) std::cout << "recotree: " << recoTreeLocation+"/tree" << std::endl; // activate all branches recotree->SetBranchStatus("*",1); // get all branches from recotree TObjArray* branches=recotree->GetListOfBranches(); // loop all branches TObjArrayIter branch(branches); TObject* object; while ( ( object = branch() ) ) { // get single branch TString branchname=(TString)object->GetName(); // info output if(fileix==0&&verbose>1) std::cout << "->reco branch : " << branchname << std::endl; // set branch address for access recotree->SetBranchAddress(branchname,(&value_[branchname])); } // B2a create reco histo int nbins =(getStringEntry(newVarBinning,1,",")).Atoi(); double min=(getStringEntry(newVarBinning,2,",")).Atof(); double max=(getStringEntry(newVarBinning,3,",")).Atof(); TH1F* newRecPlot=new TH1F( newVarName+"Rec", newVarName, nbins , min , max); // B2b create reco branch entry Float_t newRec1; Float_t newRec2; TBranch *newRecBranch1 = recotree->Branch(newVarName+"Lep", &newRec1, newVarName+"Lep"+"/F"); TBranch *newRecBranch2 = recotree->Branch(newVarName+"Had", &newRec2, newVarName+"Had"+"/F"); // info output if(fileix==0&&verbose>1){ std::cout << "will add new reco plot: new TH1F(" << newVarName << ", " << newVarName; std::cout << ", " << nbins << ", " << min << ", " << max << ") in " << outputRecoFolderLocation << std::endl; std::cout << "will add new branches " << newVarName+"Lep" << " and " << newVarName+"Had"; std::cout << ") in tree " << recoTreeLocation+"/tree" << std::endl; } // B3a create gen-reco histo TH2F* newRecGenPlot; Float_t newRecGen1; Float_t newRecGen2; TBranch *newRecGenBranch1 =0; TBranch *newRecGenBranch2 =0; if(ttbarSG){ newRecGenPlot=new TH2F( newVarName+"_", newVarName+"_", nbins , min , max, nbins , min , max); if(fileix==0&&verbose>1){ std::cout << "will add new gen-reco plot: new TH2F(" << newVarName+"_" << ", " << newVarName+"_"; std::cout << ", " << nbins << ", " << min << ", " << max << ", " << std::endl; std::cout << ", " << nbins << ", " << min << ", " << max << ")" << std::endl; } // B3b create gen branch entry newRecGenBranch1 = recotree->Branch(newVarName+"Lep"+"PartonTruth", &newRecGen1, newVarName+"Lep"+"PartonTruth"+"/F"); newRecGenBranch2 = recotree->Branch(newVarName+"Had"+"PartonTruth", &newRecGen2, newVarName+"Had"+"PartonTruth"+"/F"); } // B4 fill reco plots from tree // loop recotree for(unsigned int event=0; event<recotree->GetEntries(); ++event){ recotree->GetEntry(event); // B4a fill rec branch newRec1=value_["topPtLep"]*value_["topPtLep"]; newRec2=value_["topPtHad"]*value_["topPtHad"]; newRecBranch1->Fill(); newRecBranch2->Fill(); // B4b fill rec plot newRecPlot->Fill(newRec1, value_["weight"]); newRecPlot->Fill(newRec2, value_["weight"]); // fill rec-gen plot if(newRecGenPlot){ newRecGen1=value_["topPtLepPartonTruth"]*value_["topPtLepPartonTruth"]; newRecGen2=value_["topPtHadPartonTruth"]*value_["topPtHadPartonTruth"]; newRecGenBranch1->Fill(); newRecGenBranch2->Fill(); newRecGenPlot->Fill(newRecGen1, newRec1, value_["weight"]); newRecGenPlot->Fill(newRecGen2, newRec2, value_["weight"]); } } // B5 saving if(save){ if(fileList_.size()==1){ TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", "")); if(newRecPlot ) saveToRootFile("test.root", newRecPlot , true, 1, outputRecoFolderLocation+"/"+debugName); if(newRecGenPlot) saveToRootFile("test.root", newRecGenPlot, true, 1, outputRecoFolderLocation+"/"+debugName); } file->cd(outputRecoFolderLocation); if(newRecPlot ) newRecPlot ->Write(newRecPlot->GetTitle() , TObject::kOverwrite); if(newRecGenPlot) newRecGenPlot->Write(newRecGenPlot->GetTitle(), TObject::kOverwrite); if(recotree) recotree->Write(recotree->GetTitle(), TObject::kOverwrite); file->cd(); } // end if save } // end if recotree if(ttbarSG){ if(verbose>1) std::cout << "-> ttbarSG file! gen and reco-gen will be derived" << std::endl; // C open gen tree TTree* gentree=(TTree*)(file->Get(genTreeLocation+"/tree")->Clone()); if(!gentree||gentree->IsZombie()){ std::cout << "ERROR: can not load the chosen gentree " << genTreeLocation+"/tree in file " << name << std::endl; } else{ // info output if(fileix==0&&verbose>1) std::cout << "gentree: " << genTreeLocation+"/tree" << std::endl; // activate all branches gentree->SetBranchStatus("*",1); // get all branches from recotree TObjArray* branches=gentree->GetListOfBranches(); // loop all branches TObjArrayIter branch(branches); TObject* object; while ( ( object = branch() ) ) { // get single branch TString branchname=(TString)object->GetName(); // info output if(fileix==0&&verbose>1) std::cout << "->gen branch : " << branchname << std::endl; // set branch address for access gentree->SetBranchAddress(branchname,(&value_[branchname])); } // C2a create gen histo int nbins =(getStringEntry(newVarBinning,1,",")).Atoi(); double min=(getStringEntry(newVarBinning,2,",")).Atof(); double max=(getStringEntry(newVarBinning,3,",")).Atof(); TH1F* newGenPlot=new TH1F( newVarName+"Gen", newVarName, nbins , min , max); // C2b create gen branch entry Float_t newGen1; Float_t newGen2; TBranch *newGenBranch1 = gentree->Branch(newVarName+"Lep", &newGen1, newVarName+"Lep"+"/F"); TBranch *newGenBranch2 = gentree->Branch(newVarName+"Had", &newGen2, newVarName+"Had"+"/F"); // info output if(fileix==0&&verbose>1){ std::cout << "will add new gen plot: new TH1F(" << newVarName << ", " << newVarName; std::cout << ", " << nbins << ", " << min << ", " << max << ")" << std::endl; } // C3 fill gen plots from tree // loop gentree for(unsigned int event=0; event<gentree->GetEntries(); ++event){ gentree->GetEntry(event); // C3a fill gen branches newGen1=value_["topPtLep"]*value_["topPtLep"]; newGen2=value_["topPtHad"]*value_["topPtHad"]; newGenBranch1->Fill(); newGenBranch2->Fill(); // C3b fill gen plot newGenPlot->Fill(newGen1, value_["weight"]); newGenPlot->Fill(newGen2, value_["weight"]); } // C4 saving if(save){ if(fileList_.size()==1){ TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", "")); if(newGenPlot ) saveToRootFile("test.root", newGenPlot , true, 1, outputGenFolderLocation+"/"+debugName ); } file->cd(outputGenFolderLocation); if(newGenPlot) newGenPlot->Write(newGenPlot->GetTitle(), TObject::kOverwrite); if(gentree ) gentree->Write(gentree->GetTitle(), TObject::kOverwrite); file->cd(); } // end if save // D process additional folders if(verbose>1&&ttbarCentral) std::cout << " -> central ttbarSG file! need to process additional folders for systematic variations" << std::endl; } // end if gentree } // end if ttbarSG } // end if file // close file file->Close(); } // end loop files }
void generate_component(component comp, const char *mlabel, bool discard, fncode fn) { clist args; switch (comp->vclass) { case c_assign: { u16 offset; mtype t; variable_class vclass = env_lookup(comp->l, comp->u.assign.symbol, &offset, &t, FALSE); component val = comp->u.assign.value; if (val->vclass == c_closure) { /* Defining a function, give it a name */ if (vclass == global_var) val->u.closure->varname = comp->u.assign.symbol; else { char *varname = allocate(fnmemory(fn), strlen(comp->u.assign.symbol) + 7); sprintf(varname, "local-%s", comp->u.assign.symbol); val->u.closure->varname = varname; } } generate_component(comp->u.assign.value, NULL, FALSE, fn); if (t != stype_any) ins0(OPmscheck4 + t, fn); if (vclass == global_var) massign(comp->l, offset, comp->u.assign.symbol, fn); else if (vclass == closure_var) ins1(OPmwritec, offset, fn); else ins1(OPmwritel, offset, fn); /* Note: varname becomes a dangling pointer when fnmemory(fn) is deallocated, but it is never used again so this does not cause a problem. */ break; } case c_recall: scompile_recall(comp->l, comp->u.recall, fn); break; case c_constant: ins_constant(make_constant(comp->u.cst, FALSE, fn), fn); break; case c_scheme: scheme_compile_mgc(comp->l, make_constant(comp->u.cst, TRUE, fn), discard, fn); discard = FALSE; break; case c_closure: generate_function(comp->u.closure, fn); break; case c_block: generate_block(comp->u.blk, discard, fn); discard = FALSE; break; case c_decl: { vlist decl, next; /* declare variables one at a time (any x = y, y = 2; is an error) */ for (decl = comp->u.decls; decl; decl = next) { next = decl->next; decl->next = NULL; env_declare(decl); generate_decls(decl, fn); } generate_component(component_undefined, NULL, FALSE, fn); break; } case c_labeled: { start_block(comp->u.labeled.name, FALSE, discard, fn); generate_component(comp->u.labeled.expression, comp->u.labeled.name, discard, fn); end_block(fn); discard = FALSE; break; } case c_exit: { bool discard_exit; label exitlab = exit_block(comp->u.labeled.name, FALSE, &discard_exit, fn); if (comp->u.labeled.expression != component_undefined && discard_exit) warning(comp->l, "break result is ignored"); generate_component(comp->u.labeled.expression, NULL, discard_exit, fn); if (exitlab) branch(OPmba3, exitlab, fn); else { if (!comp->u.labeled.name) log_error(comp->l, "No loop to exit from"); else log_error(comp->l, "No block labeled %s", comp->u.labeled.name); } /* Callers expect generate_component to increase stack depth by 1 */ if (discard_exit) adjust_depth(1, fn); break; } case c_continue: { bool discard_exit; /* Meaningless for continue blocks */ label exitlab = exit_block(comp->u.labeled.name, TRUE, &discard_exit, fn); if (exitlab) branch(OPmba3, exitlab, fn); else { if (comp->u.labeled.name[0] == '<') log_error(comp->l, "No loop to continue"); else log_error(comp->l, "No loop labeled %s", comp->u.labeled.name); } /* Callers expect generate_component to increase stack depth by 1 (*/ adjust_depth(1, fn); break; } case c_execute: { u16 count; generate_args(comp->u.execute->next, fn, &count); generate_execute(comp->u.execute->c, count, fn); break; } case c_builtin: args = comp->u.builtin.args; switch (comp->u.builtin.fn) { case b_if: generate_if(args->c, args->next->c, NULL, TRUE, fn); generate_component(component_undefined, NULL, FALSE, fn); break; case b_ifelse: generate_if(args->c, args->next->c, args->next->next->c, discard, fn); discard = FALSE; break; case b_sc_and: case b_sc_or: generate_if(comp, component_true, component_false, discard, fn); discard = FALSE; break; case b_while: enter_loop(fn); generate_while(args->c, args->next->c, mlabel, discard, fn); exit_loop(fn); discard = FALSE; break; case b_dowhile: enter_loop(fn); generate_dowhile(args->c, args->next->c, mlabel, discard, fn); exit_loop(fn); discard = FALSE; break; case b_for: enter_loop(fn); generate_for(args->c, args->next->c, args->next->next->c, args->next->next->next->c, mlabel, discard, fn); exit_loop(fn); discard = FALSE; break; default: { u16 count; assert(comp->u.builtin.fn < last_builtin); generate_args(args, fn, &count); ins0(builtin_ops[comp->u.builtin.fn], fn); break; } case b_cons: { u16 count; u16 goffset; mtype t; assert(comp->u.builtin.fn < last_builtin); generate_args(args, fn, &count); goffset = global_lookup(fnglobals(fn), builtin_functions[comp->u.builtin.fn], &t); mexecute(comp->l, goffset, NULL, count, fn); break; } } break; default: assert(0); } if (discard) ins0(OPmpop, fn); }
GridColouring(int _n, int _m, int _c) : n(_n), m(_m), c(_c) { // Create vars createVars(x, n, m, 1, c, true); // Constraints // For each rectangle, corners cannot all be the same colour for (int r1 = 0; r1 < n; r1++) { for (int r2 = r1+1; r2 < n; r2++) { for (int c1 = 0; c1 < m; c1++) { for (int c2 = c1+1; c2 < m; c2++) { for (int z = 1; z <= c; z++) { vec<BoolView> a; a.push(BoolView(x[r1][c1]->getLit(z,0))); a.push(BoolView(x[r2][c1]->getLit(z,0))); a.push(BoolView(x[r1][c2]->getLit(z,0))); a.push(BoolView(x[r2][c2]->getLit(z,0))); bool_clause(a); } } } } } // Balance constraints if (BALANCE) { IntVar *llimit = getConstant(m/c); IntVar *ulimit = getConstant(m/c+1); for (int i = 0; i < n; i++) { for (int z = 1; z <= c; z++) { vec<BoolView> a; for (int j = 0; j < m; j++) { a.push(BoolView(x[i][j]->getLit(z,1))); } bool_linear(a, IRT_LE, ulimit); bool_linear(a, IRT_GE, llimit); } } } // Mathamatical global constraint if (USE_GLOBAL) addGlobalProp(); // Test if (TEST) { assert(n == 16); assert(m == 16); assert(c == 4); for (int i = 0; i < 4; i++) { for (int j = 0; j < 16; j++) { x[i][j]->setVal((i+j/4)%4+1); } } } // Post some branchings vec<IntVar*> s; flatten(x, s); branch(s, VAR_INORDER, VAL_MIN); }
nsresult nsOperaProfileMigrator::CopyPreferences(PRBool aReplace) { nsresult rv; nsCOMPtr<nsIFile> operaPrefs; mOperaProfile->Clone(getter_AddRefs(operaPrefs)); operaPrefs->Append(OPERA_PREFERENCES_FILE_NAME); nsCOMPtr<nsILocalFile> lf(do_QueryInterface(operaPrefs)); NS_ENSURE_TRUE(lf, NS_ERROR_UNEXPECTED); nsINIParser parser; rv = parser.Init(lf); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIPrefBranch> branch(do_GetService(NS_PREFSERVICE_CONTRACTID)); // Traverse the standard transforms PrefTransform* transform; PrefTransform* end = gTransforms + sizeof(gTransforms)/sizeof(PrefTransform); const char* lastSectionName = nsnull; for (transform = gTransforms; transform < end; ++transform) { if (transform->sectionName) lastSectionName = transform->sectionName; if (transform->type == _OPM(COLOR)) { char* colorString = nsnull; nsresult rv = ParseColor(parser, lastSectionName, &colorString); if (NS_SUCCEEDED(rv)) { transform->stringValue = colorString; transform->prefHasValue = PR_TRUE; transform->prefSetterFunc(transform, branch); } if (colorString) free(colorString); } else { nsCAutoString val; rv = parser.GetString(lastSectionName, transform->keyName, val); if (NS_SUCCEEDED(rv)) { nsresult strerr; switch (transform->type) { case _OPM(STRING): transform->stringValue = ToNewCString(val); break; case _OPM(INT): { transform->intValue = val.ToInteger(&strerr); } break; case _OPM(BOOL): { transform->boolValue = val.ToInteger(&strerr) != 0; } break; default: break; } transform->prefHasValue = PR_TRUE; transform->prefSetterFunc(transform, branch); if (transform->type == _OPM(STRING) && transform->stringValue) { NS_Free(transform->stringValue); transform->stringValue = nsnull; } } } } // Copy Proxy Settings CopyProxySettings(parser, branch); // Copy User Content Sheet if (aReplace) CopyUserContentSheet(parser); return NS_OK; }
void Processor::z_make_menu() { // This opcode was only used for the Macintosh version of Journey. // It controls menus with numbers greater than 2 (menus 0, 1 and 2 // are system menus). branch(false); }
nsresult nsThunderbirdProfileMigrator::TransformPreferences( const char* aSourcePrefFileName, const char* aTargetPrefFileName) { PrefTransform* transform; PrefTransform* end = gTransforms + sizeof(gTransforms)/sizeof(PrefTransform); // Load the source pref file nsCOMPtr<nsIPrefService> psvc(do_GetService(NS_PREFSERVICE_CONTRACTID)); psvc->ResetPrefs(); nsCOMPtr<nsIFile> sourcePrefsFile; mSourceProfile->Clone(getter_AddRefs(sourcePrefsFile)); sourcePrefsFile->AppendNative(nsDependentCString(aSourcePrefFileName)); psvc->ReadUserPrefs(sourcePrefsFile); nsCOMPtr<nsIPrefBranch> branch(do_QueryInterface(psvc)); for (transform = gTransforms; transform < end; ++transform) transform->prefGetterFunc(transform, branch); // read in the various pref branch trees for accounts, identities, servers, // etc. static const char* branchNames[] = { // Keep the three below first, or change the indexes below "mail.identity.", "mail.server.", "ldap_2.", "accessibility.", "applications.", "bidi.", "dom.", "editor.", "font.", "helpers.", "mail.account.", "mail.addr_book.", "mail.imap.", "mail.mdn.", "mail.smtpserver.", "mail.spam.", "mail.toolbars.", "mailnews.labels.", "mailnews.reply_", "mailnews.tags.", "middlemouse.", "mousewheel.", "network.http.", "print.", "privacy.", "security.OSCP.", "security.crl.", "ui.key.", "wallet." }; PBStructArray branches[NS_ARRAY_LENGTH(branchNames)]; uint32_t i; for (i = 0; i < NS_ARRAY_LENGTH(branchNames); ++i) ReadBranch(branchNames[i], psvc, branches[i]); // the signature file prefs may be paths to files in the thunderbird profile // path so we need to copy them over and fix these paths up before we write // them out to the new prefs.js CopySignatureFiles(branches[0], psvc); // certain mail prefs may actually be absolute paths instead of profile // relative paths we need to fix these paths up before we write them out to // the new prefs.js CopyMailFolderPrefs(branches[1], psvc); CopyAddressBookDirectories(branches[2], psvc); // Now that we have all the pref data in memory, load the target pref file, // and write it back out psvc->ResetPrefs(); nsCOMPtr<nsIFile> targetPrefsFile; mTargetProfile->Clone(getter_AddRefs(targetPrefsFile)); targetPrefsFile->AppendNative(nsDependentCString(aTargetPrefFileName)); // Don't use nullptr here as we're too early in the cycle for the prefs // service to get its default file (because the NS_GetDirectoryService items // aren't fully set up yet). psvc->ReadUserPrefs(targetPrefsFile); for (transform = gTransforms; transform < end; ++transform) transform->prefSetterFunc(transform, branch); for (i = 0; i < NS_ARRAY_LENGTH(branchNames); ++i) WriteBranch(branchNames[i], psvc, branches[i]); psvc->SavePrefFile(targetPrefsFile); return NS_OK; }
void trans_layer::send_200_ack(sip_msg* reply, sip_trans* t) { // Set request URI // TODO: use correct R-URI instead of just 'Contact' if(!get_contact(reply)) { DBG("Sorry, reply has no Contact header: could not send ACK\n"); return; } sip_nameaddr na; const char* c = get_contact(reply)->value.s; if(parse_nameaddr(&na,&c,get_contact(reply)->value.len) < 0){ DBG("Sorry, reply's Contact parsing failed: could not send ACK\n"); return; } cstring r_uri = na.addr; list<sip_header*> route_hdrs; if(t && !t->msg->route.empty()){ for(list<sip_header*>::iterator it = t->msg->route.begin(); it != t->msg->route.end(); ++it) { route_hdrs.push_back(new sip_header(0,"Route",(*it)->value)); } } else { for(list<sip_header*>::reverse_iterator it = reply->record_route.rbegin(); it != reply->record_route.rend(); ++it) { route_hdrs.push_back(new sip_header(0,"Route",(*it)->value)); } } sockaddr_storage remote_ip; set_next_hop(route_hdrs,r_uri,&remote_ip); int request_len = request_line_len(cstring("ACK",3),r_uri); char branch_buf[BRANCH_BUF_LEN]; compute_branch(branch_buf,reply->callid->value,reply->cseq->value); cstring branch(branch_buf,BRANCH_BUF_LEN); sip_header* max_forward = new sip_header(0,cstring("Max-Forwards"),cstring("10")); cstring via((char*)transport->get_local_ip()); request_len += via_len(via,branch); request_len += copy_hdrs_len(route_hdrs); request_len += copy_hdr_len(reply->to); request_len += copy_hdr_len(reply->from); request_len += copy_hdr_len(reply->callid); request_len += copy_hdr_len(max_forward); request_len += cseq_len(get_cseq(reply)->num_str,cstring("ACK",3)); request_len += 2/* CRLF end-of-headers*/; // Allocate new message char* ack_buf = new char[request_len]; // generate it char* msg = ack_buf; request_line_wr(&msg,cstring("ACK",3),r_uri); via_wr(&msg,via,branch); copy_hdrs_wr(&msg,route_hdrs); // clear route headers list for (list<sip_header*>::iterator it=route_hdrs.begin(); it!= route_hdrs.end(); it++) delete *it; copy_hdr_wr(&msg,reply->from); copy_hdr_wr(&msg,reply->to); copy_hdr_wr(&msg,reply->callid); copy_hdr_wr(&msg,max_forward); delete max_forward; cseq_wr(&msg,get_cseq(reply)->num_str,cstring("ACK",3)); *msg++ = CR; *msg++ = LF; DBG("About to send 200 ACK\n"); // DBG("About to send 200 ACK: \n<%.*s>\n",request_len,ack_buf); assert(transport); int send_err = transport->send(&remote_ip,ack_buf,request_len); if(send_err < 0){ ERROR("Error from transport layer\n"); delete [] ack_buf; } else if(t){ delete [] t->retr_buf; t->retr_buf = ack_buf; t->retr_len = request_len; memcpy(&t->retr_addr,&remote_ip,sizeof(sockaddr_storage)); } }
int trans_layer::send_request(sip_msg* msg, char* tid, unsigned int& tid_len) { // Request-URI // To // From // Call-ID // CSeq // Max-Forwards // Via // Contact // Supported / Require // Content-Length / Content-Type assert(transport); tid_len = 0; if(set_next_hop(msg->route,msg->u.request->ruri_str, &msg->remote_ip) < 0){ // TODO: error handling DBG("set_next_hop failed\n"); //delete msg; return -1; } // assume that msg->route headers are not in msg->hdrs msg->hdrs.insert(msg->hdrs.begin(),msg->route.begin(),msg->route.end()); int request_len = request_line_len(msg->u.request->method_str, msg->u.request->ruri_str); char branch_buf[BRANCH_BUF_LEN]; compute_branch(branch_buf,msg->callid->value,msg->cseq->value); cstring branch(branch_buf,BRANCH_BUF_LEN); string via(transport->get_local_ip()); if(transport->get_local_port() != 5060) via += ":" + int2str(transport->get_local_port()); request_len += via_len(stl2cstr(via),branch); request_len += copy_hdrs_len(msg->hdrs); string content_len = int2str(msg->body.len); request_len += content_length_len(stl2cstr(content_len)); request_len += 2/* CRLF end-of-headers*/; if(msg->body.len){ request_len += msg->body.len; } // Allocate new message sip_msg* p_msg = new sip_msg(); p_msg->buf = new char[request_len]; p_msg->len = request_len; // generate it char* c = p_msg->buf; request_line_wr(&c,msg->u.request->method_str, msg->u.request->ruri_str); via_wr(&c,stl2cstr(via),branch); copy_hdrs_wr(&c,msg->hdrs); content_length_wr(&c,stl2cstr(content_len)); *c++ = CR; *c++ = LF; if(msg->body.len){ memcpy(c,msg->body.s,msg->body.len); // Not needed by now as the message is finished //c += body.len; } // and parse it if(parse_sip_msg(p_msg)){ ERROR("Parser failed on generated request\n"); ERROR("Message was: <%.*s>\n",p_msg->len,p_msg->buf); delete p_msg; return MALFORMED_SIP_MSG; } memcpy(&p_msg->remote_ip,&msg->remote_ip,sizeof(sockaddr_storage)); DBG("Sending to %s:%i <%.*s>\n", get_addr_str(((sockaddr_in*)&p_msg->remote_ip)->sin_addr).c_str(), ntohs(((sockaddr_in*)&p_msg->remote_ip)->sin_port), p_msg->len,p_msg->buf); trans_bucket* bucket = get_trans_bucket(p_msg->callid->value, get_cseq(p_msg)->num_str); bucket->lock(); int send_err = transport->send(&p_msg->remote_ip,p_msg->buf,p_msg->len); if(send_err < 0){ ERROR("Error from transport layer\n"); delete p_msg; } else { sip_trans* t = bucket->add_trans(p_msg,TT_UAC); if(p_msg->u.request->method == sip_request::INVITE){ // if transport == UDP t->reset_timer(STIMER_A,A_TIMER,bucket->get_id()); // for any transport type t->reset_timer(STIMER_B,B_TIMER,bucket->get_id()); } else { // if transport == UDP t->reset_timer(STIMER_E,E_TIMER,bucket->get_id()); // for any transport type t->reset_timer(STIMER_F,F_TIMER,bucket->get_id()); } string t_id = int2hex(bucket->get_id()).substr(5,string::npos) + ":" + long2hex((unsigned long)t); memcpy(tid,t_id.c_str(),t_id.length()); tid_len = t_id.length(); } bucket->unlock(); return send_err; }
void ARMCore::thumbBranch(int11 offset) { branch(1, r[15] + 2*offset); }
void ARMCore::thumbBlx(uint1 tf, uint11 offset) { uint32 base = r[14]; r[14] = r[15]-2 + 1; branch(tf, base + 2*offset); }
void ARMCore::thumbCond(uint4 opcode, int8 offset) { if(opcode == 14) { return undefined(); } if(opcode == 15) { return swi(); } if(evalCond(opcode)) return branch(1, r[15] + 2*offset); r[15] += 2; }
int main(int argc, char *argv[]) { //Check for binary file argument if(argc != 2) { printf("No binary file provided!\n"); printf("Usage: emulate [binary_file]\n\n"); exit(EXIT_FAILURE); } //----------INITIALIZE------------- //Initialize arm struct ARM arm; //memset(arm.memory, 0, MAX_MEMORY_SIZE); //zero array for(int i = 0; i < MAX_MEMORY_SIZE; ++i) { arm.memory[i] = 0; } //GPIO setGpioAddress(&arm); //setup GPIO address arm.pc = 0; //Execute from the beginning //memset(arm.registers, 0, NUMBER_OF_REGISTERS); for(int i = 0; i < NUMBER_OF_REGISTERS; ++i) { arm.registers[i] = 0; } arm.cpsr = 0; //Read the binary file (program) to the memory, starting from pos0 binRead(arm.memory, argv[1]); int ir = 0; //INSTRUCTION REGISTER //-------FETCH-EXECUTE CYCLE------- do { //FETCH ir = arm.memory[arm.pc]; //Fetch the current instruction ++arm.pc; //Increment pc counter //DECODE int cond = checkCond(&ir, &arm); if(cond) { //Determine type switch(getType(&ir)) { case DATA_PROCESSING: dataprocessing(&ir, &arm); break; case BRANCH: branch(&ir, &arm); break; case MULTIPLY: multiply(&ir, &arm); break; case SINGLE_DATA_TRANSFER: single_data_transfer(&ir, &arm); break; } } } while (ir != 0); //---------CLEAR GPIO VIRTUAL MEMORY------- clearGpioAddress(&arm); //---------PRINT ARM STATUS------- printARM(&arm); return EXIT_SUCCESS; }
/** finds maximum weight clique */ void tcliqueMaxClique( TCLIQUE_GETNNODES((*getnnodes)), /**< user function to get the number of nodes */ TCLIQUE_GETWEIGHTS((*getweights)), /**< user function to get the node weights */ TCLIQUE_ISEDGE((*isedge)), /**< user function to check for existence of an edge */ TCLIQUE_SELECTADJNODES((*selectadjnodes)),/**< user function to select adjacent edges */ TCLIQUE_GRAPH* tcliquegraph, /**< pointer to graph data structure that is passed to graph callbacks */ TCLIQUE_NEWSOL((*newsol)), /**< user function to call on every new solution */ TCLIQUE_DATA* tcliquedata, /**< user data to pass to new solution callback function */ int* maxcliquenodes, /**< pointer to store nodes of the maximum weight clique */ int* nmaxcliquenodes, /**< pointer to store number of nodes in the maximum weight clique */ TCLIQUE_WEIGHT* maxcliqueweight, /**< pointer to store weight of the maximum weight clique */ TCLIQUE_WEIGHT maxfirstnodeweight, /**< maximum weight of branching nodes in level 0; 0 if not used * for cliques with at least one fractional node) */ TCLIQUE_WEIGHT minweight, /**< lower bound for weight of generated cliques */ int maxntreenodes, /**< maximal number of nodes of b&b tree */ int backtrackfreq, /**< frequency to backtrack to first level of tree (0: no premature backtracking) */ int maxnzeroextensions, /**< maximal number of zero-valued variables extending the clique */ int fixednode, /**< node that is forced to be in the clique, or -1; must have positive weight */ int* ntreenodes, /**< pointer to store the number of used tree nodes (or NULL) */ TCLIQUE_STATUS* status /**< pointer to store the status of the solving call */ ) { CLIQUEHASH* cliquehash; const TCLIQUE_WEIGHT* weights; int* buffer; int* K; int* V; int* Vzero; int nnodes; int nV; int nVzero; int i; BMS_CHKMEM* mem; NBC* gsd; TCLIQUE_Bool* iscolored; int* curcliquenodes; int ncurcliquenodes; TCLIQUE_WEIGHT curcliqueweight; int* tmpcliquenodes; int nbbtreenodes; int backtracklevel; assert(maxcliquenodes != NULL); assert(nmaxcliquenodes != NULL); assert(maxcliqueweight != NULL); assert(maxntreenodes >= 0); assert(backtrackfreq >= 0); assert(maxnzeroextensions >= 0); assert(status != NULL); *status = TCLIQUE_OPTIMAL; /* use default graph callbacks, if NULL pointers are given */ if( getnnodes == NULL ) getnnodes = tcliqueGetNNodes; if( getweights == NULL ) getweights = tcliqueGetWeights; if( isedge == NULL ) isedge = tcliqueIsEdge; if( selectadjnodes == NULL ) selectadjnodes = tcliqueSelectAdjnodes; /* get number of nodes */ nnodes = getnnodes(tcliquegraph); debugMessage("calculating maximal weighted clique in graph (%d nodes)\n", nnodes); /* set up data structures */ if( newsol != NULL ) createCliquehash(&cliquehash, CLIQUEHASH_INITSIZE); else cliquehash = NULL; ALLOC_ABORT( BMSallocMemoryArray(&buffer, nnodes) ); ALLOC_ABORT( BMSallocMemoryArray(&K, nnodes) ); ALLOC_ABORT( BMSallocMemoryArray(&V, nnodes) ); ALLOC_ABORT( BMSallocMemoryArray(&Vzero, nnodes) ); ALLOC_ABORT( BMSallocMemoryArray(&gsd, nnodes) ); ALLOC_ABORT( BMSallocMemoryArray(&iscolored, nnodes) ); ALLOC_ABORT( BMSallocMemoryArray(&curcliquenodes, nnodes) ); ALLOC_ABORT( BMSallocMemoryArray(&tmpcliquenodes, nnodes) ); /* set weight and number of nodes of maximum weighted clique */ *nmaxcliquenodes = 0; *maxcliqueweight = minweight-1; ncurcliquenodes = 0; curcliqueweight = 0; nbbtreenodes = 0; /* set up V and Vzero */ weights = getweights(tcliquegraph); assert(weights != NULL); nV = 0; nVzero = 0; for( i = 0 ; i < nnodes; i++ ) { if( weights[i] == 0 ) { Vzero[nVzero] = i; nVzero++; } else { V[nV] = i; nV++; } } /* initialize own memory allocator for coloring */ mem = BMScreateChunkMemory(sizeof(LIST_ITV), CHUNK_SIZE, -1); /* branch to find maximum weight clique */ backtracklevel = branch(getnnodes, getweights, isedge, selectadjnodes, tcliquegraph, newsol, tcliquedata, mem, cliquehash, buffer, 0, V, nV, Vzero, nVzero, gsd, iscolored, K, 0, maxcliquenodes, nmaxcliquenodes, maxcliqueweight, curcliquenodes, &ncurcliquenodes, &curcliqueweight, tmpcliquenodes, maxfirstnodeweight, &nbbtreenodes, maxntreenodes, backtrackfreq, maxnzeroextensions, fixednode, status); if ( ntreenodes != NULL ) *ntreenodes = nbbtreenodes; if( backtracklevel != INT_MAX && *status == TCLIQUE_OPTIMAL ) *status = TCLIQUE_USERABORT; /* delete own memory allocator for coloring */ BMSdestroyChunkMemory(&mem); /* free data structures */ BMSfreeMemoryArray(&tmpcliquenodes); BMSfreeMemoryArray(&curcliquenodes); BMSfreeMemoryArray(&iscolored); BMSfreeMemoryArray(&gsd); BMSfreeMemoryArray(&Vzero); BMSfreeMemoryArray(&V); BMSfreeMemoryArray(&K); BMSfreeMemoryArray(&buffer); if( newsol != NULL ) freeCliquehash(&cliquehash); }
void CPU::exec16(const Instruction16 &insn) { switch(insn.OP) { case 0x00: switch(insn.rform.func4) { // nop! case 0x00: /* noting */ break; // mlfh! rDg0, rAg1 case 0x01: g0[insn.rform.rD] = g1[insn.rform.rA]; break; // mhfl! rDg1, rAg0 case 0x02: g1[insn.rform.rD] = g0[insn.rform.rA]; break; // mv! rDg0, rAg0 case 0x03: g0[insn.rform.rD] = g0[insn.rform.rA]; break; // br{cond}! rAg0 case 0x04: if(conditional(insn.rform.rD)) branch(g0[insn.rform.rA] - 2, false); break; // t{cond}! case 0x05: T = conditional(insn.rform.rD); break; default: debugDump(); } break; case 0x01: { uint32_t &rA = g0[insn.rform.rA]; // uint32_t &rD = g0[insn.rform.rD]; switch(insn.rform.func4) { // mtce{lh}! rA case 0x00: switch(insn.rform.rD) { case 0x00: CEL = rA; break; case 0x01: CEH = rA; break; } break; // mfce{lh}! rA case 0x01: switch(insn.rform.rD) { case 0x00: rA = CEL; break; case 0x01: rA = CEH; break; } break; default: debugDump(); } } break; case 0x02: { uint32_t &rA = g0[insn.rform.rA]; uint32_t &rD = g0[insn.rform.rD]; uint32_t &rAh = g0[insn.rhform.rA]; uint32_t &rDh = g[insn.rhform.H][insn.rhform.rD]; switch(insn.rform.func4) { // add! rDg0, rAg0 case 0x00: rD = add(rD, rA, true); break; // sub! rDg0, rAg0 case 0x01: rD = sub(rD, rA, true); break; // neg! rDg0, rAg0 case 0x02: rD = sub(0, rA, true); break; // cmp! rDg0, rAg0 case 0x03: sub(rD, rA, true); break; // and! rDg0, rAg0 case 0x04: rD = bit_and(rD, rA, true); break; // or! rDg0, rAg0 case 0x05: rD = bit_or(rD, rA, true); break; // not! rDg0, rAg0 case 0x06: rD = bit_xor(rA, ~0, true); break; // xor! rDg0, rAg0 case 0x07: rD = bit_xor(rD, rA, true); break; // lw! rDg0, [rAg0] case 0x08: rD = miu.readU32(rA); break; // lh! rDg0, [rAg0] case 0x09: rD = sign_extend(miu.readU16(rA), 16); break; // pop! rDgh, [rAg0] case 0x0A: rDh = miu.readU32(rAh); rAh += 4; break; // lbu! rDg0, [rAg0] case 0x0B: rD = miu.readU8(rA); break; // sw! rDg0, [rAg0] case 0x0C: miu.writeU32(rA, rD); break; // sh! rDg0, [rAg0] case 0x0D: miu.writeU16(rA, rD); break; // push! rDgh, [rAg0] case 0x0E: miu.writeU32(rAh -= 4, rDh); break; // sb! rDg0, [rAg0] case 0x0F: miu.writeU8(rA, rD); break; } } break; case 0x03: { // j[l]! imm11 if(insn.jform.LK) link(); pc &= 0xFFFFF000; pc |= (insn.jform.Disp11 << 1) - 2; } break; case 0x04: { // b{cond}! imm8 if(conditional(insn.bxform.EC)) pc += (sign_extend(insn.bxform.Imm8, 8) << 1) - 2; } break; case 0x05: // ldiu! imm8 g0[insn.iform2.rD] = insn.iform2.Imm8; break; case 0x06: { uint32_t &rD = g0[insn.iform1.rD]; uint32_t imm = 1 << insn.iform1.Imm5; switch(insn.iform1.func3) { // srli! rD, imm5 case 0x03: rD = srl(rD, insn.iform1.Imm5, true); break; // bitclr! rD, imm5 case 0x04: rD = bit_and(rD, ~imm, true); break; // bitset! rD, imm5 case 0x05: rD = bit_or(rD, imm, true); break; // bittst! rD, imm5 case 0x06: bit_and(rD, imm, true); break; default: debugDump(); } } break; case 0x07: { uint32_t &rD = g0[insn.iform1.rD]; uint32_t imm = insn.iform1.Imm5 << 2; switch(insn.iform1.func3) { // lwp! rDg0, imm case 0x00: rD = miu.readU32(r2 + imm); break; // lbup! rDg0, imm case 0x01: rD = miu.readU8(r2 + imm); break; // lhp! rDg0, imm case 0x03: rD = sign_extend(miu.readU8(r2 + imm), 16); break; // swp! rDg0, imm case 0x04: miu.writeU32(r2 + imm, rD); break; // shp! rDg0, imm case 0x05: miu.writeU16(r2 + imm, rD); break; // sbp! rDg0, imm case 0x07: miu.writeU32(r2 + imm, rD); break; default: debugDump(); } } break; default: debugDump(); } }
int trans_layer::cancel(trans_bucket* bucket, sip_trans* t) { bucket->lock(); if(!bucket->exist(t)){ DBG("No transaction to cancel: wrong key or finally replied\n"); bucket->unlock(); return 0; } sip_msg* req = t->msg; // RFC 3261 says: SHOULD NOT be sent for other request // than INVITE. if(req->u.request->method != sip_request::INVITE){ bucket->unlock(); ERROR("Trying to cancel a non-INVITE request (we SHOULD NOT do that)\n"); return -1; } switch(t->state){ case TS_CALLING: // do not send a request: // just remove the transaction bucket->remove_trans(t); bucket->unlock(); return 0; case TS_COMPLETED: // final reply has been sent: // do nothing!!! bucket->unlock(); return 0; case TS_PROCEEDING: // continue with CANCEL request break; } cstring cancel_str("CANCEL"); int request_len = request_line_len(cancel_str, req->u.request->ruri_str); char branch_buf[BRANCH_BUF_LEN]; compute_branch(branch_buf,req->callid->value,get_cseq(req)->num_str); cstring branch(branch_buf,BRANCH_BUF_LEN); string via(transport->get_local_ip()); if(transport->get_local_port() != 5060) via += ":" + int2str(transport->get_local_port()); request_len += copy_hdr_len(req->via1); request_len += copy_hdr_len(req->to) + copy_hdr_len(req->from) + copy_hdr_len(req->callid) + cseq_len(get_cseq(req)->num_str,cancel_str) + copy_hdrs_len(req->route) + copy_hdrs_len(req->contacts); request_len += 2/* CRLF end-of-headers*/; // Allocate new message sip_msg* p_msg = new sip_msg(); p_msg->buf = new char[request_len]; p_msg->len = request_len; // generate it char* c = p_msg->buf; request_line_wr(&c,cancel_str, req->u.request->ruri_str); copy_hdr_wr(&c,req->via1); copy_hdr_wr(&c,req->to); copy_hdr_wr(&c,req->from); copy_hdr_wr(&c,req->callid); cseq_wr(&c,get_cseq(req)->num_str,cancel_str); copy_hdrs_wr(&c,req->route); copy_hdrs_wr(&c,req->contacts); *c++ = CR; *c++ = LF; // and parse it if(parse_sip_msg(p_msg)){ ERROR("Parser failed on generated request\n"); ERROR("Message was: <%.*s>\n",p_msg->len,p_msg->buf); delete p_msg; return MALFORMED_SIP_MSG; } memcpy(&p_msg->remote_ip,&req->remote_ip,sizeof(sockaddr_storage)); DBG("Sending to %s:%i <%.*s>\n", get_addr_str(((sockaddr_in*)&p_msg->remote_ip)->sin_addr).c_str(), ntohs(((sockaddr_in*)&p_msg->remote_ip)->sin_port), p_msg->len,p_msg->buf); int send_err = transport->send(&p_msg->remote_ip,p_msg->buf,p_msg->len); if(send_err < 0){ ERROR("Error from transport layer\n"); delete p_msg; } else { trans_bucket* n_bucket = get_trans_bucket(p_msg->callid->value, get_cseq(p_msg)->num_str); if(bucket != n_bucket) n_bucket->lock(); sip_trans* t = n_bucket->add_trans(p_msg,TT_UAC); // if transport == UDP t->reset_timer(STIMER_E,E_TIMER,bucket->get_id()); // for any transport type t->reset_timer(STIMER_F,F_TIMER,bucket->get_id()); if(bucket != n_bucket) n_bucket->unlock(); } bucket->unlock(); return send_err; }
void CPU::exec32(const Instruction32 &insn) { switch(insn.OP) { case 0x00: { uint32_t &rD = r[insn.spform.rD]; uint32_t &rA = r[insn.spform.rA]; uint32_t &rB = r[insn.spform.rB]; switch(insn.spform.func6) { // nop case 0x00: /* nothing */ break; // br{cond}[l] rA case 0x04: if(conditional(insn.spform.rB)) branch(rA - 4, insn.spform.CU); break; // add[.c] rD, rA, rB case 0x08: rD = add(rA, rB, insn.spform.CU); break; // addc[.c] rD, rA, rB case 0x09: rD = addc(rA, rB, insn.spform.CU); break; // sub[.c] rD, rA, rB case 0x0A: rD = sub(rA, rB, insn.spform.CU); break; // subc[.c] rD, rA, rB case 0x0B: rD = subc(rA, rB, insn.spform.CU); break; // cmp{tcs}.c rA, rB case 0x0C: cmp(rA, rB, insn.spform.rD & 0x03, insn.spform.CU); break; // cmpz{tcs}.c rA, rB case 0x0D: cmp(rA, 0, insn.spform.rD & 0x03, insn.spform.CU); break; // neg[.c] rD, rA case 0x0F: rD = sub(0, rA, insn.spform.CU); break; // and[.c] rD, rA, rB case 0x10: rD = bit_and(rA, rB, insn.spform.CU); break; // or[.c] rD, rA, rB case 0x11: rD = bit_or(rA, rB, insn.spform.CU); break; // not[.c] rD, rA, rB case 0x12: rD = bit_xor(rA, ~0, insn.spform.CU); break; // xor[.c] rD, rA, rB case 0x13: rD = bit_or(rA, rB, insn.spform.CU); break; // bitclr[.c] rD, rA, imm5 case 0x14: rD = bit_and(rA, ~(1 << insn.spform.rB), insn.spform.CU); break; // bitset[.c] rD, rA, imm5 case 0x15: rD = bit_or(rA, 1 << insn.spform.rB, insn.spform.CU); break; // bittst.c rA, imm5 case 0x16: bit_and(rA, 1 << insn.spform.rB, insn.spform.CU); break; // bittgl[.c] rA, imm5 case 0x17: rD = bit_xor(rA, 1 << insn.spform.rB, insn.spform.CU); break; // sll[.c] rA, imm5 case 0x18: rD = sll(rA, insn.spform.rB, insn.spform.CU); break; // srl[.c] rA, imm5 case 0x1A: rD = srl(rA, insn.spform.rB, insn.spform.CU); break; // sra[.c] rA, imm5 case 0x1B: rD = sra(rA, insn.spform.rB, insn.spform.CU); break; // mul rA, rD case 0x20: ce_op(rA, rD, std::multiplies<int64_t>()); break; // mulu rA, rD case 0x21: ce_op(rA, rD, std::multiplies<uint64_t>()); break; // div rA, rD case 0x22: ce_op(rA, rD, std::divides<int64_t>()); break; // divu rA, rD case 0x23: ce_op(rA, rD, std::divides<uint64_t>()); break; // mfce{hl} rD[, rA] case 0x24: switch(insn.spform.rB) { case 0x01: rD = CEL; break; case 0x02: rD = CEH; break; case 0x03: rD = CEH; rA = CEL; break; } break; // mtce{hl} rD[, rA] case 0x25: switch(insn.spform.rB) { case 0x01: CEL = rD; break; case 0x02: CEH = rD; break; case 0x03: CEH = rD; CEL = rA; break; } break; // mfsr rA, Srn case 0x28: rA = sr[insn.spform.rB]; // mtsr rA, Srn case 0x29: sr[insn.spform.rB] = rA; // t{cond} case 0x2A: T = conditional(insn.spform.rB); break; // mv{cond} rD, rA case 0x2B: if(conditional(insn.spform.rB)) rD = rA; break; // extsb[.c] rD, rA case 0x2C: rD = sign_extend(rA, 8); if(insn.spform.CU) basic_flags(rD); break; // extsh[.c] rD, rA case 0x2D: rD = sign_extend(rA, 16); if(insn.spform.CU) basic_flags(rD); break; // extzb[.c] rD, rA case 0x2E: rD = bit_and(rA, 0x000000FF, insn.spform.CU); break; // extzh[.c] rD, rA case 0x2F: rD = bit_and(rA, 0x0000FFFF, insn.spform.CU); break; // slli[.c] rD, rA, imm5 case 0x38: rD = sll(rA, insn.spform.rB, insn.spform.CU); break; // srli[.c] rD, rA, imm5 case 0x3A: rD = srl(rA, insn.spform.rB, insn.spform.CU); break; // srai[.c] rD, rA, imm5 case 0x3B: rD = sra(rA, insn.spform.rB, insn.spform.CU); break; default: debugDump(); } } break; case 0x01: { uint32_t &rD = r[insn.iform.rD]; switch(insn.iform.func3) { // addi[.c] rD, imm16 case 0x00: rD = add(rD, sign_extend(insn.iform.Imm16, 16), insn.iform.CU); break; // cmpi.c rD, imm16 case 0x02: cmp(rD, sign_extend(insn.iform.Imm16, 16), 3, insn.iform.CU); break; // andi.c rD, imm16 case 0x04: rD = bit_and(rD, insn.iform.Imm16, insn.iform.CU); break; // ori.c rD, imm16 case 0x05: rD = bit_or(rD, insn.iform.Imm16, insn.iform.CU); break; // ldi rD, imm16 case 0x06: rD = sign_extend(insn.iform.Imm16, 16); break; default: debugDump(); } } break; case 0x02: { // j[l] imm24 if(insn.jform.LK) link(); // Update PC pc &= 0xFC000000; pc |= (insn.jform.Disp24 << 1) - 4; } break; case 0x03: { uint32_t &rD = r[insn.rixform.rD]; uint32_t &rA = r[insn.rixform.rA]; // Pre-increment rA += sign_extend(insn.rixform.Imm12, 12); switch(insn.rixform.func3) { // lw rD, [rA, imm12]+ case 0x00: rD = miu.readU32(rA); break; // lh rD, [rA, imm12]+ case 0x01: rD = sign_extend(miu.readU16(rA), 16); break; // lhu rD, [rA, imm12]+ case 0x02: rD = miu.readU16(rA); break; // lb rD, [rA, imm12]+ case 0x03: rD = sign_extend(miu.readU8(rA), 8); break; // sw rD, [rA, imm12]+ case 0x04: miu.writeU32(rA, rD); break; // sh rD, [rA, imm12]+ case 0x05: miu.writeU16(rA, rD); break; // lbu rD, [rA, imm12]+ case 0x06: rD = miu.readU8(rA); break; // sb rD, [rA, imm12]+ case 0x07: miu.writeU8(rA, rD); break; default: debugDump(); } } break; case 0x04: { // b{cond}[l] if(conditional(insn.bcform.BC)) { if(insn.bcform.LK) link(); pc += sign_extend(((insn.bcform.Disp18_9 << 9) | insn.bcform.Disp8_0) << 1, 20) - 4; } } break; case 0x05: { uint32_t &rD = r[insn.iform.rD]; uint32_t imm16 = insn.iform.Imm16 << 16; switch(insn.iform.func3) { // addis[.c] rD, imm16 case 0x00: rD = add(rD, imm16, insn.iform.CU); break; // cmpis.c rD, imm16 case 0x02: cmp(rD, imm16, 3, insn.iform.CU); break; // andis.c rD, imm16 case 0x04: rD = bit_and(rD, imm16, insn.iform.CU); break; // oris.c rD, imm16 case 0x05: rD = bit_or(rD, imm16, insn.iform.CU); break; // ldis rD, imm16 case 0x06: rD = imm16; break; default: debugDump(); } } break; case 0x06: { uint32_t &rD = r[insn.crform.rD]; uint32_t &crA = cr[insn.crform.crA]; switch(insn.crform.CR_OP) { // mtcr rD, crA case 0x00: crA = rD; break; // mfcr rD, crA case 0x01: rD = crA; break; // rte case 0x84: branch(cr5 - 4, false); /* TODO: missing PSR */ break; default: debugDump(); } } break; case 0x07: { uint32_t &rD = r[insn.rixform.rD]; uint32_t &rA = r[insn.rixform.rA]; switch(insn.rixform.func3) { // lw rD, [rA]+, imm12 case 0x00: rD = miu.readU32(rA); break; // lh rD, [rA]+, imm12 case 0x01: rD = sign_extend(miu.readU16(rA), 16); break; // lhu rD, [rA]+, imm12 case 0x02: rD = miu.readU16(rA); break; // lb rD, [rA]+, imm12 case 0x03: rD = sign_extend(miu.readU8(rA), 8); break; // sw rD, [rA]+, imm12 case 0x04: miu.writeU32(rA, rD); break; // sh rD, [rA]+, imm12 case 0x05: miu.writeU16(rA, rD); break; // lbu rD, [rA]+, imm12 case 0x06: rD = miu.readU8(rA); break; // sb rD, [rA]+, imm12 case 0x07: miu.writeU8(rA, rD); break; default: debugDump(); } // Post-increment rA += sign_extend(insn.rixform.Imm12, 12); } break; case 0x08: { // addri[.c] rD, rA, imm14 uint32_t &rD = r[insn.riform.rD]; uint32_t &rA = r[insn.riform.rA]; uint32_t imm14 = sign_extend(insn.riform.Imm14, 14); rD = add(rA, imm14, insn.riform.CU); } break; case 0x0C: { // andri[.c] rD, rA, imm14 uint32_t &rD = r[insn.riform.rD]; uint32_t &rA = r[insn.riform.rA]; uint32_t imm14 = insn.riform.Imm14; rD = bit_and(rA, imm14, insn.riform.CU); } break; case 0x0D: { // orri[.c] rD, rA, imm14 uint32_t &rD = r[insn.riform.rD]; uint32_t &rA = r[insn.riform.rA]; uint32_t imm14 = insn.riform.Imm14; rD = bit_or(rA, imm14, insn.riform.CU); } break; case 0x10: { // lw rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); rD = miu.readU32(rA + imm15); } break; case 0x11: { // lh rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); rD = sign_extend(miu.readU16(rA + imm15), 16); } break; case 0x12: { // lhu rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); rD = miu.readU16(rA + imm15); } break; case 0x13: { // lb rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); rD = sign_extend(miu.readU8(rA + imm15), 8); } break; case 0x14: { // sw rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); miu.writeU32(rA + imm15, rD); } break; case 0x15: { // sh rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); miu.writeU16(rA + imm15, rD); } break; case 0x16: { // lbu rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); rD = miu.readU8(rA + imm15); } break; case 0x17: { // sb rD, [rA, imm15] uint32_t &rD = r[insn.mform.rD]; uint32_t &rA = r[insn.mform.rA]; uint32_t imm15 = sign_extend(insn.mform.Imm15, 15); miu.writeU8(rA + imm15, rD); } break; case 0x18: // cache op, [rA, imm15] break; default: debugDump(); } }
static return_stmt(stream, node, ret) { if ( node[3] ) expr_code( stream, node[3], 0 ); branch( stream, ret ); }
static int do_server(BINKD_CONFIG *config) { struct addrinfo *ai, *aiHead, hints; int aiErr; SOCKET new_sockfd; int pid; socklen_t client_addr_len; struct sockaddr_storage client_addr; int opt = 1; int save_errno; struct listenchain *listen_list; /* setup hints for getaddrinfo */ memset((void *)&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; for (listen_list = config->listen.first; listen_list; listen_list = listen_list->next) { if ((aiErr = getaddrinfo(listen_list->addr[0] ? listen_list->addr : NULL, listen_list->port, &hints, &aiHead)) != 0) { Log(0, "servmgr getaddrinfo: %s (%d)", gai_strerror(aiErr), aiErr); return -1; } for (ai = aiHead; ai != NULL && sockfd_used < MAX_LISTENSOCK; ai = ai->ai_next) { sockfd[sockfd_used] = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sockfd[sockfd_used] < 0) { Log (0, "servmgr socket(): %s", TCPERR ()); continue; } #ifdef UNIX /* Not sure how to set NOINHERIT flag for socket on Windows and OS/2 */ if (fcntl(sockfd[sockfd_used], F_SETFD, FD_CLOEXEC) != 0) Log(1, "servmgr fcntl set FD_CLOEXEC error: %s", strerror(errno)); #endif #ifdef IPV6_V6ONLY if (ai->ai_family == PF_INET6) { int v6only = 1; if (setsockopt(sockfd[sockfd_used], IPPROTO_IPV6, IPV6_V6ONLY, (char *) &v6only, sizeof(v6only)) == SOCKET_ERROR) Log(1, "servmgr setsockopt (IPV6_V6ONLY): %s", TCPERR()); } #endif if (setsockopt (sockfd[sockfd_used], SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof opt) == SOCKET_ERROR) Log (1, "servmgr setsockopt (SO_REUSEADDR): %s", TCPERR ()); if (bind (sockfd[sockfd_used], ai->ai_addr, ai->ai_addrlen) != 0) { Log (0, "servmgr bind(): %s", TCPERR ()); soclose(sockfd[sockfd_used]); continue; } if (listen (sockfd[sockfd_used], 5) != 0) { Log(0, "servmgr listen(): %s", TCPERR ()); soclose(sockfd[sockfd_used]); continue; } sockfd_used++; } Log (3, "servmgr listen on %s:%s", listen_list->addr[0] ? listen_list->addr : "*", listen_list->port); freeaddrinfo(aiHead); } if (sockfd_used == 0) { Log(0, "servmgr: No listen socket open"); return -1; } setproctitle ("server manager (listen %s)", config->listen.first->port); for (;;) { struct timeval tv; int n; int curfd, maxfd = 0; fd_set r; FD_ZERO (&r); for (curfd=0; curfd<sockfd_used; curfd++) { FD_SET (sockfd[curfd], &r); if (sockfd[curfd] > maxfd) maxfd = sockfd[curfd]; } tv.tv_usec = 0; tv.tv_sec = CHECKCFG_INTERVAL; unblocksig(); check_child(&n_servers); n = select(maxfd+1, &r, NULL, NULL, &tv); blocksig(); switch (n) { case 0: /* timeout */ if (checkcfg()) { for (curfd=0; curfd<sockfd_used; curfd++) soclose(sockfd[curfd]); sockfd_used = 0; return 0; } unblocksig(); check_child(&n_servers); blocksig(); continue; case -1: save_errno = TCPERRNO; if (binkd_exit) goto accepterr; if (TCPERRNO == EINTR) { unblocksig(); check_child(&n_servers); blocksig(); if (checkcfg()) { for (curfd=0; curfd<sockfd_used; curfd++) soclose(sockfd[curfd]); sockfd_used = 0; return 0; } continue; } Log (1, "servmgr select(): %s", TCPERR ()); goto accepterr; } for (curfd=0; curfd<sockfd_used; curfd++) { if (!FD_ISSET(sockfd[curfd], &r)) continue; client_addr_len = sizeof (client_addr); if ((new_sockfd = accept (sockfd[curfd], (struct sockaddr *)&client_addr, &client_addr_len)) == INVALID_SOCKET) { save_errno = TCPERRNO; if (save_errno != EINVAL && save_errno != EINTR) { if (!binkd_exit) Log (1, "servmgr accept(): %s", TCPERR ()); #ifdef UNIX if (save_errno == ECONNRESET || save_errno == ETIMEDOUT || save_errno == ECONNABORTED || save_errno == EHOSTUNREACH) continue; #endif accepterr: #ifdef OS2 /* Buggy external process closed our socket? Or OS/2 bug? */ if (save_errno == ENOTSOCK) return 0; /* will force socket re-creation */ #endif return -1; } } else { char host[BINKD_FQDNLEN + 1]; char service[MAXSERVNAME + 1]; int aiErr; add_socket(new_sockfd); /* Was the socket created after close_sockets loop in exitfunc()? */ if (binkd_exit) { del_socket(new_sockfd); soclose(new_sockfd); continue; } rel_grow_handles (6); ext_rand=rand(); /* never resolve name in here, will be done during session */ aiErr = getnameinfo((struct sockaddr *)&client_addr, client_addr_len, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV); if (aiErr == 0) Log (3, "incoming from %s (%s)", host, service); else { Log(2, "Error in getnameinfo(): %s (%d)", gai_strerror(aiErr), aiErr); Log(3, "incoming from unknown"); } /* Creating a new process for the incoming connection */ threadsafe(++n_servers); if ((pid = branch (serv, (void *) &new_sockfd, sizeof (new_sockfd))) < 0) { del_socket(new_sockfd); soclose(new_sockfd); rel_grow_handles (-6); threadsafe(--n_servers); PostSem(&eothread); Log (1, "servmgr branch(): cannot branch out"); sleep(1); } else { Log (5, "started server #%i, id=%i", n_servers, pid); #if defined(HAVE_FORK) && !defined(HAVE_THREADS) soclose (new_sockfd); #endif } } } } }
static goto_stmt(stream, node) { branch( stream, named_label( &node[3][3], 0 ) ); }
void DolphinSolver::solve<Flexible, Flexible>(const PlayBoard<Flexible>& board) { branch(make_solve_caller(*this), board); }
/** perform branching * * Set the trial energy of clones */ void SimpleFixedNodeBranch::branch(int iter, MCWalkerConfiguration& w, vector<ThisType*>& clones) { branch(iter,w); //synchronize it for(int i=0; i<clones.size(); i++) clones[i]->vParam=vParam; }
genswitch(register struct sw *p, int n) { /* p points to an array of structures, each consisting of a constant value and a label. The first is >=0 if there is a default label; its value is the label number The entries p[1] to p[n] are the nontrivial cases */ register i; register CONSZ j, range; register dlab, swlab; range = p[n].sval-p[1].sval; if( range>0 && range <= 3*n && n>=4 ){ /* implement a direct switch */ swlab = getlab(); dlab = p->slab >= 0 ? p->slab : getlab(); /* already in r0 */ printf(" casel r0,$%ld,$%ld\n", p[1].sval, range); deflab1(swlab); for( i=1,j=p[1].sval; i<=n; j++) { printf(" .word " LABFMT "-" LABFMT "\n", (j == p[i].sval ? ((j=p[i++].sval), p[i-1].slab) : dlab), swlab); } if( p->slab >= 0 ) branch( dlab ); else deflab1(dlab); return; } if( n>8 ) { /* heap switch */ heapsw[0].slab = dlab = p->slab >= 0 ? p->slab : getlab(); makeheap(p, n, 1); /* build heap */ walkheap(1, n); /* produce code */ if( p->slab >= 0 ) branch( dlab ); else deflab1(dlab); return; } /* debugging code */ /* out for the moment if( n >= 4 ) werror( "inefficient switch: %d, %d", n, (int) (range/n) ); */ /* simple switch code */ for( i=1; i<=n; ++i ){ /* already in r0 */ printf( " cmpl r0,$" ); printf( CONFMT, p[i].sval ); printf( "\n jeql " LBLFMT "\n", p[i].slab ); } if( p->slab>=0 ) branch( p->slab ); }
void swcode(Swtch swp, int b[], int lb, int ub) { int hilab, lolab, l, u, k = (lb + ub)/2; long *v = swp->values; if (k > lb && k < ub) { lolab = genlabel(1); hilab = genlabel(1); } else if (k > lb) { lolab = genlabel(1); hilab = swp->deflab->u.l.label; } else if (k < ub) { lolab = swp->deflab->u.l.label; hilab = genlabel(1); } else lolab = hilab = swp->deflab->u.l.label; l = b[k]; u = b[k+1] - 1; if (u - l + 1 <= 3) { int i; for (i = l; i <= u; i++) cmp(EQ, swp->sym, v[i], swp->labels[i]->u.l.label); if (k > lb && k < ub) cmp(GT, swp->sym, v[u], hilab); else if (k > lb) cmp(GT, swp->sym, v[u], hilab); else if (k < ub) cmp(LT, swp->sym, v[l], lolab); else assert(lolab == hilab), branch(lolab); walk(NULL, 0, 0); } else { Tree e; Type ty = signedint(swp->sym->type); Symbol table = genident(STATIC, array(voidptype, u - l + 1, 0), GLOBAL); (*IR->defsymbol)(table); if (!isunsigned(swp->sym->type) || v[l] != 0) cmp(LT, swp->sym, v[l], lolab); cmp(GT, swp->sym, v[u], hilab); e = (*optree['-'])(SUB, cast(idtree(swp->sym), ty), cnsttree(ty, v[l])); if (e->type->size < unsignedptr->size) e = cast(e, unsignedlong); walk(tree(JUMP, voidtype, rvalue((*optree['+'])(ADD, pointer(idtree(table)), e)), NULL), 0, 0); code(Switch); codelist->u.swtch.table = table; codelist->u.swtch.sym = swp->sym; codelist->u.swtch.deflab = swp->deflab; codelist->u.swtch.size = u - l + 1; codelist->u.swtch.values = &v[l]; codelist->u.swtch.labels = &swp->labels[l]; if (v[u] - v[l] + 1 >= 10000) warning("switch generates a huge table\n"); } if (k > lb) { assert(lolab != swp->deflab->u.l.label); definelab(lolab); swcode(swp, b, lb, k - 1); } if (k < ub) { assert(hilab != swp->deflab->u.l.label); definelab(hilab); swcode(swp, b, k + 1, ub); } }
/* * Run one client loop. Return -1 to exit */ static int do_client(BINKD_CONFIG *config) { FTN_NODE *r; int pid; if (!config->q_present) { q_free (SCAN_LISTED, config); if (config->printq) Log (-1, "scan\r"); q_scan (SCAN_LISTED, config); config->q_present = 1; if (config->printq) { LockSem (&lsem); q_list (stderr, SCAN_LISTED, config); ReleaseSem (&lsem); Log (-1, "idle\r"); } } if (n_clients < config->max_clients) { if ((r = q_next_node (config)) != 0) { struct call_args args; if (!bsy_test (&r->fa, F_BSY, config) || !bsy_test (&r->fa, F_CSY, config)) { char szDestAddr[FTN_ADDR_SZ + 1]; ftnaddress_to_str (szDestAddr, &r->fa); Log (4, "%s busy, skipping", szDestAddr); return 0; /* go to the next node */ } rel_grow_handles (6); threadsafe(++n_clients); lock_config_structure(config); args.node = r; args.config = config; if ((pid = branch (call, &args, sizeof (args))) < 0) { unlock_config_structure(config, 0); rel_grow_handles (-6); threadsafe(--n_clients); PostSem(&eothread); Log (1, "cannot branch out"); unblocksig(); SLEEP(1); blocksig(); check_child(&n_clients); } #if !defined(DEBUGCHILD) else { Log (5, "started client #%i, id=%i", n_clients, pid); #if defined(HAVE_FORK) && !defined(AMIGA) unlock_config_structure(config, 0); /* Forked child has own copy */ #endif } #endif } else { if (poll_flag) { if (n_clients <= 0 && q_not_empty (config) == 0) { Log (4, "the queue is empty, quitting..."); return -1; } } else config->q_present = 0; unblocksig(); SLEEP (config->rescan_delay); blocksig(); check_child(&n_clients); } } else { unblocksig(); SLEEP (config->call_delay); blocksig(); check_child(&n_clients); } return 0; }
void statement(int loop, Swtch swp, int lev) { float ref = refinc; if (Aflag >= 2 && lev == 15) warning("more than 15 levels of nested statements\n"); switch (t) { case IF: ifstmt(genlabel(2), loop, swp, lev + 1); break; case WHILE: whilestmt(genlabel(3), swp, lev + 1); break; case DO: dostmt(genlabel(3), swp, lev + 1); expect(';'); break; case FOR: forstmt(genlabel(4), swp, lev + 1); break; case BREAK: walk(NULL, 0, 0); definept(NULL); if (swp && swp->lab > loop) branch(swp->lab + 1); else if (loop) branch(loop + 2); else error("illegal break statement\n"); t = gettok(); expect(';'); break; case CONTINUE: walk(NULL, 0, 0); definept(NULL); if (loop) branch(loop + 1); else error("illegal continue statement\n"); t = gettok(); expect(';'); break; case SWITCH: swstmt(loop, genlabel(2), lev + 1); break; case CASE: { int lab = genlabel(1); if (swp == NULL) error("illegal case label\n"); definelab(lab); while (t == CASE) { static char stop[] = { IF, ID, 0 }; Tree p; t = gettok(); p = constexpr(0); if (generic(p->op) == CNST && isint(p->type)) { if (swp) { needconst++; p = cast(p, swp->sym->type); if (p->type->op == UNSIGNED) p->u.v.i = extend(p->u.v.u, p->type); needconst--; caselabel(swp, p->u.v.i, lab); } } else error("case label must be a constant integer expression\n"); test(':', stop); } statement(loop, swp, lev); } break; case DEFAULT: if (swp == NULL) error("illegal default label\n"); else if (swp->deflab) error("extra default label\n"); else { swp->deflab = findlabel(swp->lab); definelab(swp->deflab->u.l.label); } t = gettok(); expect(':'); statement(loop, swp, lev); break; case RETURN: { Type rty = freturn(cfunc->type); t = gettok(); definept(NULL); if (t != ';') if (rty == voidtype) { error("extraneous return value\n"); expr(0); retcode(NULL); } else retcode(expr(0)); else { if (rty != voidtype) { warning("missing return value\n"); retcode(cnsttree(inttype, 0L)); } else retcode(NULL); } branch(cfunc->u.f.label); } expect(';'); break; case '{': compound(loop, swp, lev + 1); break; case ';': definept(NULL); t = gettok(); break; case GOTO: walk(NULL, 0, 0); definept(NULL); t = gettok(); if (t == ID) { Symbol p = lookup(token, stmtlabs); if (p == NULL) { p = install(token, &stmtlabs, 0, FUNC); p->scope = LABELS; p->u.l.label = genlabel(1); p->src = src; } use(p, src); branch(p->u.l.label); t = gettok(); } else error("missing label in goto\n"); expect(';'); break; case ID: if (getchr() == ':') { stmtlabel(); statement(loop, swp, lev); break; } default: definept(NULL); if (kind[t] != ID) { error("unrecognized statement\n"); t = gettok(); } else { Tree e = expr0(0); listnodes(e, 0, 0); if (nodecount == 0 || nodecount > 200) walk(NULL, 0, 0); else if (glevel) walk(NULL, 0, 0); deallocate(STMT); } expect(';'); break; } if (kind[t] != IF && kind[t] != ID && t != '}' && t != EOI) { static char stop[] = { IF, ID, '}', 0 }; error("illegal statement termination\n"); skipto(0, stop); } refinc = ref; }
int main(){ int a, i;//カウンタ変数 int phase[MAXNUMBER];//波の位相の配列 int color[MAXNUMBER];//波の色の配列 int droparray[MAXNUMBER];//落ちる水滴の配列 float x;//円の中心x座標 float y;//円の中心y座標 float r[MAXNUMBER];//円の半径の配列 float scale;//減衰のための係数 float phasescale;//位相の減衰係数 float sum;//波を足し合わせる関数 int count;//カウント変数 int offset;//波の相殺 int flag;//フラグ変数 win=gopen(800,800);/*画面表示*/ winname(win,"final");/*題名*/ phasescale = 0.25; flag = 0; /*水滴の描画*/ for(a=0; a<=1; a++){ for(i=0; i<=150; i++){ background();//背景を描く関数 if(a==1){ newpen(win , 1); fillcirc(win, 270, 610, 6, 6); /*葉っぱの先の水滴を描く*/ } branch();//木の幹を書く関数 rightleaf();//上側の葉っぱを描く関数 underleaf();//下側の葉っぱを描く関数 mainleaf();//メインの葉っぱを描く関数 surfacewater();//水面を描く関数 newpen(win, 1); fillcirc(win, 426-i, 761-i, 5, 5); /*葉っぱの初期移動*/ msleep(50); } } /*波の初期設定*/ for(i=0; i < MAXNUMBER; i++){ color[i] = 128; phase[i] = -1; droparray[i]=-1; r[i]=(MAXLENGTH / MAXNUMBER) * i;//円の半径初期化 } x=300.0; y=300.0; layer(win, 0, 1); /*表示は 0 番、描画は 1 番レイヤーで*/ /*波が非同期に落ちる*/ while(1){ background();//背景を描く関数 /*葉っぱの先の水滴を描く*/ newpen(win , 1); fillcirc(win, 270, 610, 6, 6); branch();//木の幹を描く関数 rightleaf();//上側の葉っぱを描く関数 underleaf();//下側の葉っぱを描く関数 mainleaf();//メインの葉っぱを描く関数 surfacewater();//水面を描く関数 /*初期化*/ color[0] = 0; sum = 0; count = 0; for(i=0; i < MAXNUMBER; i++){ if(phase[i] >= 200){ phase[i] = -1; flag = 1; } if(phase[i] != -1){ scale = (MAXNUMBER - phase[i])*0.01; sum += 128*(sin(ENSHUU/MAXNUMBER-phasescale*phase[i])*scale); count++; msleep(3); } } if(count > 0){ color[0] = sum / count + 128 - offset; if(flag == 1){ offset += color[0] - color[1]; flag = 0; } if(offset > 0){ offset--; }else if(offset < 0){ offset++; } } if(color[0] == 0 || color[0] >= 255 ){ color[0] = 128; } for(i=MAXNUMBER-1; i>0; i--){ color[i]=color[i-1]; } for(i=MAXNUMBER-1; i>=0; i--) { if( r[i] > 0.0 ) { newhsvcolor(win, 200, color[i], 255); fillcirc(win, x, y, r[i], r[i]); } } if(drop(droparray) == 1){ for(i=0; i<MAXNUMBER; i++){ if(phase[i] == -1){ phase[i] = 0; break; } } } for(i=0; i<=MAXNUMBER; i++){ if(phase[i] != -1){ phase[i]++; } } copylayer(win, 1, 0); /*レイヤー 1 番の内容を 0 にコピー*/ msleep(40); } gclose(win);/*つける必要はないですけど開いたら閉じたかったのでつけました*/ return 0; }
ShiftSched(int _staff, int _shifts, int _acts, vec< vec<int> >& _demand, int mode) : staff(_staff), shifts(_shifts), acts(_acts), dom(acts+maxG), demand(_demand) { for(int ww = 0; ww < staff; ww++) { xv.push(); for( int ss = 0; ss < shifts; ss++ ) { xv[ww].push(newIntVar(0,dom-1)); xv[ww][ss]->specialiseToEL(); } } // Build the grammar int first = 0; while(first < shifts) { for(int ii = 0; ii < acts; ii++) { if(demand[first][ii]) goto found_first; } first++; } found_first: int last = first; for(int ss = first; ss < shifts; ss++) { for(int ii = 0; ii < acts; ii++) { if(demand[ss][ii]) { last = ss; break; } } } CFG::CFG g( buildSchedG(acts, first, last) ); // Construct variables for the circuit MDDTable mdd_tab(shifts); std::vector< std::vector<MDD> > seq; for(int ii = 0; ii < shifts; ii++) { seq.push_back( std::vector<MDD>() ); for(int kk = 0; kk < dom; kk++) { seq[ii].push_back(mdd_tab.vareq(ii, kk)); } } MDD gcirc(parseCYK(mdd_tab.fff(), seq, g)); // Convert the MDD into an edge-valued graph. vec<int> slot_cost; for(int si = 0; si < acts; si++) slot_cost.push(1); for(int si = acts; si < dom; si++) slot_cost.push(0); EVLayerGraph graph; EVLayerGraph::NodeID gcirc_evgraph(mdd_to_layergraph(graph, gcirc, slot_cost)); // Enforce the schedule for each worker. MDDOpts mopts; mopts.expl_strat = MDDOpts::E_KEEP; mopts.expl_alg = MDDOpts::E_MINIMAL; for(int ww = 0; ww < staff; ww++) { staff_cost.push(newIntVar(0, shifts)); evgraph_to_wmdd(xv[ww], staff_cost[ww], graph, gcirc_evgraph, mopts); } for(int ww = 1; ww < staff; ww++) lex(xv[ww-1],xv[ww],false); // Enforce coverage constraints. for(int ss = 0; ss < shifts; ss++) { for(int act = 0; act < acts; act++) { vec<BoolView> bv; for(int ww = 0; ww < staff; ww++) { bv.push(xv[ww][ss]->getLit(act,1)); } bool_linear_decomp(bv, IRT_GE, demand[ss][act]); // IntVar* d_const = newIntVar(demand[ss][act], demand[ss][act]); // bool_linear(bv, IRT_GE, d_const); } } unsigned int cMin(0); for(int ss = 0; ss < shifts; ss++) { for(int aa = 0; aa < acts; aa++) { cMin += demand[ss][aa]; } } cost = newIntVar(cMin, (last - first + 1)*staff); int_linear(staff_cost, IRT_LE, cost); #if 0 vec<IntVar*> rostered_int; for(int ss = 0; ss < shifts; ss++) { if(ss < first || ss > last) continue; for(int ww = 0; ww < staff; ww++) { IntVar* sv = newIntVar(0,1); bool2int(xv[ww][ss]->getLit(acts-1,3),sv); rostered_int.push(sv); } } int_linear(rostered_int, IRT_GE, cost); #endif vec<IntVar*> vs; for(int ss = 0; ss < shifts; ss++) { for(int ww = 0; ww < staff; ww++) { vs.push(xv[ww][ss]); } } branch(vs, VAR_INORDER, VAL_MAX); optimize(cost, OPT_MIN); // vs.push(cost); output_vars(vs); }
void TemplateTable::_goto() { transition(vtos, vtos); branch(false, false); }
void branch(int s_row, int s_col, short int in[MAPSIZE][MAPSIZE]) { //s_row and s_col refer to a grid in the array where there is a 5. At this point the path will branch //branch in a random direction int direction = rand()% 7+1; int die_chance = 5; switch (direction) { case 1: if (in[s_row-1][s_col-1] != 0 && in[s_row-1][s_col-1] != 5) { if (rand()%100 > die_chance) branch(s_row-1,s_col-1,in); break; } case 2: if (in[s_row-1][s_col] != 0 && in[s_row-1][s_col] != 5) { in[s_row-1][s_col] = 6; if (rand()%100 > die_chance) branch(s_row-1,s_col,in); break; } case 3: if (in[s_row-1][s_col+1] != 0 && in[s_row-1][s_col+1] != 5) { in[s_row-1][s_col+1] = 6; if (rand()%100 > die_chance) branch(s_row-1,s_col+1,in); break; } case 4: if (in[s_row][s_col-1] != 0 && in[s_row][s_col-1] != 5) { in[s_row][s_col-1] = 6; if (rand()%100 > die_chance) branch(s_row,s_col-1,in); break; } case 5: if (in[s_row][s_col+1] != 0 && in[s_row][s_col+1] != 5) { in[s_row][s_col+1] = 6; if (rand()%100 > die_chance) branch(s_row,s_col+1,in); break; } case 6: if (in[s_row+1][s_col-1] != 0 && in[s_row+1][s_col-1] != 5) { in[s_row+1][s_col-1] = 6; if (rand()%100 > die_chance) branch(s_row+1,s_col-1,in); break; } case 7: if (in[s_row+1][s_col] != 0 && in[s_row+1][s_col] != 5) { in[s_row+1][s_col] = 6; if (rand()%100 > die_chance) branch(s_row+1,s_col,in); break; } case 8: if (in[s_row+1][s_col+1] != 0 && in[s_row+1][s_col+1] != 5) { in[s_row+1][s_col+11] = 6; if (rand()%100 > die_chance) branch(s_row+1,s_col+1,in); break; } default: break; } }