// header and do while switch that keeps showing you options until you exit int main(){ int choice; printf("Roncon Contact Directory\n"); printf("========================\n"); initList(); load(); do{ choice = showMenu(); switch(choice){ case 0: // exit printf("Goodbye\n"); break; case 1: // view all printf("View all:\n"); if(listHead->next != listTail){ view(); } else{ printf("No contacts\n"); } break; case 2: // search printf("Search:\n"); if(encrypted){ printf("Decrypt file first!\n"); } else{ search(); } break; case 3: // add printf("Add: \n"); if(encrypted){ printf("Decrypt file first!\n"); } else{ add(); } break; case 4: // remove printf("Remove:\n"); if(encrypted){ printf("Decrypt file first!\n"); } else{ rem(); } break; case 5: // edit printf("Edit:\n"); if(encrypted){ printf("Decrypt file first!\n"); } else{ edit(); } break; case 6: // sort printf("Sort:\n"); if(listHead->next != listTail){ sort(); } else{ printf("No contacts\n"); } break; case 7: // encrypt printf("En/Decrypt:\n"); encryptFile(); break; default: printf("Not a valid number, re-enter.\n"); break; } // switch }while(choice != 0); save(); printf("\n\n"); system("pause"); } // main

int main() { SetSeed(ZZ(0)); cerr << "This is NTL version " << NTL_VERSION << "\n"; cerr << "Hardware charactersitics:\n"; cerr << "NTL_BITS_PER_LONG = " << NTL_BITS_PER_LONG << "\n"; cerr << "NTL_ZZ_NBITS = " << NTL_ZZ_NBITS << "\n"; cerr << "NTL_SP_NBITS = " << NTL_SP_NBITS << "\n"; #ifdef NTL_LONGDOUBLE_SP_MULMOD cerr << "NTL_LONGDOUBLE_SP_MULMOD\n"; #endif #ifdef NTL_LONGLONG_SP_MULMOD cerr << "NTL_LONGLONG_SP_MULMOD\n"; #endif cerr << "\n"; cerr << "Basic Configuration Options:\n"; #ifdef NTL_LEGACY_NO_NAMESPACE cerr << "NTL_LEGACY_NO_NAMESPACE\n"; #endif #ifdef NTL_LEGACY_INPUT_ERROR cerr << "NTL_LEGACY_INPUT_ERROR\n"; #endif #ifdef NTL_THREADS cerr << "NTL_THREADS\n"; #endif #ifdef NTL_EXCEPTIONS cerr << "NTL_EXCEPTIONS\n"; #endif #ifdef NTL_LEGACY_SP_MULMOD cout << "NTL_LEGACY_SP_MULMOD\n"; #endif #ifdef NTL_DISABLE_LONGDOUBLE cout << "NTL_DISABLE_LONGDOUBLE\n"; #endif #ifdef NTL_DISABLE_LONGLONG cout << "NTL_DISABLE_LONGLONG\n"; #endif #ifdef NTL_GMP_LIP cerr << "NTL_GMP_LIP\n"; #endif #ifdef NTL_GF2X_LIB cerr << "NTL_GF2X_LIB\n"; #endif #ifdef NTL_PCLMUL cerr << "NTL_PCLMUL\n"; #endif #ifdef NTL_LONG_LONG_TYPE cerr << "NTL_LONG_LONG_TYPE: "; cerr << make_string(NTL_LONG_LONG_TYPE) << "\n"; #endif #ifdef NTL_UNSIGNED_LONG_LONG_TYPE cerr << "NTL_UNSIGNED_LONG_LONG_TYPE: "; cerr << make_string(NTL_UNSIGNED_LONG_LONG_TYPE) << "\n"; #endif #ifdef NTL_X86_FIX cerr << "NTL_X86_FIX\n"; #endif #ifdef NTL_NO_X86_FIX cerr << "NTL_NO_X86_FIX\n"; #endif #ifdef NTL_NO_INIT_TRANS cerr << "NTL_NO_INIT_TRANS\n"; #endif #ifdef NTL_CLEAN_INT cerr << "NTL_CLEAN_INT\n"; #endif #ifdef NTL_CLEAN_PTR cerr << "NTL_CLEAN_PTR\n"; #endif #ifdef NTL_RANGE_CHECK cerr << "NTL_RANGE_CHECK\n"; #endif cerr << "\n"; cerr << "Resolution of double-word types:\n"; cerr << make_string(NTL_LL_TYPE) << "\n"; cerr << make_string(NTL_ULL_TYPE) << "\n"; cerr << "\n"; cerr << "Performance Options:\n"; #ifdef NTL_LONG_LONG cerr << "NTL_LONG_LONG\n"; #endif #ifdef NTL_AVOID_FLOAT cerr << "NTL_AVOID_FLOAT\n"; #endif #ifdef NTL_SPMM_ULL cerr << "NTL_SPMM_ULL\n"; #endif #ifdef NTL_SPMM_ASM cerr << "NTL_SPMM_ASM\n"; #endif #ifdef NTL_AVOID_BRANCHING cerr << "NTL_AVOID_BRANCHING\n"; #endif #ifdef NTL_FFT_BIGTAB cout << "NTL_FFT_BIGTAB\n"; #endif #ifdef NTL_FFT_LAZYMUL cout << "NTL_FFT_LAZYMUL\n"; #endif #ifdef NTL_TBL_REM cerr << "NTL_TBL_REM\n"; #endif #ifdef NTL_TBL_REM_LL cerr << "NTL_TBL_REM_LL\n"; #endif #ifdef NTL_GF2X_ALTCODE cerr << "NTL_GF2X_ALTCODE\n"; #endif #ifdef NTL_GF2X_ALTCODE1 cerr << "NTL_GF2X_ALTCODE1\n"; #endif #ifdef NTL_GF2X_NOINLINE cerr << "NTL_GF2X_NOINLINE\n"; #endif cerr << "\n\n"; cerr << "running tests"; long n, k, i; n = 250; k = 16000; ZZ p; for (i = 0; i < 15; i++) { // cerr << n << "/" << k; cerr << "."; RandomLen(p, k); ZZ_p::init(p); ZZ_pX a, b, c, c1; random(a, n); random(b, n); FFTMul(c, a, b); c1 = conv<ZZ_pX>( SSMul( conv<ZZX>(a), conv<ZZX>(b) ) ); if (c1 != c) { cerr << "ZZ_pX mul failed!\n"; return 1; } n = long(n * 1.35); k = long(k / 1.414); } // small prime tests...I've made some changes in v5.3 // that should be checked on various platforms, so // we might as well check them here. if (SmallModulusTest(17, 1000)) { cerr << "first SmallModulusTest failed!!\n"; return 1; } if (SmallModulusTest((1L << (NTL_SP_NBITS))-1, 1000)) { cerr << "second SmallModulusTest failed!!\n"; return 1; } // Test gf2x code.... if (GF2X_test()) { cerr << "GF2X test failed!\n"; return 1; } cerr << "OK\n"; ZZ x1, x2, x3, x4; double t; RandomLen(x1, 1024); RandomBnd(x2, x1); RandomBnd(x3, x1); mul(x4, x2, x3); t = GetTime(); for (i = 0; i < 100000; i++) mul(x4, x2, x3); t = GetTime()-t; cerr << "time for 1024-bit mul: " << t*10 << "us"; cerr << "\n"; rem(x2, x4, x1); t = GetTime(); for (i = 0; i < 100000; i++) rem(x2, x4, x1); t = GetTime()-t; cerr << "time for 2048/1024-bit rem: " << t*10 << "us"; cerr << "\n"; GenPrime(p, 1024); RandomBnd(x1, p); if (IsZero(x1)) set(x1); InvMod(x2, x1, p); t = GetTime(); for (i = 0; i < 1000; i++) InvMod(x2, x1, p); t = GetTime()-t; cerr << "time for 1024-bit modular inverse: " << t*1000 << "us"; cerr << "\n"; // test modulus switching n = 1024; k = 1024; RandomLen(p, k); ZZ_p::init(p); ZZ_pX j1, j2, j3; random(j1, n); random(j2, n); mul(j3, j1, j2); t = GetTime(); for (i = 0; i < 100; i++) mul(j3, j1, j2); t = GetTime()-t; cerr << "time to multiply degree 1023 polynomials\n modulo a 1024-bit number: "; cerr << (t/100) << "s"; cerr << "\n"; GF2X_time(); return 0; }

// bootstrap a ciphertext to reduce noise void FHEPubKey::thinReCrypt(Ctxt &ctxt) { FHE_TIMER_START; // Some sanity checks for dummy ciphertext long ptxtSpace = ctxt.getPtxtSpace(); if (ctxt.isEmpty()) return; if (ctxt.parts.size()==1 && ctxt.parts[0].skHandle.isOne()) { // Dummy encryption, just ensure that it is reduced mod p ZZX poly = to_ZZX(ctxt.parts[0]); for (long i=0; i<poly.rep.length(); i++) poly[i] = to_ZZ( rem(poly[i],ptxtSpace) ); poly.normalize(); ctxt.DummyEncrypt(poly); return; } assert(recryptKeyID>=0); // check that we have bootstrapping data long p = ctxt.getContext().zMStar.getP(); long r = ctxt.getContext().alMod.getR(); long p2r = ctxt.getContext().alMod.getPPowR(); const ThinRecryptData& trcData = ctxt.getContext().trcData; // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}. long e = trcData.e; long ePrime = trcData.ePrime; long p2ePrime = power_long(p,ePrime); long q = power_long(p,e)+1; assert(e>=r); #ifdef DEBUG_PRINTOUT cerr << "reCrypt: p="<<p<<", r="<<r<<", e="<<e<<" ePrime="<<ePrime << ", q="<<q<<endl; #endif // can only bootstrap ciphertext with plaintext-space dividing p^r assert(p2r % ptxtSpace == 0); #ifdef PRINT_LEVELS CheckCtxt(ctxt, "init"); #endif if (thinRecrypt_initial_level) { // experimental code...we should drop down // to a reasonably small level before doing the // first linear map. // TODO: we should also check that we have enough // levels to do the first linear map. ctxt.modDownToLevel(thinRecrypt_initial_level); } #ifdef PRINT_LEVELS CheckCtxt(ctxt, "after mod down"); #endif // Move the slots to powerful-basis coefficients FHE_NTIMER_START(AAA_slotToCoeff); trcData.slotToCoeff->apply(ctxt); FHE_NTIMER_STOP(AAA_slotToCoeff); #ifdef PRINT_LEVELS CheckCtxt(ctxt, "after slotToCoeff"); #endif FHE_NTIMER_START(AAA_bootKeySwitch); // Make sure that this ciphertxt is in canonical form if (!ctxt.inCanonicalForm()) ctxt.reLinearize(); // Mod-switch down if needed IndexSet s = ctxt.getPrimeSet() / ctxt.getContext().specialPrimes; // set minus if (s.card()>2) { // leave only bottom two primes long frst = s.first(); long scnd = s.next(frst); IndexSet s2(frst,scnd); s.retain(s2); // retain only first two primes } ctxt.modDownToSet(s); // key-switch to the bootstrapping key ctxt.reLinearize(recryptKeyID); // "raw mod-switch" to the bootstrapping mosulus q=p^e+1. vector<ZZX> zzParts; // the mod-switched parts, in ZZX format double noise = ctxt.rawModSwitch(zzParts, q); noise = sqrt(noise); // Add multiples of p2r and q to make the zzParts divisible by p^{e'} long maxU=0; for (long i=0; i<(long)zzParts.size(); i++) { // make divisible by p^{e'} long newMax = makeDivisible(zzParts[i].rep, p2ePrime, p2r, q, trcData.alpha); zzParts[i].normalize(); // normalize after working directly on the rep if (maxU < newMax) maxU = newMax; } // Check that the estimated noise is still low if (noise + maxU*p2r*(skHwts[recryptKeyID]+1) > q/2) cerr << " * noise/q after makeDivisible = " << ((noise + maxU*p2r*(skHwts[recryptKeyID]+1))/q) << endl; for (long i=0; i<(long)zzParts.size(); i++) zzParts[i] /= p2ePrime; // divide by p^{e'} // Multiply the post-processed cipehrtext by the encrypted sKey #ifdef DEBUG_PRINTOUT cerr << "+ Before recryption "; decryptAndPrint(cerr, recryptEkey, *dbgKey, *dbgEa, printFlag); #endif double p0size = to_double(coeffsL2Norm(zzParts[0])); double p1size = to_double(coeffsL2Norm(zzParts[1])); ctxt = recryptEkey; ctxt.multByConstant(zzParts[1], p1size*p1size); ctxt.addConstant(zzParts[0], p0size*p0size); #ifdef DEBUG_PRINTOUT cerr << "+ Before linearTrans1 "; decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag); #endif FHE_NTIMER_STOP(AAA_bootKeySwitch); #ifdef PRINT_LEVELS CheckCtxt(ctxt, "after bootKeySwitch"); #endif // Move the powerful-basis coefficients to the plaintext slots FHE_NTIMER_START(AAA_coeffToSlot); trcData.coeffToSlot->apply(ctxt); FHE_NTIMER_STOP(AAA_coeffToSlot); #ifdef PRINT_LEVELS CheckCtxt(ctxt, "after coeffToSlot"); #endif #ifdef DEBUG_PRINTOUT cerr << "+ After linearTrans1 "; decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag); #endif // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots) FHE_NTIMER_START(AAA_extractDigitsThin); extractDigitsThin(ctxt, e-ePrime, r, ePrime); FHE_NTIMER_STOP(AAA_extractDigitsThin); #ifdef PRINT_LEVELS CheckCtxt(ctxt, "after extractDigitsThin"); #endif #ifdef DEBUG_PRINTOUT cerr << "+ Before linearTrans2 "; decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag); #endif }

/* if can find adj_list[i] that is a clique remove i, all edges from i; ordering[o++] = i; cliques[c++] = adj_list[i]; else find adj_list[i] with smallest clique weight remove i, all edges from i; ordering[o++] = i; make adj_list[i] a clique; cliques[c++] = adj_list[i]; */ Elimination elim(int size, Map * adj_list, Neighborhood * partial_order, Map node_map){ Map ordering, cliques, max_cliques, trashcan; int i, j, clique_exists, min_node, subset, index1, index2; float min_weight, weight; word w, w2, child, child2; Iterator iter, iter2; Map nodes = create_Map(size, compare, hash_int, empty(), 1); Map roots = create_Map(size, compare, hash_int, empty(), 1); int ** fill_ins; fill_ins = (int **) malloc(sizeof(int *) * size); fill_ins[0] = (int *) malloc(sizeof(int) * size * size); for(i = 1; i < size; i++){ fill_ins[i] = fill_ins[i - 1] + size; } for(i = 0; i < size; i++){ for(j = 0; j < size; j++){ fill_ins[i][j] = 0; } } for(i = 0; i < size; i++){ w.i = i; put(nodes, w, w); } find_roots(partial_order, nodes, roots); ordering = create_Map(size + 1, compare, hash_int, empty(), 1); cliques = create_Map(size + 1, set_compare, hash_set, empty(), 1); while(get_size_Map(nodes) > 0){ clique_exists = 0; iter = get_Iterator(roots); while(!is_empty(iter)){ w = next_key(iter); if(is_clique_heuristic(w.i, adj_list) && is_clique(w.i, adj_list, size)){ clique_exists = 1; break; } } if(!clique_exists){ min_weight = LONG_MAX; iter = get_Iterator(roots); while(!is_empty(iter)){ w = next_value(iter); weight = 0; iter2 = get_Iterator(adj_list[w.i]); while(!is_empty(iter2)){ weight += ((Node) next_value(iter2).v)->weight; } if(weight < min_weight){ min_weight = weight; min_node = w.i; } } w.i = min_node; } min_node = w.i; rem(nodes, w); remove_node(partial_order, w.i); empty_Map(roots); find_roots(partial_order, nodes, roots); put(ordering, w, w); child.v = adj_list[w.i]; if(!find((Map) child.v, w)){ child2.v = create_Node(w.i, 0); put(node_map, child2, child2); put((Map) child.v, w, child2); } child.v = copy_Map((Map) child.v); put(cliques, child, child); iter = get_Iterator(adj_list[min_node]); i = 0; while(!is_empty(iter)){ child = next_value(iter); rem(adj_list[((Node) child.v)->index], w); } iter = create_Iterator(adj_list[min_node]); while(!is_empty(iter)){ child = next_value(iter); index1 = ((Node) child.v)->index; w.i = index1; iter2 = get_Iterator(adj_list[min_node]); while(!is_empty(iter2)){ child2 = next_value(iter2); index2 = ((Node) child2.v)->index; if(index1 != index2){ w2.i = index2; if(index1 < index2 && !find(adj_list[index1], w2)){ fill_ins[index1][index2] = 1; } put(adj_list[index1], w2, child2); } } } destroy_Iterator(iter); } destroy_Map(nodes); destroy_Map(roots); max_cliques = create_Map(size, set_compare, hash_set, empty(), 2); trashcan = create_Map(size, set_compare, hash_set, empty(), 2); while(get_size_Map(cliques) > 0){ iter = get_Iterator(cliques); child = next_key(iter); rem(cliques, child); subset = 0; while(!is_empty(iter)){ child2 = next_key(iter); if(is_subset_of((Map) child2.v, (Map) child.v)){ rem(cliques, child2); put(trashcan, child2, child2); } else if(is_subset_of((Map) child.v, (Map) child2.v)){ subset = 1; break; } } if(!subset){ put(max_cliques, child, child); } else { put(trashcan, child, child); } } destroy_Map(cliques); iter = get_Iterator(trashcan); while(!is_empty(iter)){ child = next_key(iter); destroy_Map((Map) child.v); } destroy_Map(trashcan); return create_Elimination(ordering, max_cliques, fill_ins, node_map); }

void inv(zz_pE& d, mat_zz_pE& X, const mat_zz_pE& A) { long n = A.NumRows(); if (A.NumCols() != n) LogicError("inv: nonsquare matrix"); if (n == 0) { set(d); X.SetDims(0, 0); return; } long i, j, k, pos; zz_pX t1, t2; zz_pX *x, *y; const zz_pXModulus& p = zz_pE::modulus(); UniqueArray<vec_zz_pX> M_store; M_store.SetLength(n); vec_zz_pX *M = M_store.get(); for (i = 0; i < n; i++) { M[i].SetLength(2*n); for (j = 0; j < n; j++) { M[i][j].rep.SetMaxLength(2*deg(p)-1); M[i][j] = rep(A[i][j]); M[i][n+j].rep.SetMaxLength(2*deg(p)-1); clear(M[i][n+j]); } set(M[i][n+i]); } zz_pX det; set(det); for (k = 0; k < n; k++) { pos = -1; for (i = k; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) { pos = i; } } if (pos != -1) { if (k != pos) { swap(M[pos], M[k]); negate(det, det); } MulMod(det, det, M[k][k], p); // make M[k, k] == -1 mod p, and make row k reduced InvMod(t1, M[k][k], p); negate(t1, t1); for (j = k+1; j < 2*n; j++) { rem(t2, M[k][j], p); MulMod(M[k][j], t2, t1, p); } for (i = k+1; i < n; i++) { // M[i] = M[i] + M[k]*M[i,k] t1 = M[i][k]; // this is already reduced x = M[i].elts() + (k+1); y = M[k].elts() + (k+1); for (j = k+1; j < 2*n; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(*x, *x, t2); } } } else { clear(d); return; } } X.SetDims(n, n); for (k = 0; k < n; k++) { for (i = n-1; i >= 0; i--) { clear(t1); for (j = i+1; j < n; j++) { mul(t2, rep(X[j][k]), M[i][j]); add(t1, t1, t2); } sub(t1, t1, M[i][n+k]); conv(X[i][k], t1); } } conv(d, det); }

void DDF(vec_pair_ZZ_pX_long& factors, const ZZ_pX& ff, const ZZ_pX& hh, long verbose) { ZZ_pX f = ff; ZZ_pX h = hh; if (!IsOne(LeadCoeff(f))) LogicError("DDF: bad args"); factors.SetLength(0); if (deg(f) == 0) return; if (deg(f) == 1) { AddFactor(factors, f, 1, verbose); return; } long CompTableSize = 2*SqrRoot(deg(f)); long GCDTableSize = ZZ_pX_BlockingFactor; ZZ_pXModulus F; build(F, f); ZZ_pXNewArgument H; build(H, h, F, min(CompTableSize, deg(f))); long i, d, limit, old_n; ZZ_pX g, X; vec_ZZ_pX tbl(INIT_SIZE, GCDTableSize); SetX(X); i = 0; g = h; d = 1; limit = GCDTableSize; while (2*d <= deg(f)) { old_n = deg(f); sub(tbl[i], g, X); i++; if (i == limit) { ProcessTable(f, factors, F, i, tbl, d, verbose); i = 0; } d = d + 1; if (2*d <= deg(f)) { // we need to go further if (deg(f) < old_n) { // f has changed build(F, f); rem(h, h, f); rem(g, g, f); build(H, h, F, min(CompTableSize, deg(f))); } CompMod(g, g, H, F); } } ProcessTable(f, factors, F, i, tbl, d-1, verbose); if (!IsOne(f)) AddFactor(factors, f, deg(f), verbose); }

void SFCanZass(vec_ZZ_pX& factors, const ZZ_pX& ff, long verbose) { ZZ_pX f = ff; if (!IsOne(LeadCoeff(f))) LogicError("SFCanZass: bad args"); if (deg(f) == 0) { factors.SetLength(0); return; } if (deg(f) == 1) { factors.SetLength(1); factors[0] = f; return; } factors.SetLength(0); double t; const ZZ& p = ZZ_p::modulus(); ZZ_pXModulus F; build(F, f); ZZ_pX h; if (verbose) { cerr << "computing X^p..."; t = GetTime(); } PowerXMod(h, p, F); if (verbose) { cerr << (GetTime()-t) << "\n"; } vec_pair_ZZ_pX_long u; if (verbose) { cerr << "computing DDF..."; t = GetTime(); } NewDDF(u, f, h, verbose); if (verbose) { t = GetTime()-t; cerr << "DDF time: " << t << "\n"; } ZZ_pX hh; vec_ZZ_pX v; long i; for (i = 0; i < u.length(); i++) { const ZZ_pX& g = u[i].a; long d = u[i].b; long r = deg(g)/d; if (r == 1) { // g is already irreducible append(factors, g); } else { // must perform EDF if (d == 1) { // root finding RootEDF(v, g, verbose); append(factors, v); } else { // general case rem(hh, h, g); EDF(v, g, hh, d, verbose); append(factors, v); } } } }

void CServer::RunOTThread() { cout << "\not thread started\n" << flush; // IKNP-first step: receiver of Naor-Pinkas ZZ& p = CConfig::GetInstance()->GetPrime(); ZZ q = p/2 - 1; ZZ& g = CConfig::GetInstance()->GetGenerator(); // NP receiver: receive Cs int nBufSize = NUM_EXECS_NAOR_PINKAS * FIELD_SIZE_IN_BYTES; BYTE* pBuf = new BYTE[nBufSize]; m_sockOT.Receive(pBuf, nBufSize); ZZ* pC = new ZZ[NUM_EXECS_NAOR_PINKAS]; BYTE* pBufIdx = pBuf; for(int i=0, idx=0; i<NUM_EXECS_NAOR_PINKAS; i++) { ZZFromBytes(pC[i], pBufIdx, FIELD_SIZE_IN_BYTES); pBufIdx += FIELD_SIZE_IN_BYTES; #ifdef _DEBUG cout << "pC[" << i <<"]: " << pC[i] << endl; #endif } // compute pk0, pk1 CBitVector rnd; rnd.Create(NUM_EXECS_NAOR_PINKAS*FIELD_SIZE_IN_BITS, m_aSeed, m_nCounter); BYTE* pBufRnd = rnd.GetArr(); ZZ* pK = new ZZ[NUM_EXECS_NAOR_PINKAS]; ZZ ztmp; for(int i=0, idx=0; !m_bStop && i<NUM_EXECS_NAOR_PINKAS; i++) { ZZFromBytes(ztmp, pBufRnd, FIELD_SIZE_IN_BYTES); pBufRnd += FIELD_SIZE_IN_BYTES; rem(pK[i], ztmp, q); } pBufIdx = pBuf; ZZ pk0, pk1; for(int i=0, idx=0; !m_bStop && i<NUM_EXECS_NAOR_PINKAS; i++) { // compute pk0, pk1 if( !m_S.GetBit(i) ) { PowerMod(pk0, g, pK[i], p); } else { PowerMod(pk1, g, pK[i], p); //pk0 = pC[i]/pk1; InvMod(ztmp, pk1, p); MulMod(pk0, pC[i], ztmp, p); } #ifdef _DEBUG cout << "pk0[" << i << "]: " << pk0 << endl; #endif // put pk0 BytesFromZZ(pBufIdx, pk0, FIELD_SIZE_IN_BYTES); pBufIdx += FIELD_SIZE_IN_BYTES; } m_sockOT.Send(pBuf, nBufSize); delete [] pC; delete [] pBuf; if( m_bStop ) return; // NP receiver: get the g^r0, Enc(M0), g^r2, Enc(M1) int nInputStart = m_pCircuit->GetInputStart(ID_CLIENT); int nInputEnd = m_pCircuit->GetInputEnd(ID_CLIENT); int nMsgSize = (nInputEnd-nInputStart)/SHA1_BITS + 1; // in sha1 scale int nMsginOT = FIELD_SIZE_IN_BYTES + nMsgSize*SHA1_BYTES; int nBufSize2 = NUM_EXECS_NAOR_PINKAS * nMsginOT * 2; BYTE* pBuf2 = new BYTE[nBufSize2]; m_sockOT.Receive(pBuf2, nBufSize2); ZZ w; ZZ key; BYTE tmp[FIELD_SIZE_IN_BYTES]; sha1_context sha; SHA_BUFFER buf_key; BYTE** ppMat = new BYTE*[NUM_EXECS_NAOR_PINKAS]; BYTE* pBufToRead; BYTE* pBufMatIdx; pBufIdx = pBuf2; for(int i=0, idx=0; !m_bStop && i<NUM_EXECS_NAOR_PINKAS; i++) { ppMat[i] = new BYTE[nMsgSize*SHA1_BYTES]; if( !m_S.GetBit(i)) { pBufToRead = pBufIdx; pBufIdx += nMsginOT + nMsginOT; } else { pBufIdx += nMsginOT; pBufToRead = pBufIdx; pBufIdx += nMsginOT; } ZZFromBytes(w, pBufToRead, FIELD_SIZE_IN_BYTES); pBufToRead += FIELD_SIZE_IN_BYTES; PowerMod(key, w, pK[i], p); BytesFromZZ(tmp, key, FIELD_SIZE_IN_BYTES); sha1_starts(&sha); sha1_update(&sha, tmp, FIELD_SIZE_IN_BYTES); sha1_finish(&sha, (BYTE*) &buf_key); pBufMatIdx=ppMat[i]; for(int j=0; j<nMsgSize; j++) { sha1_starts(&sha); sha1_update(&sha, (BYTE*) &buf_key, sizeof(buf_key)); sha1_update(&sha, (BYTE*) &j, sizeof(int)); sha1_finish(&sha, tmp); for(int x=0; x<SHA1_BYTES; x++, pBufMatIdx++, pBufToRead++ ) { *(pBufMatIdx) = *(pBufToRead) ^ tmp[x]; } } } delete [] pK; if( m_bStop ) return; // IKNP-second step: send the keys for client inputs int nInputSize = nInputEnd - nInputStart + 1; KEY* pKeys = new KEY[nInputSize*2]; YAO_WIRE* wire; KEY* wirekey; CBitVector qj; qj.Create(NUM_EXECS_NAOR_PINKAS); int j=0; // 0-starting index KEY* pKeyIdx = pKeys; for(int i=nInputStart; !m_bStop && i<=nInputEnd; i++,j++) { while( m_nGatesDone < i ) { SleepMiliSec(100); } // compute qj for(int r=0; r<NUM_EXECS_NAOR_PINKAS; r++) { qj.SetBit( r, ppMat[r][j/8] & bitmask[j & 0x7] ); } // compute hash sha1_starts(&sha); sha1_update(&sha, qj.GetArr(), NUM_EXECS_NAOR_PINKAS/8); sha1_update(&sha, (BYTE*)&j, sizeof(int)); sha1_finish(&sha, (BYTE*)&buf_key); // y0 wire = m_pYaoWires+i; wirekey = wire->keys + wire->b; XOR_KEYP3( pKeyIdx, (&buf_key), wirekey ); pKeyIdx++; // compute qj xor s for(int x=0; x<NUM_EXECS_NAOR_PINKAS/8; x++ ) qj.GetArr()[x] ^= m_S.GetByte(x); /* #ifdef _DEBUG cout << "qj xor s = "; for(int z=0; z<NUM_EXECS_NAOR_PINKAS; z++) cout << (int) qj.GetBit(z); cout << endl; #endif */ // y1 sha1_starts(&sha); sha1_update(&sha, qj.GetArr(), NUM_EXECS_NAOR_PINKAS/8); sha1_update(&sha, (BYTE*)&j, sizeof(int)); sha1_finish(&sha, (BYTE*)&buf_key); wirekey = wire->keys + (wire->b^1); XOR_KEYP3( pKeyIdx, (&buf_key), wirekey ); pKeyIdx++; } m_sockOT.Send( pKeys, nInputSize*sizeof(KEY)*2); // clean-up delete [] pBuf2; for(int i=0; i<NUM_EXECS_NAOR_PINKAS; i++) { delete [] ppMat[i]; } delete [] ppMat; delete [] pKeys; cout << "\not thread ended \n" << flush; }

int main() { scanf("%s",inf); int i,flag=0,part1=0,part2=1; for(i=0;i<strlen(inf);i++) { if(inf[i]=='(') { s[++top]='('; } else if(inf[i]=='[') { s[++top]='['; } else if(inf[i]=='{') { s[++top]='{'; } else if(inf[i]==')') { if(s[top]!='(') { flag=1; break; } top--; } else if(inf[i]==']') { if(s[top]!='[') { flag=1; break; } top--; } else if(inf[i]=='}') { if(s[top]!='{') { flag=1; break; } top--; } } if(flag==1) { part1=0;//printf("Incorrect Bracket placements\n"); } else { if(top==-1) { part1=1; } else { part1=0; } } inf[strlen(inf)]=';'; rem();//to remove all brackets for(i=0;inf2[i]!=';';i++) { if(isoperand(i) && isoperand(i+1)) { part2=0; break; } if(inf2[i+1]!=';') { if( isoperand(i) && isoperator(i+1)) { if(inf2[i+2]==';') { part2=0; break; } else if( !isoperand(i+2) ) { part2=0; break; } } } } if( part1 && part2) { printf("Correct\n"); } else { printf("Incorrect:/\n"); } return 0; }

int main() { cerr << "This is NTL version " << NTL_VERSION << "\n"; cerr << "Basic Configuration Options:\n"; #ifdef NTL_STD_CXX cerr << "NTL_STD_CXX\n"; #endif #ifdef NTL_PSTD_NNS cerr << "NTL_PSTD_NNS\n"; #endif #ifdef NTL_PSTD_NHF cerr << "NTL_PSTD_NHF\n"; #endif #ifdef NTL_PSTD_NTN cerr << "NTL_PSTD_NTN\n"; #endif #ifdef NTL_GMP_LIP cerr << "NTL_GMP_LIP\n"; #endif #ifdef NTL_GMP_HACK cerr << "NTL_GMP_HACK\n"; #endif #ifdef NTL_GF2X_LIB cerr << "NTL_GF2X_LIB\n"; #endif #ifdef NTL_LONG_LONG_TYPE cerr << "NTL_LONG_LONG_TYPE: "; cerr << make_string(NTL_LONG_LONG_TYPE) << "\n"; #endif #ifdef NTL_UNSIGNED_LONG_LONG_TYPE cerr << "NTL_UNSIGNED_LONG_LONG_TYPE: "; cerr << make_string(NTL_UNSIGNED_LONG_LONG_TYPE) << "\n"; #endif #ifdef NTL_CXX_ONLY cerr << "NTL_CXX_ONLY\n"; #endif #ifdef NTL_X86_FIX cerr << "NTL_X86_FIX\n"; #endif #ifdef NTL_NO_X86_FIX cerr << "NTL_NO_X86_FIX\n"; #endif #ifdef NTL_NO_INIT_TRANS cerr << "NTL_NO_INIT_TRANS\n"; #endif #ifdef NTL_CLEAN_INT cerr << "NTL_CLEAN_INT\n"; #endif #ifdef NTL_CLEAN_PTR cerr << "NTL_CLEAN_PTR\n"; #endif #ifdef NTL_RANGE_CHECK cerr << "NTL_RANGE_CHECK\n"; #endif cerr << "\n"; cerr << "Resolution of double-word types:\n"; cerr << make_string(NTL_LL_TYPE) << "\n"; cerr << make_string(NTL_ULL_TYPE) << "\n"; cerr << "\n"; cerr << "Performance Options:\n"; #ifdef NTL_LONG_LONG cerr << "NTL_LONG_LONG\n"; #endif #ifdef NTL_AVOID_FLOAT cerr << "NTL_AVOID_FLOAT\n"; #endif #ifdef NTL_SPMM_UL cerr << "NTL_SPMM_UL\n"; #endif #ifdef NTL_SPMM_ULL cerr << "NTL_SPMM_ULL\n"; #endif #ifdef NTL_SPMM_ASM cerr << "NTL_SPMM_ASM\n"; #endif #ifdef NTL_AVOID_BRANCHING cerr << "NTL_AVOID_BRANCHING\n"; #endif #ifdef NTL_TBL_REM cerr << "NTL_TBL_REM\n"; #endif #ifdef NTL_GF2X_ALTCODE cerr << "NTL_GF2X_ALTCODE\n"; #endif #ifdef NTL_GF2X_ALTCODE1 cerr << "NTL_GF2X_ALTCODE1\n"; #endif #ifdef NTL_GF2X_NOINLINE cerr << "NTL_GF2X_NOINLINE\n"; #endif cerr << "\n\n"; if (_ntl_gmp_hack) cerr << "using GMP hack\n\n"; cerr << "running tests..."; long n, k; n = 200; k = 10*NTL_ZZ_NBITS; ZZ p; GenPrime(p, k); ZZ_p::init(p); // initialization ZZ_pX f, g, h, r1, r2, r3; random(g, n); // g = random polynomial of degree < n random(h, n); // h = " " random(f, n); // f = " " // SetCoeff(f, n); // Sets coefficient of X^n to 1 ZZ_p lc; do { random(lc); } while (IsZero(lc)); SetCoeff(f, n, lc); // For doing arithmetic mod f quickly, one must pre-compute // some information. ZZ_pXModulus F; build(F, f); PlainMul(r1, g, h); // this uses classical arithmetic PlainRem(r1, r1, f); MulMod(r2, g, h, F); // this uses the FFT MulMod(r3, g, h, f); // uses FFT, but slower // compare the results... if (r1 != r2) { cerr << "r1 != r2!!\n"; return 1; } else if (r1 != r3) { cerr << "r1 != r3!!\n"; return 1; } // small prime tests...I've made some changes in v5.3 // that should be checked on various platforms, so // we might as well check them here. if (SmallModulusTest(17, 1000)) { cerr << "first SmallModulusTest failed!!\n"; return 1; } if (SmallModulusTest((1L << (NTL_SP_NBITS))-1, 1000)) { cerr << "second SmallModulusTest failed!!\n"; return 1; } // Test gf2x code.... if (GF2X_test()) { cerr << "GF2X test failed!\n"; return 1; } cerr << "OK\n"; ZZ x1, x2, x3, x4; double t; long i; RandomLen(x1, 1024); RandomBnd(x2, x1); RandomBnd(x3, x1); mul(x4, x2, x3); t = GetTime(); for (i = 0; i < 100000; i++) mul(x4, x2, x3); t = GetTime()-t; cerr << "time for 1024-bit mul: " << t*10 << "us"; if (_ntl_gmp_hack) { _ntl_gmp_hack = 0; mul(x4, x2, x3); t = GetTime(); for (i = 0; i < 100000; i++) mul(x4, x2, x3); t = GetTime()-t; cerr << " (" << (t*10) << "us without GMP)"; _ntl_gmp_hack = 1; } cerr << "\n"; rem(x2, x4, x1); t = GetTime(); for (i = 0; i < 100000; i++) rem(x2, x4, x1); t = GetTime()-t; cerr << "time for 2048/1024-bit rem: " << t*10 << "us"; if (_ntl_gmp_hack) { _ntl_gmp_hack = 0; rem(x2, x4, x1); t = GetTime(); for (i = 0; i < 100000; i++) rem(x2, x4, x1); t = GetTime()-t; cerr << " (" << (t*10) << "us without GMP)"; _ntl_gmp_hack = 1; } cerr << "\n"; GenPrime(p, 1024); RandomBnd(x1, p); if (IsZero(x1)) set(x1); InvMod(x2, x1, p); t = GetTime(); for (i = 0; i < 1000; i++) InvMod(x2, x1, p); t = GetTime()-t; cerr << "time for 1024-bit modular inverse: " << t*1000 << "us"; if (_ntl_gmp_hack) { _ntl_gmp_hack = 0; InvMod(x2, x1, p); t = GetTime(); for (i = 0; i < 1000; i++) InvMod(x2, x1, p); t = GetTime()-t; cerr << " (" << (t*1000) << "us without GMP)"; _ntl_gmp_hack = 1; } cerr << "\n"; // test modulus switching n = 1024; k = 1024; RandomLen(p, k); ZZ_p::init(p); ZZ_pInfo->check(); ZZ_pX j1, j2, j3; random(j1, n); random(j2, n); t = GetTime(); for (i = 0; i < 20; i++) mul(j3, j1, j2); t = GetTime()-t; cerr << "time to multiply degree 1023 polynomials\n modulo a 1024-bit number: "; cerr << (t/20) << "s"; if (_ntl_gmp_hack) { _ntl_gmp_hack = 0; ZZ_p::init(p); ZZ_pInfo->check(); t = GetTime(); for (i = 0; i < 20; i++) mul(j3, j1, j2); t = GetTime()-t; cerr << " (" << (t/20) << "s without GMP)"; _ntl_gmp_hack = 1; } cerr << "\n"; GF2X_time(); return 0; }

int main(){ Buffer b = (Buffer) malloc(sizeof(struct buffer)); init(b); int r=0, resposta; while(r!=1){ printStack(b); char input[1024]; printf("\naction (he for help)$ "); fgets(input, sizeof(input), stdin); input[strlen(input)-1] = '\0'; if(strcmp(input,"pu") == 0) { int num, scanres; char tempInput[50], enter; printf("Number to push: "); fgets(tempInput,sizeof(tempInput), stdin); scanres = sscanf(tempInput,"%d%c",&num,&enter); if(!(scanres == 2 && enter == '\n')) printf("Not a number. "); else { resposta = add(b,num); if(resposta) printf("Pushed %d to stack. ",num); else printf("Stack is full. "); } printf("<ENTER>"); getchar(); } else if(strcmp(input,"po") == 0) { int removed, ret; ret = empty(b); if(ret) printf("Stack is empty. <ENTER>"); else { rem(b,&removed); printf("Popped %d. ",removed); printf("<ENTER>"); } getchar(); } else if(strcmp(input,"to") == 0) { int top, res; res = next(b,&top); if (res) printf("Stack top: %d <ENTER>",top); else printf("Stack is empty. <ENTER>"); getchar(); } else if(strcmp(input,"em") == 0) { if(empty(b)) printf("Stack is empty. "); else printf("stack is not empty. "); printf("<ENTER>"); getchar(); } else if(strcmp(input,"he") == 0) { printf("\n# available actions:\n"); printf("# pu - push to stack;\n"); printf("# po - pop the stack;\n"); printf("# to - get stack top;\n"); printf("# em - check if stack is empty.\n"); printf("# he - print this helper.\n"); printf("# ex - exit.\n\n"); printf("<ENTER>"); getchar(); } else if(strcmp(input,"ex") == 0) { r = 1; printf("Leaving... "); printf("<ENTER>"); getchar(); } else { printf("\nNot an action. Type he for available actions. "); printf("<ENTER>"); getchar(); } } printf("Done.\n"); return 1; }

void DDF(vec_pair_GF2X_long& factors, const GF2X& ff, long verbose) { GF2X f = ff; if (IsZero(f)) LogicError("DDF: bad args"); factors.SetLength(0); if (deg(f) == 0) return; if (deg(f) == 1) { AddFactor(factors, f, 1, verbose); return; } long GCDTableSize = GF2X_BlockingFactor; GF2XModulus F; build(F, f); long i, d, limit, old_n; GF2X g, X; vec_GF2X tbl(INIT_SIZE, GCDTableSize); SetX(X); i = 0; SqrMod(g, X, F); d = 1; limit = GCDTableSize; while (2*d <= deg(f)) { old_n = deg(f); add(tbl[i], g, X); i++; if (i == limit) { ProcessTable(f, factors, F, i, tbl, d, verbose); i = 0; } d = d + 1; if (2*d <= deg(f)) { // we need to go further if (deg(f) < old_n) { // f has changed build(F, f); rem(g, g, F); } SqrMod(g, g, F); } } ProcessTable(f, factors, F, i, tbl, d-1, verbose); if (!IsOne(f)) AddFactor(factors, f, deg(f), verbose); }

Entry::~Entry() { rem(); if(data) free(data); }

blargg_err_t Gme_File::load_remaining_( void const* h, long s, Data_Reader& in ) { Remaining_Reader rem( h, s, &in ); return load( rem ); }

long gauss(mat_GF2E& M_in, long w) { long k, l; long i, j; long pos; GF2X t1, t2, t3; GF2X *x, *y; long n = M_in.NumRows(); long m = M_in.NumCols(); if (w < 0 || w > m) Error("gauss: bad args"); const GF2XModulus& p = GF2E::modulus(); vec_GF2XVec M; M.SetLength(n); for (i = 0; i < n; i++) { M[i].SetSize(m, 2*GF2E::WordLength()); for (j = 0; j < m; j++) { M[i][j] = rep(M_in[i][j]); } } l = 0; for (k = 0; k < w && l < n; k++) { pos = -1; for (i = l; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) { pos = i; } } if (pos != -1) { swap(M[pos], M[l]); InvMod(t3, M[l][k], p); for (j = k+1; j < m; j++) { rem(M[l][j], M[l][j], p); } for (i = l+1; i < n; i++) { // M[i] = M[i] + M[l]*M[i,k]*t3 MulMod(t1, M[i][k], t3, p); clear(M[i][k]); x = M[i].elts() + (k+1); y = M[l].elts() + (k+1); for (j = k+1; j < m; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(t2, t2, *x); *x = t2; } } l++; } } for (i = 0; i < n; i++) for (j = 0; j < m; j++) conv(M_in[i][j], M[i][j]); return l; }

void inv(GF2E& d, Mat<GF2E>& X, const Mat<GF2E>& A) { long n = A.NumRows(); if (A.NumCols() != n) LogicError("inv: nonsquare matrix"); if (n == 0) { set(d); X.SetDims(0, 0); return; } const GF2XModulus& G = GF2E::modulus(); GF2X t1, t2; GF2X pivot; GF2X pivot_inv; Vec< GF2XVec > M; // scratch space M.SetLength(n); for (long i = 0; i < n; i++) { M[i].SetSize(n, 2*GF2E::WordLength()); for (long j = 0; j < n; j++) { M[i][j] = rep(A[i][j]); } } GF2X det; det = 1; Vec<long> P; P.SetLength(n); for (long k = 0; k < n; k++) P[k] = k; // records swap operations GF2Context GF2_context; GF2_context.save(); double sz = GF2E_SizeInWords(); bool seq = double(n)*double(n)*sz*sz < PAR_THRESH; bool pivoting = false; for (long k = 0; k < n; k++) { long pos = -1; for (long i = k; i < n; i++) { rem(pivot, M[i][k], G); if (pivot != 0) { InvMod(pivot_inv, pivot, G); pos = i; break; } } if (pos != -1) { if (k != pos) { swap(M[pos], M[k]); negate(det, det); P[k] = pos; pivoting = true; } MulMod(det, det, pivot, G); { // multiply row k by pivot_inv GF2X *y = &M[k][0]; for (long j = 0; j < n; j++) { rem(t2, y[j], G); MulMod(y[j], t2, pivot_inv, G); } y[k] = pivot_inv; } NTL_GEXEC_RANGE(seq, n, first, last) NTL_IMPORT(n) NTL_IMPORT(k) GF2_context.restore(); GF2X *y = &M[k][0]; GF2X t1, t2; for (long i = first; i < last; i++) { if (i == k) continue; // skip row k GF2X *x = &M[i][0]; rem(t1, x[k], G); negate(t1, t1); x[k] = 0; if (t1 == 0) continue; // add t1 * row k to row i for (long j = 0; j < n; j++) { mul(t2, y[j], t1); add(x[j], x[j], t2); } } NTL_GEXEC_RANGE_END } else { clear(d); return; } }

void SFBerlekamp(vec_ZZ_pX& factors, const ZZ_pX& ff, long verbose) { ZZ_pX f = ff; if (!IsOne(LeadCoeff(f))) LogicError("SFBerlekamp: bad args"); if (deg(f) == 0) { factors.SetLength(0); return; } if (deg(f) == 1) { factors.SetLength(1); factors[0] = f; return; } double t; const ZZ& p = ZZ_p::modulus(); long n = deg(f); ZZ_pXModulus F; build(F, f); ZZ_pX g, h; if (verbose) { cerr << "computing X^p..."; t = GetTime(); } PowerXMod(g, p, F); if (verbose) { cerr << (GetTime()-t) << "\n"; } vec_long D; long r; vec_ZZVec M; if (verbose) { cerr << "building matrix..."; t = GetTime(); } BuildMatrix(M, n, g, F, verbose); if (verbose) { cerr << (GetTime()-t) << "\n"; } if (verbose) { cerr << "diagonalizing..."; t = GetTime(); } NullSpace(r, D, M, verbose); if (verbose) { cerr << (GetTime()-t) << "\n"; } if (verbose) cerr << "number of factors = " << r << "\n"; if (r == 1) { factors.SetLength(1); factors[0] = f; return; } if (verbose) { cerr << "factor extraction..."; t = GetTime(); } vec_ZZ_p roots; RandomBasisElt(g, D, M); MinPolyMod(h, g, F, r); if (deg(h) == r) M.kill(); FindRoots(roots, h); FindFactors(factors, f, g, roots); ZZ_pX g1; vec_ZZ_pX S, S1; long i; while (factors.length() < r) { if (verbose) cerr << "+"; RandomBasisElt(g, D, M); S.kill(); for (i = 0; i < factors.length(); i++) { const ZZ_pX& f = factors[i]; if (deg(f) == 1) { append(S, f); continue; } build(F, f); rem(g1, g, F); if (deg(g1) <= 0) { append(S, f); continue; } MinPolyMod(h, g1, F, min(deg(f), r-factors.length()+1)); FindRoots(roots, h); S1.kill(); FindFactors(S1, f, g1, roots); append(S, S1); } swap(factors, S); } if (verbose) { cerr << (GetTime()-t) << "\n"; } if (verbose) { cerr << "degrees:"; long i; for (i = 0; i < factors.length(); i++) cerr << " " << deg(factors[i]); cerr << "\n"; } }

int main(int argc, char *argv[]) { extern int optind; extern char *optarg; enum S command = COMMAND, state; DB *dbp; DBT data, key, keydata; size_t len; int ch, oflags, sflag; char *fname, *infoarg, *p, *t, buf[8 * 1024]; bool unlink_dbfile; infoarg = NULL; fname = NULL; unlink_dbfile = false; oflags = O_CREAT | O_RDWR; sflag = 0; while ((ch = getopt(argc, argv, "f:i:lo:s")) != -1) switch (ch) { case 'f': fname = optarg; break; case 'i': infoarg = optarg; break; case 'l': oflags |= DB_LOCK; break; case 'o': if ((ofd = open(optarg, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0) err(1, "Cannot create `%s'", optarg); break; case 's': sflag = 1; break; case '?': default: usage(); } argc -= optind; argv += optind; if (argc != 2) usage(); /* Set the type. */ type = dbtype(*argv++); /* Open the descriptor file. */ if (strcmp(*argv, "-") && freopen(*argv, "r", stdin) == NULL) err(1, "Cannot reopen `%s'", *argv); /* Set up the db structure as necessary. */ if (infoarg == NULL) infop = NULL; else for (p = strtok(infoarg, ",\t "); p != NULL; p = strtok(0, ",\t ")) if (*p != '\0') infop = setinfo(type, p); /* * Open the DB. Delete any preexisting copy, you almost never * want it around, and it often screws up tests. */ if (fname == NULL) { const char *q = getenv("TMPDIR"); if (q == NULL) q = "/var/tmp"; (void)snprintf(buf, sizeof(buf), "%s/__dbtest", q); fname = buf; (void)unlink(buf); unlink_dbfile = true; } else if (!sflag) (void)unlink(fname); if ((dbp = dbopen(fname, oflags, S_IRUSR | S_IWUSR, type, infop)) == NULL) err(1, "Cannot dbopen `%s'", fname); XXdbp = dbp; if (unlink_dbfile) (void)unlink(fname); state = COMMAND; for (lineno = 1; (p = fgets(buf, sizeof(buf), stdin)) != NULL; ++lineno) { /* Delete the newline, displaying the key/data is easier. */ if (ofd == STDOUT_FILENO && (t = strchr(p, '\n')) != NULL) *t = '\0'; if ((len = strlen(buf)) == 0 || isspace((unsigned char)*p) || *p == '#') continue; /* Convenient gdb break point. */ if (XXlineno == lineno) XXlineno = 1; switch (*p) { case 'c': /* compare */ chkcmd(state); state = KEY; command = COMPARE; break; case 'e': /* echo */ chkcmd(state); /* Don't display the newline, if CR at EOL. */ if (p[len - 2] == '\r') --len; if (write(ofd, p + 1, len - 1) != (ssize_t)len - 1 || write(ofd, "\n", 1) != 1) err(1, "write failed"); break; case 'g': /* get */ chkcmd(state); state = KEY; command = GET; break; case 'p': /* put */ chkcmd(state); state = KEY; command = PUT; break; case 'r': /* remove */ chkcmd(state); if (flags == R_CURSOR) { rem(dbp, &key); state = COMMAND; } else { state = KEY; command = REMOVE; } break; case 'S': /* sync */ chkcmd(state); synk(dbp); state = COMMAND; break; case 's': /* seq */ chkcmd(state); if (flags == R_CURSOR) { state = KEY; command = SEQ; } else seq(dbp, &key); break; case 'f': flags = setflags(p + 1); break; case 'D': /* data file */ chkdata(state); data.data = rfile(p + 1, &data.size); goto ldata; case 'd': /* data */ chkdata(state); data.data = xcopy(p + 1, len - 1); data.size = len - 1; ldata: switch (command) { case COMPARE: compare(&keydata, &data); break; case PUT: put(dbp, &key, &data); break; default: errx(1, "line %zu: command doesn't take data", lineno); } if (type != DB_RECNO) free(key.data); free(data.data); state = COMMAND; break; case 'K': /* key file */ chkkey(state); if (type == DB_RECNO) errx(1, "line %zu: 'K' not available for recno", lineno); key.data = rfile(p + 1, &key.size); goto lkey; case 'k': /* key */ chkkey(state); if (type == DB_RECNO) { static recno_t recno; recno = atoi(p + 1); key.data = &recno; key.size = sizeof(recno); } else { key.data = xcopy(p + 1, len - 1); key.size = len - 1; } lkey: switch (command) { case COMPARE: getdata(dbp, &key, &keydata); state = DATA; break; case GET: get(dbp, &key); if (type != DB_RECNO) free(key.data); state = COMMAND; break; case PUT: state = DATA; break; case REMOVE: rem(dbp, &key); if ((type != DB_RECNO) && (flags != R_CURSOR)) free(key.data); state = COMMAND; break; case SEQ: seq(dbp, &key); if ((type != DB_RECNO) && (flags != R_CURSOR)) free(key.data); state = COMMAND; break; default: errx(1, "line %zu: command doesn't take a key", lineno); } break; case 'o': dump(dbp, p[1] == 'r', 0); break; #ifdef __NetBSD__ case 'O': dump(dbp, p[1] == 'r', 1); break; case 'u': unlinkpg(dbp); break; #endif default: errx(1, "line %zu: %s: unknown command character", lineno, p); } } #ifdef STATISTICS /* * -l must be used (DB_LOCK must be set) for this to be * used, otherwise a page will be locked and it will fail. */ if (type == DB_BTREE && oflags & DB_LOCK) __bt_stat(dbp); #endif if ((*dbp->close)(dbp)) err(1, "db->close failed"); (void)close(ofd); return 0; }

static void NullSpace(long& r, vec_long& D, vec_ZZVec& M, long verbose) { long k, l, n; long i, j; long pos; ZZ t1, t2; ZZ *x, *y; const ZZ& p = ZZ_p::modulus(); n = M.length(); D.SetLength(n); for (j = 0; j < n; j++) D[j] = -1; r = 0; l = 0; for (k = 0; k < n; k++) { if (verbose && k % 10 == 0) cerr << "+"; pos = -1; for (i = l; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) pos = i; } if (pos != -1) { swap(M[pos], M[l]); // make M[l, k] == -1 mod p, and make row l reduced InvMod(t1, M[l][k], p); NegateMod(t1, t1, p); for (j = k+1; j < n; j++) { rem(t2, M[l][j], p); MulMod(M[l][j], t2, t1, p); } for (i = l+1; i < n; i++) { // M[i] = M[i] + M[l]*M[i,k] t1 = M[i][k]; // this is already reduced x = M[i].elts() + (k+1); y = M[l].elts() + (k+1); for (j = k+1; j < n; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(*x, *x, t2); } } D[k] = l; // variable k is defined by row l l++; } else { r++; } } }

int main(int argc, char **argv) { double xoffset; /* offset for x-axis */ double yoffset; /* offset for y-axis */ double text_height; double text_width; int i; int j; int c; int tic_every; int max_tics; int title_color; int num_y_files; int tic_unit; double t, b, l, r; double tt, tb, tl, tr; double prev_x, prev_y[11]; double new_x, new_y[11]; int line; double x_line[3]; double y_line[3]; int err; struct in_file { int num_pnts; /* number of lines in file */ int color; /* color to use for y lines */ float max; /* maximum value in file */ float min; /* minimum value in file */ float value; /* current value read in */ char name[1024]; /* name of file */ char full_name[1024]; /* path/name of file */ FILE *fp; /* pointer to file */ }; struct in_file in[12]; struct GModule *module; float max_y; float min_y; float height, width; float xscale; float yscale; char txt[1024], xlabel[512]; char tic_name[1024]; char *name; char color_name[20]; FILE *fopen(); struct Option *dir_opt, *x_opt, *y_opt; struct Option *y_color_opt; struct Option *title[3]; struct Option *t_color_opt; /* Initialize the GIS calls */ G_gisinit(argv[0]); /* Set description */ module = G_define_module(); G_add_keyword(_("display")); G_add_keyword(_("cartography")); module->description = _("Generates and displays simple line graphs in the active graphics monitor display frame."); x_opt = G_define_option(); x_opt->key = "x_file"; x_opt->description = _("Name of data file for X axis of graph"); x_opt->type = TYPE_STRING; x_opt->required = YES; y_opt = G_define_option(); y_opt->key = "y_file"; y_opt->description = _("Name of data file(s) for Y axis of graph"); y_opt->type = TYPE_STRING; y_opt->required = YES; y_opt->multiple = YES; dir_opt = G_define_option(); dir_opt->key = "directory"; dir_opt->description = _("Path to file location"); dir_opt->type = TYPE_STRING; dir_opt->required = NO; /* Remove answer because create problem with full path */ /* dir_opt->answer = "."; */ y_color_opt = G_define_option(); y_color_opt->key = "y_color"; y_color_opt->description = _("Color for Y data"); y_color_opt->type = TYPE_STRING; y_color_opt->required = NO; y_color_opt->multiple = YES; y_color_opt->gisprompt = "old_color,color,color"; y_color_opt->answers = NULL; t_color_opt = G_define_option(); t_color_opt->key = "title_color"; t_color_opt->description = _("Color for axis, tics, numbers, and title"); t_color_opt->type = TYPE_STRING; t_color_opt->required = NO; t_color_opt->gisprompt = "old_color,color,color"; t_color_opt->answer = DEFAULT_FG_COLOR; title[0] = G_define_option(); title[0]->key = "x_title"; title[0]->description = _("Title for X data"); title[0]->type = TYPE_STRING; title[0]->required = NO; title[0]->answer = ""; title[1] = G_define_option(); title[1]->key = "y_title"; title[1]->description = _("Title for Y data"); title[1]->type = TYPE_STRING; title[1]->required = NO; title[1]->answer = ""; title[2] = G_define_option(); title[2]->key = "title"; title[2]->description = _("Title for Graph"); title[2]->type = TYPE_STRING; title[2]->required = NO; title[2]->answer = ""; if (G_parser(argc, argv)) exit(EXIT_FAILURE); for (i = 0; i < 3; i++) { for (j = 0; j < strlen(title[i]->answer); j++) if (title[i]->answer[j] == '_') title[i]->answer[j] = ' '; } /* build path to X data file and open for reading notice that in[0] will be the X file, and in[1-10] will be the Y file(s) */ if (dir_opt->answer != NULL) { sprintf(in[0].full_name, "%s/%s", dir_opt->answer, x_opt->answer); } else { sprintf(in[0].full_name, "%s", x_opt->answer); } sprintf(in[0].name, "%s", x_opt->answer); if ((in[0].fp = fopen(in[0].full_name, "r")) == NULL) G_fatal_error(_("Unable to open input file <%s>"), in[0].full_name); num_y_files = 0; /* open all Y data files */ for (i = 0, j = 1; (name = y_opt->answers[i]); i++, j++) { if (dir_opt->answer != NULL) { sprintf(in[j].full_name, "%s/%s", dir_opt->answer, name); } else { sprintf(in[j].full_name, "%s", name); } sprintf(in[j].name, "%s", name); if ((in[j].fp = fopen(in[j].full_name, "r")) == NULL) G_fatal_error(_("Unable to open input file <%s>"), in[j].full_name); num_y_files++; if (num_y_files > 10) G_fatal_error(_("Maximum of 10 Y data files exceeded")); } /* set colors */ title_color = D_translate_color(t_color_opt->answer); /* I had an argument with the parser, and couldn't get a neat list of the input colors as I thought I should. I did a quick hack to get my list from the answer var, which gives us the colors input separated by commas. at least we know that they have been checked against the list of possibles */ c = 0; j = 1; if (y_color_opt->answer != NULL) { for (i = 0; i <= (strlen(y_color_opt->answer)); i++) { if ((y_color_opt->answer[i] == ',') || (i == (strlen(y_color_opt->answer)))) { color_name[c] = '\0'; in[j].color = D_translate_color(color_name); j++; c = 0; } else { color_name[c++] = y_color_opt->answer[i]; } } /* this is lame. I could come up with a color or prompt for one or something */ if (j < num_y_files) G_fatal_error(_("Only <%d> colors given for <%d> lines"), j, num_y_files); } else /* no colors given on command line, use default list */ { for (i = 1; i <= num_y_files; i++) { in[i].color = default_y_colors[i]; } } /* get coordinates of current screen window, in pixels */ D_open_driver(); D_setup_unity(0); D_get_src(&t, &b, &l, &r); /* create axis lines, to be drawn later */ height = b - t; width = r - l; x_line[0] = x_line[1] = l + (ORIGIN_X * width); x_line[2] = l + (XAXIS_END * width); y_line[0] = b - (YAXIS_END * height); y_line[1] = y_line[2] = b - (ORIGIN_Y * height); text_height = (b - t) * TEXT_HEIGHT; text_width = (r - l) * TEXT_WIDTH; D_text_size(text_width, text_height); /* read thru each data file in turn, find max and min values for each, count lines, find x min and max, find overall y min and max */ max_y = -99999.9; min_y = 99999.9; for (i = 0; i <= num_y_files; i++) { in[i].min = 99999.9; in[i].max = -99999.9; in[i].value = 0.0; in[i].num_pnts = 0; while ((err = fscanf(in[i].fp, "%f", &in[i].value)) != EOF) { in[i].num_pnts++; in[i].max = MAX(in[i].max, in[i].value); in[i].min = MIN(in[i].min, in[i].value); if (i > 0) { /* if we have a y file */ min_y = MIN(min_y, in[i].value); max_y = MAX(max_y, in[i].value); } } if ((i > 0) && (in[0].num_pnts != in[i].num_pnts)) { if (in[i].num_pnts < in[0].num_pnts) { G_warning(_("Y input file <%s> contains fewer data points than the X input file"), in[i].name); } else { G_warning(_("Y input file <%s> contains more data points than the X input file"), in[i].name); } if (in[i].num_pnts > in[0].num_pnts) G_message(n_("The last point will be ignored", "The last %d points will be ignored", (in[i].num_pnts - in[0].num_pnts)), (in[i].num_pnts - in[0].num_pnts)); } } /* close all files */ for (i = 0; i <= num_y_files; i++) fclose(in[i].fp); /* figure scaling factors and offsets */ xscale = ((double)(x_line[2] - x_line[1]) / (double)(in[0].num_pnts)); yscale = ((double)(y_line[1] - y_line[0]) / (max_y - min_y)); yoffset = (double)(y_line[1]); xoffset = (double)(x_line[1]); /* figure tic_every and tic_units for the x-axis of the bar-chart. tic_every tells how often to place a tic-number. tic_unit tells the unit to use in expressing tic-numbers. */ if (xscale < XTIC_DIST) { max_tics = (x_line[2] - x_line[1]) / XTIC_DIST; i = 1; while (((in[0].max - in[0].min) / tics[i].every) > max_tics) i++; tic_every = tics[i].every; tic_unit = tics[i].unit; strcpy(tic_name, tics[i].name); } else { tic_every = 1; tic_unit = 1; strcpy(tic_name, ""); } /* open all the data files again */ for (i = 0; i <= num_y_files; i++) { if ((in[i].fp = fopen(in[i].full_name, "r")) == NULL) { D_close_driver(); G_fatal_error(_("Unable to open input file <%s>"), in[i].full_name); } } /* loop through number of lines in x data file, then loop thru for each y file, drawing a piece of each line and a legend bar on each iteration evenly divisible, a tic-mark on those evenly divisible by tic_unit, and a tic_mark number on those evenly divisible by tic_every */ /* read the info from the inputs */ for (line = 0; line < in[0].num_pnts; line++) { /* scan in an X value */ err = fscanf(in[0].fp, "%f", &in[0].value); /* didn't find a number or hit EOF before our time */ if ((err != 1) || (err == EOF)) { D_close_driver(); G_fatal_error(_("Problem reading X data file at line %d"), line); } /* for each Y data file, get a value and compute where to draw it */ for (i = 1; i <= num_y_files; i++) { /* check to see that we do indeed have data for this point */ if (line < in[i].num_pnts) { err = fscanf(in[i].fp, "%f", &in[i].value); if ((in[i].num_pnts >= line) && (err != 1)) { D_close_driver(); G_fatal_error(_("Problem reading <%s> data file at line %d"), in[i].name, line); } /* in case the Y file has fewer lines than the X file, we will skip trying to draw when we run out of data */ /* draw increment of each Y file's data */ D_use_color(in[i].color); /* find out position of where Y should be drawn. */ /* if our minimum value of y is not negative, this is easy */ if (min_y >= 0) new_y[i] = (yoffset - yscale * (in[i].value - min_y)); /* if our minimum value of y is negative, then we have two cases: our current value to plot is pos or neg */ else { if (in[i].value < 0) new_y[i] = (yoffset - yscale * (-1 * (min_y - in[i].value))); else new_y[i] = (yoffset - yscale * (in[i].value + (min_y * -1))); } new_x = xoffset + (line * xscale); if (line == 0) { prev_x = xoffset; prev_y[i] = yoffset; } D_line_abs(prev_x, prev_y[i], new_x, new_y[i]); prev_y[i] = new_y[i]; } } prev_x = new_x; /* draw x-axis tic-marks and numbers */ if (rem((long int)in[0].value, tic_every) == 0.0) { /* draw a numbered tic-mark */ D_use_color(title_color); D_begin(); D_move_abs(xoffset + line * xscale, b - ORIGIN_Y * (b - t)); D_cont_rel(0, BIG_TIC * (b - t)); D_end(); D_stroke(); if ((in[0].value >= 1) || (in[0].value <= -1) || (in[0].value == 0)) sprintf(txt, "%.0f", (in[0].value / tic_unit)); else sprintf(txt, "%.2f", (in[0].value)); text_height = (b - t) * TEXT_HEIGHT; text_width = (r - l) * TEXT_WIDTH; D_text_size(text_width, text_height); D_get_text_box(txt, &tt, &tb, &tl, &tr); while ((tr - tl) > XTIC_DIST) { text_width *= 0.75; text_height *= 0.75; D_text_size(text_width, text_height); D_get_text_box(txt, &tt, &tb, &tl, &tr); } D_pos_abs((xoffset + (line * xscale - (tr - tl) / 2)), (b - XNUMS_Y * (b - t))); D_text(txt); } else if (rem(line, tic_unit) == 0.0) { /* draw a tic-mark */ D_use_color(title_color); D_begin(); D_move_abs(xoffset + line * xscale, b - ORIGIN_Y * (b - t)); D_cont_rel(0, SMALL_TIC * (b - t)); D_end(); D_stroke(); } } /* close all input files */ for (i = 0; i <= num_y_files; i++) { fclose(in[i].fp); } /* draw the x-axis label */ if ((strcmp(title[0]->answer, "") == 0) && (strcmp(tic_name, "") == 0)) *xlabel = '\0'; else sprintf(xlabel, "X: %s %s", title[0]->answer, tic_name); text_height = (b - t) * TEXT_HEIGHT; text_width = (r - l) * TEXT_WIDTH * 1.5; D_text_size(text_width, text_height); D_get_text_box(xlabel, &tt, &tb, &tl, &tr); D_pos_abs((l + (r - l) / 2 - (tr - tl) / 2), (b - LABEL_1 * (b - t))); D_use_color(title_color); D_text(xlabel); /* DRAW Y-AXIS TIC-MARKS AND NUMBERS first, figure tic_every and tic_units for the x-axis of the bar-chart. tic_every tells how often to place a tic-number. tic_unit tells the unit to use in expressing tic-numbers. */ if (yscale < YTIC_DIST) { max_tics = (y_line[1] - y_line[0]) / YTIC_DIST; i = 1; while (((max_y - min_y) / tics[i].every) > max_tics) i++; tic_every = tics[i].every; tic_unit = tics[i].unit; strcpy(tic_name, tics[i].name); } else { tic_every = 1; tic_unit = 1; strcpy(tic_name, ""); } /* Y-AXIS LOOP */ for (i = (int)min_y; i <= (int)max_y; i += tic_unit) { if (rem(i, tic_every) == 0.0) { /* draw a tic-mark */ D_begin(); D_move_abs(x_line[0], yoffset - yscale * (i - min_y)); D_cont_rel(-(r - l) * BIG_TIC, 0); D_end(); D_stroke(); /* draw a tic-mark number */ sprintf(txt, "%d", (i / tic_unit)); text_height = (b - t) * TEXT_HEIGHT; text_width = (r - l) * TEXT_WIDTH; D_text_size(text_width, text_height); D_get_text_box(txt, &tt, &tb, &tl, &tr); while ((tt - tb) > YTIC_DIST) { text_width *= 0.75; text_height *= 0.75; D_text_size(text_width, text_height); D_get_text_box(txt, &tt, &tb, &tl, &tr); } D_pos_abs(l + (r - l) * YNUMS_X - (tr - tl) / 2, yoffset - (yscale * (i - min_y) + 0.5 * (tt - tb))); D_text(txt); } else if (rem(i, tic_unit) == 0.0) { /* draw a tic-mark */ D_begin(); D_move_abs(x_line[0], (yoffset - yscale * (i - min_y))); D_cont_rel(-(r - l) * SMALL_TIC, 0); D_end(); D_stroke(); } } /* draw the y-axis label */ if ((strcmp(title[1]->answer, "") == 0) && (strcmp(tic_name, "") == 0)) *xlabel = '\0'; else sprintf(xlabel, "Y: %s %s", title[1]->answer, tic_name); text_height = (b - t) * TEXT_HEIGHT; text_width = (r - l) * TEXT_WIDTH * 1.5; D_text_size(text_width, text_height); D_get_text_box(xlabel, &tt, &tb, &tl, &tr); D_pos_abs(l + (r - l) / 2 - (tr - tl) / 2, b - LABEL_2 * (b - t)); D_use_color(title_color); D_text(xlabel); /* top label */ sprintf(xlabel, "%s", title[2]->answer); text_height = (b - t) * TEXT_HEIGHT; text_width = (r - l) * TEXT_WIDTH * 2.0; D_text_size(text_width, text_height); D_get_text_box(xlabel, &tt, &tb, &tl, &tr); /* D_move_abs((int)(((r-l)/2)-(tr-tl)/2), (int) (t+ (b-t)*.07) ); */ D_pos_abs(l + (r - l) / 2 - (tr - tl) / 2, t + (b - t) * .07); D_use_color(title_color); D_text(xlabel); /* draw x and y axis lines */ D_use_color(title_color); D_polyline_abs(x_line, y_line, 3); D_save_command(G_recreate_command()); D_close_driver(); exit(EXIT_SUCCESS); }

static void MarkProcess(char **inbufp, size_t *inlenp) { char *inbuf, *pt; int inlen; int cx, cy, x2, y2, j, yend; int newcopylen = 0, od; int in_mark; int rep_cnt; struct acluser *md_user; /* char *extrap = 0, extrabuf[100]; */ markdata = (struct markdata *)flayer->l_data; fore = markdata->md_window; md_user = markdata->md_user; if (inbufp == 0) { MarkAbort(); return; } LGotoPos(flayer, markdata->cx, W2D(markdata->cy)); inbuf = *inbufp; inlen = *inlenp; pt = inbuf; in_mark = 1; while (in_mark && (inlen /* || extrap */ )) { unsigned char ch = (unsigned char)*pt++; inlen--; if (flayer->l_mouseevent.start) { int r = LayProcessMouse(flayer, ch); if (r == -1) LayProcessMouseSwitch(flayer, 0); else { if (r) ch = 0222; else continue; } } od = mark_key_tab[(int)ch]; rep_cnt = markdata->rep_cnt; if (isdigit(od) && !markdata->f_cmd.flag) { if (rep_cnt < 1001 && (od != '0' || rep_cnt != 0)) { markdata->rep_cnt = 10 * rep_cnt + od - '0'; continue; /* * Now what is that 1001 here? Well, we have a screen with * 25 * 80 = 2000 characters. Movement is at most across the full * screen. This we do with word by word movement, as character by * character movement never steps over line boundaries. The most words * we can place on the screen are 1000 single letter words. Thus 1001 * is sufficient. Users with bigger screens never write in single letter * words, as they should be more advanced. jw. * Oh, wrong. We still give even the experienced user a factor of ten. */ } } cx = markdata->cx; cy = markdata->cy; if (markdata->f_cmd.flag) { markdata->f_cmd.flag = 0; markdata->rep_cnt = 0; if (isgraph(od)) { markdata->f_cmd.target = od; rep_cnt = (rep_cnt) ? rep_cnt : 1; nextchar(&cx, &cy, markdata->f_cmd.direction, od, rep_cnt); revto(cx, cy); continue; } } processchar: switch (od) { case 'f': /* fall through */ case 'F': /* fall through */ case 't': /* fall through */ case 'T': /* fall through */ /* * Set f_cmd to do a search on the next key stroke. * If we break, rep_cnt will be reset, so we * continue instead. It might be cleaner to * store the rep_count in f_cmd and * break here so later followon code will be * hit. */ markdata->f_cmd.flag = 1; markdata->f_cmd.direction = od; continue; case ';': case ',': if (!markdata->f_cmd.target) break; if (!rep_cnt) rep_cnt = 1; nextchar(&cx, &cy, od == ';' ? markdata->f_cmd.direction : (markdata->f_cmd.direction ^ 0x20), markdata->f_cmd.target, rep_cnt); revto(cx, cy); break; case 'o': case 'x': if (!markdata->second) break; markdata->cx = markdata->x1; markdata->cy = markdata->y1; markdata->x1 = cx; markdata->y1 = cy; revto(markdata->cx, markdata->cy); break; case '\014': /* CTRL-L Redisplay */ Redisplay(0); LGotoPos(flayer, cx, W2D(cy)); break; case 0202: /* M-C-b */ case '\010': /* CTRL-H Backspace */ case 'h': if (rep_cnt == 0) rep_cnt = 1; revto(cx - rep_cnt, cy); break; case 0216: /* M-C-p */ case '\016': /* CTRL-N */ case 'j': if (rep_cnt == 0) rep_cnt = 1; revto(cx, cy + rep_cnt); break; case '+': if (rep_cnt == 0) rep_cnt = 1; j = cy + rep_cnt; if (j > fore->w_histheight + fore->w_height - 1) j = fore->w_histheight + fore->w_height - 1; revto(linestart(j), j); break; case '-': if (rep_cnt == 0) rep_cnt = 1; cy -= rep_cnt; if (cy < 0) cy = 0; revto(linestart(cy), cy); break; case '^': revto(linestart(cy), cy); break; case '\n': revto(markdata->left_mar, cy + 1); break; case 0220: /* M-C-p */ case '\020': /* CTRL-P */ case 'k': if (rep_cnt == 0) rep_cnt = 1; revto(cx, cy - rep_cnt); break; case 0206: /* M-C-f */ case 'l': if (rep_cnt == 0) rep_cnt = 1; revto(cx + rep_cnt, cy); break; case '\001': /* CTRL-A from tcsh/emacs */ case '0': revto(markdata->left_mar, cy); break; case '\004': /* CTRL-D down half screen */ if (rep_cnt == 0) rep_cnt = (fore->w_height + 1) >> 1; revto_line(cx, cy + rep_cnt, W2D(cy)); break; case '$': revto(lineend(cy), cy); break; case '\022': /* CTRL-R emacs style backwards search */ ISearch(-1); in_mark = 0; break; case '\023': /* CTRL-S emacs style search */ ISearch(1); in_mark = 0; break; case '\025': /* CTRL-U up half screen */ if (rep_cnt == 0) rep_cnt = (fore->w_height + 1) >> 1; revto_line(cx, cy - rep_cnt, W2D(cy)); break; case '\007': /* CTRL-G show cursorpos */ if (markdata->left_mar == 0 && markdata->right_mar == fore->w_width - 1) LMsg(0, "Column %d Line %d(+%d)", cx + 1, W2D(cy) + 1, markdata->hist_offset); else LMsg(0, "Column %d(%d..%d) Line %d(+%d)", cx + 1, markdata->left_mar + 1, markdata->right_mar + 1, W2D(cy) + 1, markdata->hist_offset); break; case '\002': /* CTRL-B back one page */ if (rep_cnt == 0) rep_cnt = 1; rep_cnt *= fore->w_height; revto(cx, cy - rep_cnt); break; case '\006': /* CTRL-F forward one page */ if (rep_cnt == 0) rep_cnt = 1; rep_cnt *= fore->w_height; revto(cx, cy + rep_cnt); break; case '\005': /* CTRL-E scroll up */ if (rep_cnt == 0) rep_cnt = 1; MarkScrollUpDisplay(rep_cnt); if (cy < D2W(0)) revto(cx, D2W(0)); else LGotoPos(flayer, cx, W2D(cy)); break; case '\031': /* CTRL-Y scroll down */ if (rep_cnt == 0) rep_cnt = 1; MarkScrollDownDisplay(rep_cnt); if (cy > D2W(fore->w_height - 1)) revto(cx, D2W(fore->w_height - 1)); else LGotoPos(flayer, cx, W2D(cy)); break; case '@': /* it may be useful to have a key that does nothing */ break; case '%': rep_cnt--; /* rep_cnt is a percentage for the history buffer */ if (rep_cnt < 0) rep_cnt = 0; if (rep_cnt > 100) rep_cnt = 100; revto_line(markdata->left_mar, (rep_cnt * (fore->w_histheight + fore->w_height)) / 100, (fore->w_height - 1) / 2); break; case 0201: case 'g': rep_cnt = 1; /* FALLTHROUGH */ case 0205: case 'G': /* rep_cnt is here the WIN line number */ if (rep_cnt == 0) rep_cnt = fore->w_histheight + fore->w_height; revto_line(markdata->left_mar, --rep_cnt, (fore->w_height - 1) / 2); break; case 'H': revto(markdata->left_mar, D2W(0)); break; case 'M': revto(markdata->left_mar, D2W((fore->w_height - 1) / 2)); break; case 'L': revto(markdata->left_mar, D2W(fore->w_height - 1)); break; case '|': revto(--rep_cnt, cy); break; case 'w': if (rep_cnt == 0) rep_cnt = 1; nextword(&cx, &cy, NW_MUSTMOVE, rep_cnt); revto(cx, cy); break; case 'e': case 'E': if (rep_cnt == 0) rep_cnt = 1; nextword(&cx, &cy, NW_ENDOFWORD | NW_MUSTMOVE | (od == 'E' ? NW_BIG : 0), rep_cnt); revto(cx, cy); break; case 'b': case 'B': if (rep_cnt == 0) rep_cnt = 1; nextword(&cx, &cy, NW_BACK | NW_ENDOFWORD | NW_MUSTMOVE | (od == 'B' ? NW_BIG : 0), rep_cnt); revto(cx, cy); break; case 'a': markdata->append_mode = 1 - markdata->append_mode; LMsg(0, (markdata->append_mode) ? ":set append" : ":set noappend"); break; case 'v': case 'V': /* this sets start column to column 9 for VI :set nu users */ if (markdata->left_mar == 8) rep_cnt = 1; else rep_cnt = 9; /* FALLTHROUGH */ case 'c': case 'C': /* set start column (c) and end column (C) */ if (markdata->second) { rem(markdata->x1, markdata->y1, cx, cy, 1, (char *)0, fore->w_height - 1); /* Hack */ markdata->second = 1; /* rem turns off second */ } rep_cnt--; if (rep_cnt < 0) rep_cnt = cx; if (od != 'C') { markdata->left_mar = rep_cnt; if (markdata->left_mar > markdata->right_mar) markdata->left_mar = markdata->right_mar; } else { markdata->right_mar = rep_cnt; if (markdata->left_mar > markdata->right_mar) markdata->right_mar = markdata->left_mar; } if (markdata->second) { markdata->cx = markdata->x1; markdata->cy = markdata->y1; revto(cx, cy); } if (od == 'v' || od == 'V') LMsg(0, (markdata->left_mar != 8) ? ":set nonu" : ":set nu"); break; case 'J': /* how do you join lines in VI ? */ markdata->nonl = (markdata->nonl + 1) % 4; switch (markdata->nonl) { case 0: if (join_with_cr) LMsg(0, "Multiple lines (CR/LF)"); else LMsg(0, "Multiple lines (LF)"); break; case 1: LMsg(0, "Lines joined"); break; case 2: LMsg(0, "Lines joined with blanks"); break; case 3: LMsg(0, "Lines joined with comma"); break; } break; case '/': Search(1); in_mark = 0; break; case '?': Search(-1); in_mark = 0; break; case 'n': Search(0); break; case 'N': markdata->isdir = -markdata->isdir; Search(0); markdata->isdir = -markdata->isdir; break; case 'y': case 'Y': if (markdata->second == 0) { revto(linestart(cy), cy); markdata->second++; cx = markdata->x1 = markdata->cx; cy = markdata->y1 = markdata->cy; } if (--rep_cnt > 0) revto(cx, cy + rep_cnt); revto(lineend(markdata->cy), markdata->cy); if (od == 'y') break; /* FALLTHROUGH */ case 'W': if (od == 'W') { if (rep_cnt == 0) rep_cnt = 1; if (!markdata->second) { nextword(&cx, &cy, NW_BACK | NW_ENDOFWORD, 1); revto(cx, cy); markdata->second++; cx = markdata->x1 = markdata->cx; cy = markdata->y1 = markdata->cy; } nextword(&cx, &cy, NW_ENDOFWORD, rep_cnt); revto(cx, cy); } cx = markdata->cx; cy = markdata->cy; /* FALLTHROUGH */ case 'A': if (od == 'A') markdata->append_mode = 1; /* FALLTHROUGH */ case '>': if (od == '>') markdata->write_buffer = 1; /* FALLTHROUGH */ case ' ': case '\r': if (!markdata->second) { markdata->second++; markdata->x1 = cx; markdata->y1 = cy; revto(cx, cy); LMsg(0, "First mark set - Column %d Line %d", cx + 1, W2D(cy) + 1); break; } else { int append_mode = markdata->append_mode; int write_buffer = markdata->write_buffer; x2 = cx; y2 = cy; newcopylen = rem(markdata->x1, markdata->y1, x2, y2, 2, (char *)0, 0); /* count */ if (md_user->u_plop.buf && !append_mode) UserFreeCopyBuffer(md_user); yend = fore->w_height - 1; if (fore->w_histheight - markdata->hist_offset < fore->w_height) { markdata->second = 0; yend -= MarkScrollUpDisplay(fore->w_histheight - markdata->hist_offset); } if (newcopylen > 0) { /* the +3 below is for : cr + lf + \0 */ if (md_user->u_plop.buf) md_user->u_plop.buf = realloc(md_user->u_plop.buf, (unsigned)(md_user->u_plop.len + newcopylen + 3)); else { md_user->u_plop.len = 0; md_user->u_plop.buf = malloc((unsigned)(newcopylen + 3)); } if (!md_user->u_plop.buf) { MarkAbort(); in_mark = 0; LMsg(0, "Not enough memory... Sorry."); md_user->u_plop.len = 0; md_user->u_plop.buf = 0; break; } if (append_mode) { switch (markdata->nonl) { /* * this code defines, what glues lines together */ case 0: if (join_with_cr) { md_user->u_plop.buf[md_user->u_plop.len] = '\r'; md_user->u_plop.len++; } md_user->u_plop.buf[md_user->u_plop.len] = '\n'; md_user->u_plop.len++; break; case 1: break; case 2: md_user->u_plop.buf[md_user->u_plop.len] = ' '; md_user->u_plop.len++; break; case 3: md_user->u_plop.buf[md_user->u_plop.len] = ','; md_user->u_plop.len++; break; } } md_user->u_plop.len += rem(markdata->x1, markdata->y1, x2, y2, markdata->hist_offset == fore->w_histheight, md_user->u_plop.buf + md_user->u_plop.len, yend); md_user->u_plop.enc = fore->w_encoding; } if (markdata->hist_offset != fore->w_histheight) { LAY_CALL_UP(LRefreshAll(flayer, 0)); } ExitOverlayPage(); WindowChanged(fore, 'P'); if (append_mode) LMsg(0, "Appended %d characters to buffer", newcopylen); else LMsg(0, "Copied %d characters into buffer", md_user->u_plop.len); if (write_buffer) WriteFile(md_user, (char *)0, DUMP_EXCHANGE); in_mark = 0; break; } case 0222: if (flayer->l_mouseevent.start) { int button = flayer->l_mouseevent.buffer[0]; if (button == 'a') { /* Scroll down */ od = 'j'; } else if (button == '`') { /* Scroll up */ od = 'k'; } else if (button == ' ') { /* Left click */ cx = flayer->l_mouseevent.buffer[1]; cy = D2W(flayer->l_mouseevent.buffer[2]); revto(cx, cy); od = ' '; } else od = 0; LayProcessMouseSwitch(flayer, 0); if (od) goto processchar; } else LayProcessMouseSwitch(flayer, 1); break; default: MarkAbort(); LMsg(0, "Copy mode aborted"); in_mark = 0; break; } if (in_mark) /* markdata may be freed */ markdata->rep_cnt = 0; } if (in_mark) { flayer->l_x = markdata->cx; flayer->l_y = W2D(markdata->cy); } *inbufp = pt; *inlenp = inlen; }

int cardEffect(int card, int choice1, int choice2, int choice3, struct gameState *state, int handPos, int *bonus){ int currentPlayer = whoseTurn(state); //uses switch to select card and perform actions switch( card ){ case adventurer: adv(currentPlayer, state); break; case council_room: council(currentPlayer, state, handPos); break; case feast: fea(currentPlayer, state, choice1); break; case gardens: return -1; case mine: min(currentPlayer, state, handPos, choice1, choice2); break; case remodel: rem(currentPlayer, state, handPos, choice1, choice2); break; case smithy: smi(currentPlayer, state, handPos); break; case village: vill(currentPlayer, state, handPos); break; case baron: bar(currentPlayer, state, choice1); break; case great_hall: great(currentPlayer, state, handPos); break; case minion: mini(currentPlayer, state, handPos, choice1, choice2); break; case steward: stew(currentPlayer, state, handPos, choice1, choice2, choice3); break; case tribute: trib(currentPlayer, state); break; case ambassador: ambass(currentPlayer, state, handPos, choice1, choice2); break; case cutpurse: catp(currentPlayer, state, handPos); break; case embargo: embar(currentPlayer, state, handPos, choice1); break; case outpost: outp(currentPlayer, state, handPos); break; case salvager: salv(currentPlayer, state, handPos, choice1); break; case sea_hag: seahag(currentPlayer, state); break; case treasure_map: treasur(currentPlayer, state, handPos); break; } return -1; }

void determinant(zz_pE& d, const mat_zz_pE& M_in) { long k, n; long i, j; long pos; zz_pX t1, t2; zz_pX *x, *y; const zz_pXModulus& p = zz_pE::modulus(); n = M_in.NumRows(); if (M_in.NumCols() != n) LogicError("determinant: nonsquare matrix"); if (n == 0) { set(d); return; } UniqueArray<vec_zz_pX> M_store; M_store.SetLength(n); vec_zz_pX *M = M_store.get(); for (i = 0; i < n; i++) { M[i].SetLength(n); for (j = 0; j < n; j++) { M[i][j].rep.SetMaxLength(2*deg(p)-1); M[i][j] = rep(M_in[i][j]); } } zz_pX det; set(det); for (k = 0; k < n; k++) { pos = -1; for (i = k; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) pos = i; } if (pos != -1) { if (k != pos) { swap(M[pos], M[k]); negate(det, det); } MulMod(det, det, M[k][k], p); // make M[k, k] == -1 mod p, and make row k reduced InvMod(t1, M[k][k], p); negate(t1, t1); for (j = k+1; j < n; j++) { rem(t2, M[k][j], p); MulMod(M[k][j], t2, t1, p); } for (i = k+1; i < n; i++) { // M[i] = M[i] + M[k]*M[i,k] t1 = M[i][k]; // this is already reduced x = M[i].elts() + (k+1); y = M[k].elts() + (k+1); for (j = k+1; j < n; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(*x, *x, t2); } } } else { clear(d); return; } } conv(d, det); }

static void solve_impl(ZZ_p& d, vec_ZZ_p& X, const mat_ZZ_p& A, const vec_ZZ_p& b, bool trans) { long n = A.NumRows(); if (A.NumCols() != n) LogicError("solve: nonsquare matrix"); if (b.length() != n) LogicError("solve: dimension mismatch"); if (n == 0) { set(d); X.SetLength(0); return; } long i, j, k, pos; ZZ t1, t2; ZZ *x, *y; const ZZ& p = ZZ_p::modulus(); vec_ZZVec M; sqr(t1, p); mul(t1, t1, n); M.SetLength(n); for (i = 0; i < n; i++) { M[i].SetSize(n+1, t1.size()); if (trans) for (j = 0; j < n; j++) M[i][j] = rep(A[j][i]); else for (j = 0; j < n; j++) M[i][j] = rep(A[i][j]); M[i][n] = rep(b[i]); } ZZ det; set(det); for (k = 0; k < n; k++) { pos = -1; for (i = k; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) { pos = i; } } if (pos != -1) { if (k != pos) { swap(M[pos], M[k]); NegateMod(det, det, p); } MulMod(det, det, M[k][k], p); // make M[k, k] == -1 mod p, and make row k reduced InvMod(t1, M[k][k], p); NegateMod(t1, t1, p); for (j = k+1; j <= n; j++) { rem(t2, M[k][j], p); MulMod(M[k][j], t2, t1, p); } for (i = k+1; i < n; i++) { // M[i] = M[i] + M[k]*M[i,k] t1 = M[i][k]; // this is already reduced x = M[i].elts() + (k+1); y = M[k].elts() + (k+1); for (j = k+1; j <= n; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(*x, *x, t2); } } } else { clear(d); return; } } X.SetLength(n); for (i = n-1; i >= 0; i--) { clear(t1); for (j = i+1; j < n; j++) { mul(t2, rep(X[j]), M[i][j]); add(t1, t1, t2); } sub(t1, t1, M[i][n]); conv(X[i], t1); } conv(d, det); }

long gauss(mat_zz_pE& M_in, long w) { long k, l; long i, j; long pos; zz_pX t1, t2, t3; zz_pX *x, *y; long n = M_in.NumRows(); long m = M_in.NumCols(); if (w < 0 || w > m) LogicError("gauss: bad args"); const zz_pXModulus& p = zz_pE::modulus(); UniqueArray<vec_zz_pX> M_store; M_store.SetLength(n); vec_zz_pX *M = M_store.get(); for (i = 0; i < n; i++) { M[i].SetLength(m); for (j = 0; j < m; j++) { M[i][j].rep.SetMaxLength(2*deg(p)-1); M[i][j] = rep(M_in[i][j]); } } l = 0; for (k = 0; k < w && l < n; k++) { pos = -1; for (i = l; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) { pos = i; } } if (pos != -1) { swap(M[pos], M[l]); InvMod(t3, M[l][k], p); negate(t3, t3); for (j = k+1; j < m; j++) { rem(M[l][j], M[l][j], p); } for (i = l+1; i < n; i++) { // M[i] = M[i] + M[l]*M[i,k]*t3 MulMod(t1, M[i][k], t3, p); clear(M[i][k]); x = M[i].elts() + (k+1); y = M[l].elts() + (k+1); for (j = k+1; j < m; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(t2, t2, *x); *x = t2; } } l++; } } for (i = 0; i < n; i++) for (j = 0; j < m; j++) conv(M_in[i][j], M[i][j]); return l; }

void determinant(GF2E& d, const mat_GF2E& M_in) { long k, n; long i, j; long pos; GF2X t1, t2; GF2X *x, *y; const GF2XModulus& p = GF2E::modulus(); n = M_in.NumRows(); if (M_in.NumCols() != n) Error("determinant: nonsquare matrix"); if (n == 0) { set(d); return; } vec_GF2XVec M; M.SetLength(n); for (i = 0; i < n; i++) { M[i].SetSize(n, 2*GF2E::WordLength()); for (j = 0; j < n; j++) M[i][j] = rep(M_in[i][j]); } GF2X det; set(det); for (k = 0; k < n; k++) { pos = -1; for (i = k; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) pos = i; } if (pos != -1) { if (k != pos) { swap(M[pos], M[k]); } MulMod(det, det, M[k][k], p); // make M[k, k] == -1 mod p, and make row k reduced InvMod(t1, M[k][k], p); for (j = k+1; j < n; j++) { rem(t2, M[k][j], p); MulMod(M[k][j], t2, t1, p); } for (i = k+1; i < n; i++) { // M[i] = M[i] + M[k]*M[i,k] t1 = M[i][k]; // this is already reduced x = M[i].elts() + (k+1); y = M[k].elts() + (k+1); for (j = k+1; j < n; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(*x, *x, t2); } } } else { clear(d); return; } } conv(d, det); }

void UnitTestBulkData::testChangeParts_loop( ParallelMachine pm ) { enum { nPerProc = 10 }; const unsigned p_rank = parallel_machine_rank( pm ); const unsigned p_size = parallel_machine_size( pm ); const unsigned nLocalNode = nPerProc + ( 1 < p_size ? 1 : 0 ); const unsigned nLocalEdge = nPerProc ; UnitTestRingMeshFixture ring_mesh( pm , nPerProc , true /* generate parts */ ); ring_mesh.m_meta_data.commit(); ring_mesh.generate_mesh( false /* no aura */ ); Part & part_owns = ring_mesh.m_meta_data.locally_owned_part(); Part & part_univ = ring_mesh.m_meta_data.universal_part(); Selector select_owned( ring_mesh.m_meta_data.locally_owned_part() ); Selector select_used = select_owned | ring_mesh.m_meta_data.globally_shared_part(); Selector select_all( ring_mesh.m_meta_data.universal_part() ); std::vector<unsigned> local_count ; for ( unsigned i = 0 ; i < nLocalEdge ; ++i ) { const unsigned n = i + nPerProc * p_rank ; Entity * const edge = ring_mesh.m_bulk_data.get_entity( 1 , ring_mesh.m_edge_ids[n] ); STKUNIT_ASSERT( edge != NULL ); STKUNIT_ASSERT( edge->bucket().member( part_univ ) ); STKUNIT_ASSERT( edge->bucket().member( part_owns ) ); STKUNIT_ASSERT( edge->bucket().member( * ring_mesh.m_edge_parts[ n % ring_mesh.m_edge_parts.size() ] ) ); } for ( unsigned i = 0 ; i < nLocalNode ; ++i ) { const unsigned n = ( i + nPerProc * p_rank ) % ring_mesh.m_node_ids.size(); const unsigned e0 = n ; const unsigned e1 = ( n + ring_mesh.m_edge_ids.size() - 1 ) % ring_mesh.m_edge_ids.size(); const unsigned ns = ring_mesh.m_edge_parts.size(); const unsigned n0 = e0 % ns ; const unsigned n1 = e1 % ns ; Part * const epart_0 = ring_mesh.m_edge_parts[ n0 < n1 ? n0 : n1 ]; Part * const epart_1 = ring_mesh.m_edge_parts[ n0 < n1 ? n1 : n0 ]; Entity * const node = ring_mesh.m_bulk_data.get_entity( 0 , ring_mesh.m_node_ids[n] ); STKUNIT_ASSERT( node != NULL ); if ( node->owner_rank() == p_rank ) { STKUNIT_ASSERT( node->bucket().member( part_univ ) ); STKUNIT_ASSERT( node->bucket().member( part_owns ) ); STKUNIT_ASSERT( node->bucket().member( *epart_0 ) ); STKUNIT_ASSERT( node->bucket().member( *epart_1 ) ); } else { STKUNIT_ASSERT( node->bucket().member( part_univ ) ); STKUNIT_ASSERT( ! node->bucket().member( part_owns ) ); STKUNIT_ASSERT( node->bucket().member( * epart_0 ) ); STKUNIT_ASSERT( node->bucket().member( * epart_1 ) ); } } ring_mesh.m_bulk_data.modification_begin(); if ( 0 == p_rank ) { for ( unsigned i = 0 ; i < nLocalEdge ; ++i ) { const unsigned n = i + nPerProc * p_rank ; PartVector add(1); add[0] = & ring_mesh.m_edge_part_extra ; PartVector rem(1); rem[0] = ring_mesh.m_edge_parts[ n % ring_mesh.m_edge_parts.size() ]; Entity * const edge = ring_mesh.m_bulk_data.get_entity( 1 , ring_mesh.m_edge_ids[n] ); ring_mesh.m_bulk_data.change_entity_parts( *edge , add , rem ); STKUNIT_ASSERT( edge->bucket().member( part_univ ) ); STKUNIT_ASSERT( edge->bucket().member( part_owns ) ); STKUNIT_ASSERT( edge->bucket().member(ring_mesh.m_edge_part_extra ) ); } } ring_mesh.m_bulk_data.modification_end(); for ( unsigned i = 0 ; i < nLocalNode ; ++i ) { const unsigned n = ( i + nPerProc * p_rank ) % ring_mesh.m_node_ids.size(); const unsigned e0 = n ; const unsigned e1 = ( n + ring_mesh.m_edge_ids.size() - 1 ) % ring_mesh.m_edge_ids.size(); const unsigned ns = ring_mesh.m_edge_parts.size(); const unsigned n0 = e0 % ns ; const unsigned n1 = e1 % ns ; Part * ep_0 = e0 < nLocalEdge ? & ring_mesh.m_edge_part_extra : ring_mesh.m_edge_parts[n0] ; Part * ep_1 = e1 < nLocalEdge ? & ring_mesh.m_edge_part_extra : ring_mesh.m_edge_parts[n1] ; Part * epart_0 = ep_0->mesh_meta_data_ordinal() < ep_1->mesh_meta_data_ordinal() ? ep_0 : ep_1 ; Part * epart_1 = ep_0->mesh_meta_data_ordinal() < ep_1->mesh_meta_data_ordinal() ? ep_1 : ep_0 ; Entity * const node = ring_mesh.m_bulk_data.get_entity( 0 , ring_mesh.m_node_ids[n] ); STKUNIT_ASSERT( node != NULL ); if ( node->owner_rank() == p_rank ) { STKUNIT_ASSERT( node->bucket().member( part_owns ) ); } else { STKUNIT_ASSERT( ! node->bucket().member( part_owns ) ); } STKUNIT_ASSERT( node->bucket().member( part_univ ) ); STKUNIT_ASSERT( node->bucket().member( *epart_0 ) ); STKUNIT_ASSERT( node->bucket().member( *epart_1 ) ); } }

void inv(GF2E& d, mat_GF2E& X, const mat_GF2E& A) { long n = A.NumRows(); if (A.NumCols() != n) Error("inv: nonsquare matrix"); if (n == 0) { set(d); X.SetDims(0, 0); return; } long i, j, k, pos; GF2X t1, t2; GF2X *x, *y; const GF2XModulus& p = GF2E::modulus(); vec_GF2XVec M; M.SetLength(n); for (i = 0; i < n; i++) { M[i].SetSize(2*n, 2*GF2E::WordLength()); for (j = 0; j < n; j++) { M[i][j] = rep(A[i][j]); clear(M[i][n+j]); } set(M[i][n+i]); } GF2X det; set(det); for (k = 0; k < n; k++) { pos = -1; for (i = k; i < n; i++) { rem(t1, M[i][k], p); M[i][k] = t1; if (pos == -1 && !IsZero(t1)) { pos = i; } } if (pos != -1) { if (k != pos) { swap(M[pos], M[k]); } MulMod(det, det, M[k][k], p); // make M[k, k] == -1 mod p, and make row k reduced InvMod(t1, M[k][k], p); for (j = k+1; j < 2*n; j++) { rem(t2, M[k][j], p); MulMod(M[k][j], t2, t1, p); } for (i = k+1; i < n; i++) { // M[i] = M[i] + M[k]*M[i,k] t1 = M[i][k]; // this is already reduced x = M[i].elts() + (k+1); y = M[k].elts() + (k+1); for (j = k+1; j < 2*n; j++, x++, y++) { // *x = *x + (*y)*t1 mul(t2, *y, t1); add(*x, *x, t2); } } } else { clear(d); return; } } X.SetDims(n, n); for (k = 0; k < n; k++) { for (i = n-1; i >= 0; i--) { clear(t1); for (j = i+1; j < n; j++) { mul(t2, rep(X[j][k]), M[i][j]); add(t1, t1, t2); } add(t1, t1, M[i][n+k]); conv(X[i][k], t1); } } conv(d, det); }

char *alloc_chars(buffer * const b, const int64_t len) { if (!len || !b) return NULL; assert_buffer(b); block_signals(); char_pool *cp; for(cp = (char_pool *)b->char_pool_list.head; cp->cp_node.next; cp = (char_pool *)cp->cp_node.next) { assert_char_pool(cp); /* We try to allocate before the first used character, or after the last used character. If we succeed with a pool which is not the head of the list, we move it to the head in order to optimize the next try. */ if (cp->first_used >= len) { cp->first_used -= len; b->free_chars -= len; if (cp != (char_pool *)b->char_pool_list.head) { rem(&cp->cp_node); add_head(&b->char_pool_list, &cp->cp_node); } release_signals(); return cp->pool + cp->first_used; } else if (cp->size - cp->last_used > len) { cp->last_used += len; b->free_chars -= len; if (cp != (char_pool *)b->char_pool_list.head) { rem(&cp->cp_node); add_head(&b->char_pool_list, &cp->cp_node); } release_signals(); return cp->pool + cp->last_used - len + 1; } } /* If no free space has been found, we allocate a new pool which is guaranteed to contain at least len characters. The pool is added to the head of the list. */ if (cp = alloc_char_pool(len)) { add_head(&b->char_pool_list, &cp->cp_node); cp->last_used = len - 1; b->allocated_chars += cp->size; b->free_chars += cp->size - len; release_signals(); return cp->pool; } release_signals(); return NULL; }

double LCArmResp::SigO1Freq(int em, int rec, double trec) { /*! First order approximation in relative frequency : computation of the following formula : * \f[ * { \delta \nu \over \nu_0 } (t) = { -1 \over 2(1+\hat{k}.\hat{n}(t))} * \left[ H \left( t+{\hat{k}.\vec{r}_{rec}(t) \over c} \right) - H \left( t+{\hat{k}.\vec{r}_{em}(t) \over c} - {L \over c} \right) \right] * \f] * with \f$ \hat{k} \f$ the propagation direction of the gravitational wave, * \f$ \hat{n}(t) \f$ the direction of the arm, * \f$ \vec{r}_{em}(t) \f$ the position of the emitter, * \f$ \vec{r}_{rec}(t) \f$ the position of the receiver, * \f$ L \f$ the arm length and * \f[ H(t) = h_{B+} (t) \xi_{+} (\hat{\theta},\hat{\phi},\hat{n}(t)) + h_{B\times} (t) \xi_{\times} (\hat{\theta},\hat{\phi},\hat{n}(t)) \f] * with \f[ \left\{ \begin{array}{lll} * \xi_{+}(\vec{u}, \vec{v}, \vec{n}) & = & {\left(\vec{u}. \vec{n} \right)}^2 - {\left(\vec{v}. \vec{n} \right)}^2 \\ * \xi_{\times}(\vec{u}, \vec{v}, \vec{n}) & = & 2 \left(\vec{u}. \vec{n} \right) \left(\vec{v}. \vec{n} \right) \end{array} \right. * \f] */ //! **** Compute quantities associated to the detector LCVector rrec(MT), rem(MT), vArm(MT), n(MT); double tem, tr, te; double hpr, hcr, hpe, hce; //! ** Time at emission : \f$ t_{em} = t_{rec} - L/c \f$ tem = trec + Orb->Arm(em, rec, trec); //! ** Position of receiver at reception time rrec = Orb->Pos(rec, trec)/LC::c_SI; //! ** Position of emitter at reception time (is it OK ?) rem = Orb->Pos(em, trec)/LC::c_SI; //! ** Unit vector of the arm vArm = rrec - rem; n = vArm.unit(); //! **** Loop on gravitaional waves double un, vn, kn; double xipo2, xico2, krrec, krem; double sig(0.); for(int iGW=0; iGW<NGWs; iGW++){ //! *** The tree scalar products between the frame and the arm unit vector : \f$ \hat{u}.\hat{n} \f$ , \f$ \hat{v}.\hat{n} \f$ and \f$ \hat{k}.\hat{n} \f$ un = (*u[iGW])*n; vn = (*v[iGW])*n; kn = (*k[iGW])*n; //! *** Compute \f[ { \xi_{+} \over 2} (t_r) = { {\left(\vec{u}. \vec{n}(t_r) \right)}^2 - {\left(\vec{v}. \vec{n}(t_r) \right)}^2 \over 2 } \f] xipo2 = 0.5*(un*un-vn*vn); //! *** Compute \f[ {\xi_{\times} \over 2} (t_r) = \left(\vec{u}. \vec{n}(t_r) \right) \left(\vec{v}. \vec{n}(t_r) \right) \f] xico2 = un*vn; //! *** Scalar product between the direction of propagation and the spacecraft positions \f$ \hat{k}.\vec{r}_{rec} \f$ and \f$ \hat{k}.\vec{r}_{rec} \f$ //! for computing the time \f$ t_r, t_e \f$ when the gravitational wave act on each spacecraft krrec = (*k[iGW])*rrec; krem = (*k[iGW])*rem; tr = trec + krrec; te = tem + krem; //! *** Compute the 2 components of the gravitational wave strain at time when it act on each spacecraft GWs[iGW]->hBpc(tr, hpr, hcr); GWs[iGW]->hBpc(te, hpe, hce); /* if(((tr>1.8e6)&&(tr<1.9e6))||((tr>0.8e6)&&(tr<0.9e6))||((tr>0.2e6)&&(tr<0.3e6))){ MT->o->precision(12); Cout << tr << " " << hpr << " " << hcr << " " << te << " " << hpe << " " << hce << Endl; } */ /*! *** Compute the signal which is : * \f[ s^{GW} = { ( h_{B+}(t_e) - h_{B+}(t_r) ) {\xi_{+} \over 2} (t_r) + ( h_{B\times}(t_e) - h_{B\times}(t_r) ) {\xi_{\times} \over 2} (t_r) \over 1 + \hat{k}.\hat{n} } * \f] * NB : We consider \f$ \xi_{+,\times} (t_e) \sim \xi_{+,\times} (t_r) \f$ which corresponds to \f$ \hat{n}(t_e) \sim \hat{n} (t_r) \f$ */ sig += ( (hpe-hpr) * xipo2 + (hce-hcr) * xico2 ) / (1. + kn) ; //if((rec==1)&&(em==2)) // DEBUGfCheck << trec << " " << tem << " " << un << " " << vn << " " << kn << " " << xipo2 << " " << xico2 << " " << krrec << " " << krem << " " << tr << " " << te << " " << hpr << " " << hcr << " " << hpe << " " << hce << " " << sig << Endl; } #ifdef _DEBUG_ARMRESP_ (*DEBUGfCheck) << trec << " " << sig << " " << em << " " << rec << Endl; #endif return(sig); }