/** * Sub function to Add a dictionary entry line to the word dictionary. * * @param buf [i/o] buffer to hold the input string, will be modified in this function * @param vnum_p [in] current number of words in @a winfo * @param linenum [in] current line number of the input * @param winfo [out] pointer to word dictionary to append the data. * @param hmminfo [in] HTK %HMM definition data. if NULL, phonemes are ignored. * @param do_conv [in] TRUE if performing triphone conversion * @param ok_flag [out] will be set to FALSE if an error occured for this input. * @param headphone [in] word head silence model name * @param tailphone [in] word tail silence model name * @param contextphone [in] silence context name to be used at head and tail * * @return FALSE if buf == "DICEND", else TRUE will be returned. */ boolean voca_load_wordlist_line(char *buf, WORD_ID *vnum_p, int linenum, WORD_INFO *winfo, HTK_HMM_INFO *hmminfo, boolean do_conv, boolean *ok_flag, char *headphone, char *tailphone, char *contextphone) { char *ptmp, *lp = NULL, *p; static char cbuf[MAX_HMMNAME_LEN]; static HMM_Logical **tmpwseq = NULL; static int tmpmaxlen; int len; HMM_Logical *tmplg; boolean pok, first; int vnum; vnum = *vnum_p; if (strmatch(buf, "DICEND")) return FALSE; /* allocate temporal work area for the first call */ if (tmpwseq == NULL) { tmpmaxlen = PHONEMELEN_STEP; tmpwseq = (HMM_Logical **)mymalloc(sizeof(HMM_Logical *) * tmpmaxlen); } /* backup whole line for debug output */ strcpy(bufbak, buf); /* Output string */ if ((ptmp = mystrtok_quote(buf, " \t\n")) == NULL) { jlog("Error: voca_load_wordlist: line %d: corrupted data:\n> %s\n", linenum, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } winfo->wname[vnum] = strcpy((char *)mybmalloc2(strlen(ptmp)+1, &(winfo->mroot)), ptmp); /* reset transparent flag */ winfo->is_transparent[vnum] = FALSE; /* just move pointer to next token */ if ((ptmp = mystrtok_movetonext(NULL, " \t\n")) == NULL) { jlog("Error: voca_load_wordlist: line %d: corrupted data:\n> %s\n", linenum, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } #ifdef CLASS_NGRAM winfo->cprob[vnum] = 0.0; /* prob = 1.0, logprob = 0.0 */ #endif if (ptmp[0] == '@') { /* class N-gram prob */ #ifdef CLASS_NGRAM /* word probability within the class (for class N-gram) */ /* format: classname @classprob wordname [output] phoneseq */ /* classname equals to wname, and wordname will be omitted */ /* format: @%f (log scale) */ /* if "@" not found or "@0", it means class == word */ if ((ptmp = mystrtok(NULL, " \t\n")) == NULL) { jlog("Error: voca_load_wordlist: line %d: corrupted data:\n> %s\n", linenum, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } if (ptmp[1] == '\0') { /* space between '@' and figures */ jlog("Error: voca_load_wordlist: line %d: value after '@' missing, maybe wrong space?\n> %s\n", linenum, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } winfo->cprob[vnum] = atof(&(ptmp[1])); if (winfo->cprob[vnum] != 0.0) winfo->cwnum++; /* read next word entry (just skip them) */ if ((ptmp = mystrtok(NULL, " \t\n")) == NULL) { jlog("Error: voca_load_wordlist: line %d: corrupted data:\n> %s\n", linenum,bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } /* move to the next word entry */ if ((ptmp = mystrtok_movetonext(NULL, " \t\n")) == NULL) { jlog("Error: voca_load_wordlist: line %d: corrupted data:\n> %s\n", linenum, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } #else /* ~CLASS_NGRAM */ jlog("Error: voca_load_wordlist: line %d: cannot handle in-class word probability\n> %s\n", linenum, ptmp, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; #endif /* CLASS_NGRAM */ } /* OutputString */ switch(ptmp[0]) { case '[': /* ignore transparency */ ptmp = mystrtok_quotation(NULL, " \t\n", '[', ']', 0); break; case '{': /* ignore transparency */ ptmp = mystrtok_quotation(NULL, " \t\n", '{', '}', 0); break; default: /* ALLOW no entry for output */ /* same as wname is used */ ptmp = winfo->wname[vnum]; } if (ptmp == NULL) { jlog("Error: voca_load_htkdict: line %d: corrupted data:\n> %s\n", linenum, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } winfo->woutput[vnum] = strcpy((char *)mybmalloc2(strlen(ptmp)+1, &(winfo->mroot)), ptmp); /* phoneme sequence */ if (hmminfo == NULL) { /* don't read */ winfo->wseq[vnum] = NULL; winfo->wlen[vnum] = 0; } else { len = 0; first = TRUE; pok = TRUE; for (;;) { if (do_conv) { if (first) { /* init phone cycler */ cycle_triphone(NULL); /* insert head phone at beginning of word */ if (contextphone) { if (strlen(contextphone) >= MAX_HMMNAME_LEN) { jlog("Error: voca_load_htkdict: line %d: too long phone name: %s\n", linenum, contextphone); winfo->errnum++; *ok_flag = FALSE; return TRUE; } cycle_triphone(contextphone); } else { cycle_triphone("NULL_C"); } if ((lp = mystrtok(NULL, " \t\n")) == NULL) { jlog("Error: voca_load_wordlist: line %d: word %s has no phoneme:\n> %s\n", linenum, winfo->wname[vnum], bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } if (strlen(lp) >= MAX_HMMNAME_LEN) { jlog("Error: voca_load_htkdict: line %d: too long phone name: %s\n", linenum, lp); winfo->errnum++; *ok_flag = FALSE; return TRUE; } p = cycle_triphone(lp); first = FALSE; } else { /* do_conv, not first */ if (lp != NULL) { /* some token processed at last loop */ lp = mystrtok(NULL, " \t\n"); if (lp != NULL) { /* token exist */ if (strlen(lp) >= MAX_HMMNAME_LEN) { jlog("Error: voca_load_htkdict: line %d: too long phone name: %s\n", linenum, lp); winfo->errnum++; *ok_flag = FALSE; return TRUE; } p = cycle_triphone(lp); } else { /* no more token, insert tail phone at end of word */ if (contextphone) { if (strlen(contextphone) >= MAX_HMMNAME_LEN) { jlog("Error: voca_load_htkdict: line %d: too long phone name: %s\n", linenum, contextphone); winfo->errnum++; *ok_flag = FALSE; return TRUE; } p = cycle_triphone(contextphone); } else { p = cycle_triphone("NULL_C"); } } } else { /* no more token at last input */ /* flush tone cycler */ p = cycle_triphone_flush(); } } } else { /* not do_conv */ if (first) { p = lp = headphone; first = FALSE; } else { if (lp != NULL) { /* some token processed at last loop */ p = lp = mystrtok(NULL, " \t\n"); /* if no more token, use tailphone */ if (lp == NULL) p = tailphone; } else { /* no more token at last input, exit loop */ p = NULL; } } } if (p == NULL) break; /* for headphone and tailphone, their context should not be handled */ /* and when they appear as context they should be replaced by contextphone */ if (do_conv) { center_name(p, cbuf); if (contextphone) { if (strmatch(cbuf, contextphone)) { if (len == 0) { p = headphone; } else if (lp == NULL) { p = tailphone; } } } else { if (strmatch(cbuf, "NULL_C")) { if (len == 0) { p = headphone; } else if (lp == NULL) { p = tailphone; } } else { if (strnmatch(p, "NULL_C", 6)) { if (strnmatch(&(p[strlen(p)-6]), "NULL_C", 6)) { p = cbuf; } else { p = rightcenter_name(p, cbuf); } } else if (strnmatch(&(p[strlen(p)-6]), "NULL_C", 6)) { p = leftcenter_name(p, cbuf); } } } } //printf("[[%s]]\n", p); /* both defined/pseudo phone is allowed */ tmplg = htk_hmmdata_lookup_logical(hmminfo, p); if (tmplg == NULL) { /* not found */ if (do_conv) { /* logical phone was not found */ jlog("Error: voca_load_wordlist: line %d: logical phone \"%s\" not found\n", linenum, p); snprintf(cbuf,MAX_HMMNAME_LEN,"%s", p); } else { jlog("Error: voca_load_wordlist: line %d: phone \"%s\" not found\n", linenum, p); snprintf(cbuf, MAX_HMMNAME_LEN, "%s", p); } add_to_error(winfo, cbuf); pok = FALSE; } else { /* found */ if (len >= tmpmaxlen) { /* expand wseq area by PHONEMELEN_STEP */ tmpmaxlen += PHONEMELEN_STEP; tmpwseq = (HMM_Logical **)myrealloc(tmpwseq, sizeof(HMM_Logical *) * tmpmaxlen); } /* store to temporal buffer */ tmpwseq[len] = tmplg; } len++; } if (!pok) { /* error in phoneme */ jlog("Error: voca_load_wordlist: the line content was: %s\n", bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } if (len == 0) { jlog("Error: voca_load_wordlist: line %d: no phone specified:\n> %s\n", linenum, bufbak); winfo->errnum++; *ok_flag = FALSE; return TRUE; } /* store to winfo */ winfo->wseq[vnum] = (HMM_Logical **)mybmalloc2(sizeof(HMM_Logical *) * len, &(winfo->mroot)); memcpy(winfo->wseq[vnum], tmpwseq, sizeof(HMM_Logical *) * len); winfo->wlen[vnum] = len; winfo->wton[vnum] = 0; } vnum++; *vnum_p = vnum; return(TRUE); }
/********************************************************************** * * void balance_loop1 * * This function does load-balancing on the search for starting * points. It divides the dataset by the number of processors at the * character level. The work assigned to each processor is stored in a * global struct. * * IN: SAMPLE **samples the dataset * int n_samples size of the dataset * OUT: SEQ_PARAMS *start_n_end (global) start and end points for this node * * This function is called in 'init.c'. **********************************************************************/ void balance_loop1(SAMPLE **samples, int n_samples) { int n_residues; float residues_per_node, target; int iseq, inode, seq_start, seq_end; /* Allocate storage for the sequence parameters. */ start_n_end = (SEQ_PARAMS *)mymalloc(sizeof(SEQ_PARAMS)); /* First count how many residues we have. */ for (iseq = 0, n_residues = 0; iseq < n_samples; iseq++) n_residues += samples[iseq]->length; /* Calculate the number of residues per node. */ residues_per_node = MAX(1, n_residues / mpNodes()); /* fprintf(stderr, "n_residues=%d residues_per_node=%g\n", n_residues, residues_per_node); */ /* Set the starting points for node 0. */ if (mpMyID() == 0) { start_n_end->start_seq = 0; start_n_end->start_off = 0; } /* Calculate per-node starting and ending points. */ for (iseq = 0, seq_start = 0, seq_end = samples[0]->length - 1, inode = 0, target = residues_per_node; (target < n_residues) || (iseq < n_samples); /* Incrementing is done in the loop */) { /* See whether we've moved past the target. */ if (seq_end >= target) { if (mpMyID() == inode) { start_n_end->end_seq = iseq; start_n_end->end_off = (int)target - seq_start - 1; } if (mpMyID() == inode + 1) { start_n_end->start_seq = iseq; start_n_end->start_off = (int)target - seq_start; } /* fprintf(stderr, "end %d %d\nnode %d start %d %d ", iseq, (int)target-seq_start-1, inode+1, iseq, (int)target-seq_start); */ /* Move to a new node. */ inode++; /* Calculate the target for this node. */ target = residues_per_node * (inode+1); } else { /* Move to a new sequence. */ if (++iseq < n_samples) { /* Calculate the starting and ending points of this sequence. */ seq_start = seq_end; seq_end += samples[iseq]->length; /* 1 more than the index. */ } } } /* Set the ending points for the last node. */ if (mpMyID() == mpNodes() - 1) { start_n_end->end_seq = n_samples - 1; start_n_end->end_off = samples[n_samples - 1]->length - 1; } /* Search for (and correct) fencepost problems. */ if (start_n_end->start_off >= samples[start_n_end->start_seq]->length) { start_n_end->start_seq++; start_n_end->start_off = 0; } else if (start_n_end->start_off <= -1) { start_n_end->start_seq--; start_n_end->start_off = samples[start_n_end->start_seq]->length - 1; } if (start_n_end->end_off >= samples[start_n_end->end_seq]->length) { start_n_end->end_seq++; start_n_end->end_off = 0; } else if (start_n_end->end_off <= -1) { start_n_end->end_seq--; start_n_end->end_off = samples[start_n_end->end_seq]->length - 1; } #ifdef DEBUG fprintf(stderr, "%d: (%d,%d) -> (%d,%d)\n", mpMyID(), start_n_end->start_seq, start_n_end->start_off, start_n_end->end_seq, start_n_end->end_off); #endif /* DEBUG */ /* Do some error checking. */ /* if (inode != mpNodes()) { fprintf(stderr, "Warning! inode(%d) != mpNodes(%d)\n", inode, mpNodes()); } */ if (iseq != n_samples) fprintf(stderr, "Warning! iseq(%d) != n_samples(%d)\n", iseq, n_samples); }
void * gz_inflate(char *in, size_t inlen, size_t *outlenptr, char *errbuf, size_t errlen) { z_stream z = {0}; unsigned char *out; size_t outlen; int r; if(!gz_check(in, inlen)) { snprintf(errbuf, errlen, "Invalid header"); return NULL; } if(in[3] != 0) { snprintf(errbuf, errlen, "Header extensions is not supported"); return NULL; } in += 10; inlen -= 10; z.next_in = (void *)in; z.avail_in = inlen; if(inflateInit2(&z, -MAX_WBITS) != Z_OK) { snprintf(errbuf, errlen, "Inflate init failed"); return NULL; } outlen = inlen * 2; out = mymalloc(outlen + 1); if(out == NULL) { snprintf(errbuf, errlen, "Out of memory"); inflateEnd(&z); return NULL; } while(1) { if(outlen - z.total_out == 0) { outlen *= 2; out = realloc(out, outlen+1); } z.next_out = out + z.total_out; z.avail_out = outlen - z.total_out; r = inflate(&z, 0); if(r == Z_STREAM_END) break; if(r != Z_OK) { snprintf(errbuf, errlen, "inflate: %s", z.msg); inflateEnd(&z); free(out); return NULL; } } out[z.total_out] = 0; *outlenptr = z.total_out; inflateEnd(&z); return out; }
void *ff_memalloc (UINT size) { return (void*)mymalloc(SRAMIN,size); }
/* mysqlname_parse - parse mysql configuration file */ static MYSQL_NAME *mysqlname_parse(const char *mysqlcf) { const char *myname = "mysqlname_parse"; int i; char *hosts; MYSQL_NAME *name = (MYSQL_NAME *) mymalloc(sizeof(MYSQL_NAME)); ARGV *hosts_argv; /* parser */ name->parser = cfg_parser_alloc(mysqlcf); /* username */ name->username = cfg_get_str(name->parser, "user", "", 0, 0); /* password */ name->password = cfg_get_str(name->parser, "password", "", 0, 0); /* database name */ name->dbname = cfg_get_str(name->parser, "dbname", "", 1, 0); /* table name */ name->table = cfg_get_str(name->parser, "table", "", 1, 0); /* select field */ name->select_field = cfg_get_str(name->parser, "select_field", "", 1, 0); /* where field */ name->where_field = cfg_get_str(name->parser, "where_field", "", 1, 0); /* additional conditions */ name->additional_conditions = cfg_get_str(name->parser, "additional_conditions", "", 0, 0); /* mysql server hosts */ hosts = cfg_get_str(name->parser, "hosts", "", 0, 0); /* coo argv interface */ hosts_argv = argv_split(hosts, " ,\t\r\n"); if (hosts_argv->argc == 0) { /* no hosts specified, * default to 'localhost' */ if (msg_verbose) msg_info("%s: %s: no hostnames specified, defaulting to 'localhost'", myname, mysqlcf); argv_add(hosts_argv, "localhost", ARGV_END); argv_terminate(hosts_argv); } name->len_hosts = hosts_argv->argc; name->hostnames = (char **) mymalloc((sizeof(char *)) * name->len_hosts); i = 0; for (i = 0; hosts_argv->argv[i] != NULL; i++) { name->hostnames[i] = mystrdup(hosts_argv->argv[i]); if (msg_verbose) msg_info("%s: %s: adding host '%s' to list of mysql server hosts", myname, mysqlcf, name->hostnames[i]); } myfree(hosts); argv_free(hosts_argv); return name; }
static boolean ngram_read_bin_compat(FILE *fp, NGRAM_INFO *ndata, int *retry_ret) { int i,n,len; char *w, *p; NNID *n3_bgn; NNID d, ntmp; #ifdef WORDS_INT unsigned short *buf; #endif NGRAM_TUPLE_INFO *t, *tt, *ttt; /* old binary N-gram assumes these types */ ndata->bigram_index_reversed = TRUE; ndata->n = 3; ndata->dir = DIR_RL; /* read total info and set max_word_num */ ndata->d = (NGRAM_TUPLE_INFO *)mymalloc(sizeof(NGRAM_TUPLE_INFO) * ndata->n); memset(ndata->d, 0, sizeof(NGRAM_TUPLE_INFO) * ndata->n); for(n=0;n<ndata->n;n++) { rdn(fp, &(ndata->d[n].totalnum), sizeof(NNID), 1); } ndata->max_word_num = ndata->d[0].totalnum; if (file_version == 4) { rdn(fp, &(ndata->d[1].context_num), sizeof(NNID), 1); } for(n=0;n<ndata->n;n++) { if (n < 2) { ndata->d[n].is24bit = FALSE; } else { if (ndata->d[n].totalnum >= NNID_MAX_24) { jlog("Warning: ngram_read_bin_compat: num of %d-gram exceeds 24bit, now switch to %dbit index\n", n+1, sizeof(NNID) * 8); ndata->d[n].is24bit = FALSE; } else { ndata->d[n].is24bit = TRUE; } } ndata->d[n].nnid2ctid_upper = NULL; ndata->d[n].nnid2ctid_lower = NULL; } /* always do back-off compaction for 3-gram and up */ /* mark 2-gram and up */ ndata->d[0].ct_compaction = FALSE; for(n=1;n<ndata->n;n++) { ndata->d[n].ct_compaction = TRUE; } /* read wname */ rdn(fp, &len, sizeof(int), 1); w = mymalloc(len); rdn(fp, w, 1, len); /* assign... */ ndata->wname = (char **)mymalloc(sizeof(char *) * ndata->max_word_num); p = w; i = 0; while (p < w + len) { ndata->wname[i++] = p; while(*p != '\0') p++; p++; } if (i != ndata->max_word_num) { jlog("Error: ngram_read_bin_compat: wname error??\n"); return FALSE; } /* malloc 1-gram */ t = &(ndata->d[0]); tt = &(ndata->d[1]); ttt = &(ndata->d[2]); t->bgn_upper = NULL; t->bgn_lower = NULL; t->bgn = NULL; t->num = NULL; t->bgnlistlen = 0; t->nnid2wid = NULL; t->nnid2ctid_upper = NULL; t->nnid2ctid_lower = NULL; t->context_num = t->totalnum; t->prob = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), t->totalnum); ndata->bo_wt_1 = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), t->context_num); t->bo_wt = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), t->context_num); tt->bgnlistlen = t->context_num; tt->bgn = (NNID *)mymalloc_big(sizeof(NNID), tt->bgnlistlen); tt->num = (WORD_ID *)mymalloc_big(sizeof(WORD_ID), tt->bgnlistlen); /* read 1-gram */ jlog("stat: ngram_read_bin_compat: reading 1-gram\n"); rdn(fp, t->prob, sizeof(LOGPROB), t->totalnum); rdn(fp, ndata->bo_wt_1, sizeof(LOGPROB), t->context_num); rdn(fp, t->bo_wt, sizeof(LOGPROB), t->context_num); rdn(fp, tt->bgn, sizeof(NNID), tt->bgnlistlen); #ifdef WORDS_INT rdn_wordid(fp, tt->num, tt->bgnlistlen, need_conv); #else rdn(fp, tt->num, sizeof(WORD_ID), tt->bgnlistlen); #endif #ifdef WORDS_INT { /* check if we are wrongly reading word_id=2byte bingram (if bingram version >= 4, this should not be happen because header correctly tells the word_id byte size. This will occur only if matches all the conditions below: - you run Julius with --enable-words-int, - you use old bingram of version <= 3, and - you use bingram file converted without --enable-words-int */ WORD_ID w; for(w=0;w<ndata->max_word_num;w++) { if (ndata->d[1].num[w] > ndata->max_word_num) { if (words_int_retry) { jlog("Error: ngram_read_bin_compat: retry failed, wrong bingram format\n"); return FALSE; } jlog("Warning: ngram_read_bin_compat: incorrect data, may be a 2-byte v3 bingram, retry with conversion\n"); free(ndata->wname[0]); free(ndata->wname); free(t->prob); free(ndata->bo_wt_1); free(t->bo_wt); free(tt->bgn); free(tt->num); myfrewind(fp); words_int_retry = TRUE; *retry_ret = 1; return FALSE; } } } #endif /* malloc the rest */ tt->nnid2wid = (WORD_ID *)mymalloc_big(sizeof(WORD_ID), tt->totalnum); tt->prob = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), tt->totalnum); ndata->p_2 = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), tt->totalnum); if (file_version == 4) { /* context compaction and 24bit */ tt->nnid2ctid_upper = (NNID_UPPER *)mymalloc_big(sizeof(NNID_UPPER), tt->totalnum); tt->nnid2ctid_lower = (NNID_LOWER *)mymalloc_big(sizeof(NNID_LOWER), tt->totalnum); tt->bo_wt = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), tt->context_num); ttt->bgnlistlen = tt->context_num; ttt->bgn_upper = (NNID_UPPER *)mymalloc_big(sizeof(NNID_UPPER), ttt->bgnlistlen); ttt->bgn_lower = (NNID_LOWER *)mymalloc_big(sizeof(NNID_LOWER), ttt->bgnlistlen); ttt->num = (WORD_ID *)mymalloc_big(sizeof(WORD_ID), ttt->bgnlistlen); } else { tt->context_num = tt->totalnum; tt->bo_wt = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), tt->context_num); ttt->bgnlistlen = tt->context_num; ttt->num = (WORD_ID *)mymalloc_big(sizeof(WORD_ID), ttt->bgnlistlen); if (ttt->is24bit) { ttt->bgn_upper = (NNID_UPPER *)mymalloc_big(sizeof(NNID_UPPER), ttt->bgnlistlen); ttt->bgn_lower = (NNID_LOWER *)mymalloc_big(sizeof(NNID_LOWER), ttt->bgnlistlen); n3_bgn = (NNID *)mymalloc_big(sizeof(NNID), ttt->bgnlistlen); } else { ttt->bgn = (NNID *)mymalloc_big(sizeof(NNID), ttt->bgnlistlen); } } ttt->nnid2wid = (WORD_ID *)mymalloc_big(sizeof(WORD_ID), ttt->totalnum); ttt->prob = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), ttt->totalnum); ttt->bo_wt = NULL; /* read 2-gram*/ jlog("Stat: ngram_read_bin_compat: reading 2-gram\n"); #ifdef WORDS_INT rdn_wordid(fp, tt->nnid2wid, tt->totalnum, need_conv); #else rdn(fp, tt->nnid2wid, sizeof(WORD_ID), tt->totalnum); #endif rdn(fp, ndata->p_2, sizeof(LOGPROB), tt->totalnum); rdn(fp, tt->prob, sizeof(LOGPROB), tt->totalnum); if (file_version == 4) { rdn(fp, tt->nnid2ctid_upper, sizeof(NNID_UPPER), tt->totalnum); rdn(fp, tt->nnid2ctid_lower, sizeof(NNID_LOWER), tt->totalnum); rdn(fp, tt->bo_wt, sizeof(LOGPROB), tt->context_num); rdn(fp, ttt->bgn_upper, sizeof(NNID_UPPER), ttt->bgnlistlen); rdn(fp, ttt->bgn_lower, sizeof(NNID_LOWER), ttt->bgnlistlen); #ifdef WORDS_INT rdn_wordid(fp, ttt->num, ttt->bgnlistlen, need_conv); #else rdn(fp, ttt->num, sizeof(WORD_ID), ttt->bgnlistlen); #endif } else { rdn(fp, tt->bo_wt, sizeof(LOGPROB), tt->context_num); if (ttt->is24bit) { rdn(fp, n3_bgn, sizeof(NNID), ttt->bgnlistlen); for(d=0;d<ttt->bgnlistlen;d++) { if (n3_bgn[d] == NNID_INVALID) { ttt->bgn_lower[d] = 0; ttt->bgn_upper[d] = NNID_INVALID_UPPER; } else { ntmp = n3_bgn[d] & 0xffff; ttt->bgn_lower[d] = ntmp; ntmp = n3_bgn[d] >> 16; ttt->bgn_upper[d] = ntmp; } } } else {
void HeapInfo::init(int dataSize) { void* storage = mymalloc(sizeof(HeapInfoImpl)); g_impl = reinterpret_cast<HeapInfoImpl*>(storage); g_impl->m_infoMap = g_hash_table_new_full(keyHash, keyEqual, NULL, valueRelease); }
void merged_scrollback_with_search(char *search_for, mybool_t case_insensitive) { int lc_size = nfd * sizeof(int); int *last_check = (int *)mymalloc(lc_size); int *winnr = NULL; buffer buf; regex_t reg; int rc; memset(last_check, 0x00, lc_size); memset(&buf, 0x00, sizeof(buf)); /* compile the search string which is supposed to be a valid regular * expression */ if (search_for) { if ((rc=regcomp(®, search_for, REG_EXTENDED | (case_insensitive == MY_TRUE?REG_ICASE:0)))) { regexp_error_popup(rc, ®); free(last_check); return; } } /* merge all windows into one */ for(;;) { int loop; double chosen_ts = (double)(((long long int)1) << 62); int chosen_win = -1; int curline; char *string; int checked_all = 0; for(loop=0; loop<nfd; loop++) { if (lb[loop].curpos == last_check[loop]) { checked_all++; continue; } if (search_for != NULL && lb[loop].be[last_check[loop]].Bline != NULL) { rc = regexec(®, lb[loop].be[last_check[loop]].Bline, 0, NULL, 0); /* did not match? don't add and continue */ if (rc == REG_NOMATCH) { continue; } /* is it an error? then popup and abort */ if (rc != 0) { regexp_error_popup(rc, ®); break; } } if (lb[loop].be[last_check[loop]].ts <= chosen_ts) { chosen_ts = lb[loop].be[last_check[loop]].ts; chosen_win = loop; } } if (chosen_win == -1) { if (checked_all == nfd) break; for(loop=0; loop<nfd; loop++) { if (lb[loop].curpos > last_check[loop]) last_check[loop]++; } continue; } if (!IS_MARKERLINE(lb[chosen_win].be[last_check[chosen_win]].pi)) { /*** ADD LINE TO BUFFER ***/ buf.be = (buffered_entry *)myrealloc(buf.be, sizeof(buffered_entry) * (buf.curpos + 1)); winnr = (int *)myrealloc(winnr, sizeof(int) * (buf.curpos + 1)); curline = buf.curpos++; /* add the logline itself */ string = lb[chosen_win].be[last_check[chosen_win]].Bline; if (string) buf.be[curline].Bline = mystrdup(string); else buf.be[curline].Bline = NULL; /* remember pointer to subwindow (required for setting colors etc.) */ buf.be[curline].pi = lb[chosen_win].be[last_check[chosen_win]].pi; buf.be[curline].ts = lb[chosen_win].be[last_check[chosen_win]].ts; /* remember window nr. */ winnr[curline] = chosen_win; } last_check[chosen_win]++; } if (buf.curpos == 0) error_popup("Search in all windows", -1, "Nothing found."); else { char *header; if (search_for) { char *help = "Searched for: "; int len = strlen(help) + strlen(search_for) + 1; header = mymalloc(len); snprintf(header, len, "%s%s", help, search_for); } else { char *help = "Merge view"; header = mymalloc(strlen(help) + 1); sprintf(header, "%s", help); } scrollback_do(-1, &buf, winnr, header); myfree(header); } delete_be_in_buffer(&buf); myfree(winnr); myfree(last_check); }
static void mainloop (void) { /* data is persistant across calls */ static struct timeval timestruct; static int changequartersec, changesec, changemin, changehour; static time_t lasttime, lastmin, lasthour, last4sec, last5sec, last20sec; static time_t lastautoadd; static time_t last3min, last2min, lastignoredec; static int first_loop = 1; static ir_uint64 last250ms; userinput *pubplist; userinput *urehash; ir_uint64 xdccsent; unsigned int i; int highests; unsigned int ss; upload *ul; transfer *tr; channel_t *ch; xdcc *xd; dccchat_t *chat; updatecontext(); gnetwork = NULL; if (first_loop) { /* init if first time called */ FD_ZERO(&gdata.readset); FD_ZERO(&gdata.writeset); changehour=changemin=changesec=changequartersec=0; gettimeofday(×truct, NULL); last250ms = gdata.curtimems; gdata.curtimems = timeval_to_ms(×truct); ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Startup" " running: %ld ms", (long)(gdata.curtimems - last250ms)); gdata.curtime = timestruct.tv_sec; lasttime=gdata.curtime; last250ms = gdata.curtimems; lastmin=(lasttime/60)-1; lasthour=(lasttime/60/60)-1; last4sec = last5sec = last20sec = last2min = last3min = lasttime; lastignoredec = lasttime; for (ss=0; ss<gdata.networks_online; ss++) { gdata.networks[ss].lastnotify = lasttime; gdata.networks[ss].lastslow = lasttime; gdata.networks[ss].server_input_line[0] = '\0'; } gdata.cursendptr = 0; lastautoadd = gdata.curtime + 60; first_loop = 0; } updatecontext(); FD_ZERO(&gdata.readset); FD_ZERO(&gdata.writeset); FD_ZERO(&gdata.execset); highests = 0; #ifdef USE_CURL fetch_multi_fdset(&gdata.readset, &gdata.writeset, &gdata.execset, &highests); #endif /* USE_CURL */ highests = irc_select(highests); if (!gdata.background) { FD_SET(fileno(stdin), &gdata.readset); highests = max2(highests, fileno(stdin)); } highests = chat_select_fdset(highests); highests = t_select_fdset(highests, changequartersec); highests = l_select_fdset(highests, changequartersec); #ifndef WITHOUT_TELNET highests = telnet_select_fdset(highests); #endif /* WITHOUT_TELNET */ #ifndef WITHOUT_HTTP highests = h_select_fdset(highests, changequartersec); #endif /* WITHOUT_HTTP */ if (gdata.md5build.file_fd != FD_UNUSED) { assert(gdata.md5build.xpack); FD_SET(gdata.md5build.file_fd, &gdata.readset); highests = max2(highests, gdata.md5build.file_fd); } updatecontext(); if (gdata.debug > 81) { select_dump("try", highests); } if (gdata.attop) gotobot(); tostdout_write(); gettimeofday(×truct, NULL); gdata.selecttimems = timeval_to_ms(×truct); if (ir_kqueue_select(highests+1, &gdata.readset, &gdata.writeset, &gdata.execset) < 0) { if (errno != EINTR) { outerror(OUTERROR_TYPE_WARN,"Select returned an error: %s",strerror(errno)); usleep(10000); /* prevent fast spinning */ } /* data is undefined on error, zero and continue */ FD_ZERO(&gdata.readset); FD_ZERO(&gdata.writeset); FD_ZERO(&gdata.execset); } if (gdata.debug > 81) { select_dump("got", highests); } /*----- one second check ----- */ updatecontext(); if (gettimeofday(×truct, NULL) < 0) { outerror(OUTERROR_TYPE_CRASH,"gettimeofday() failed! %s\n",strerror(errno)); } gdata.curtimems = timeval_to_ms(×truct); gdata.curtime = timestruct.tv_sec; if (gdata.curtimems > gdata.selecttimems + 1000) outerror(OUTERROR_TYPE_WARN, "Iroffer was blocked for %lims", (long)(gdata.curtimems - gdata.selecttimems)); /* adjust for drift and cpu usage */ if ((gdata.curtimems > (last250ms+1000)) || (gdata.curtimems < last250ms)) { /* skipped forward or backwards, correct */ last250ms = gdata.curtimems-250; } if (gdata.curtimems >= (last250ms+250)) { changequartersec = 1; /* note bandwidth limiting requires no drift! */ last250ms += 250; } else { changequartersec = 0; } changesec = 0; if (gdata.curtime != lasttime) { if (gdata.curtime < lasttime - MAX_WAKEUP_WARN) { outerror(OUTERROR_TYPE_WARN, "System Time Changed Backwards %lim %lis!!\n", (long)(lasttime-gdata.curtime)/60, (long)(lasttime-gdata.curtime)%60); } if (gdata.curtime > lasttime + MAX_WAKEUP_WARN) { outerror(OUTERROR_TYPE_WARN, "System Time Changed Forward or Mainloop Skipped %lim %lis!!\n", (long)(gdata.curtime-lasttime)/60, (long)(gdata.curtime-lasttime)%60); if (gdata.debug > 0) { dump_slow_context(); } } if (gdata.curtime > lasttime + MAX_WAKEUP_ERR) { outerror(OUTERROR_TYPE_WARN, "System Time Changed Forward or Mainloop Skipped %lim %lis!!\n", (long)(gdata.curtime-lasttime)/60, (long)(gdata.curtime-lasttime)%60); if (gdata.debug > 0) { dumpcontext(); } } lasttime = gdata.curtime; changesec = 1; } if (changesec && lasttime/60/60 != lasthour) { lasthour = lasttime/60/60; changehour = 1; } if (changesec && lasttime/60 != lastmin) { lastmin = lasttime/60; changemin = 1; } if (gdata.needsshutdown) { gdata.needsshutdown = 0; shutdowniroffer(); } if (gdata.needsreap) { gdata.needsreap = 0; irc_resolved(); } #ifdef USE_CURL fetch_perform(); #endif /* USE_CURL */ updatecontext(); if (changesec) { gdata.totaluptime++; gdata.xdccsent[(gdata.curtime+1)%XDCC_SENT_SIZE] = 0; gdata.xdccrecv[(gdata.curtime+1)%XDCC_SENT_SIZE] = 0; xdccsent = 0; for (i=0; i<XDCC_SENT_SIZE; i++) xdccsent += (ir_uint64)gdata.xdccsum[i]; if (((float)xdccsent)/XDCC_SENT_SIZE/1024.0 > gdata.sentrecord) gdata.sentrecord = ((float)xdccsent)/XDCC_SENT_SIZE/1024.0; gdata.xdccsum[(gdata.curtime+1)%XDCC_SENT_SIZE] = 0; run_delayed_jobs(); } updatecontext(); /*----- see if anything waiting on console ----- */ gdata.needsclear = 0; if (!gdata.background && FD_ISSET(fileno(stdin), &gdata.readset)) parseconsole(); irc_perform(changesec); l_perform(changesec); chat_perform(); t_perform(changesec, changequartersec); #ifndef WITHOUT_TELNET telnet_perform(); #endif /* WITHOUT_TELNET */ #ifndef WITHOUT_HTTP h_perform(changesec, changequartersec); #endif /* WITHOUT_HTTP */ /*----- time for a delayed shutdown? ----- */ if (changesec && gdata.delayedshutdown) { if (!irlist_size(&gdata.trans)) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Delayed Shutdown Activated, No Transfers Remaining"); shutdowniroffer(); } } updatecontext(); for (ss=0; ss<gdata.networks_online; ss++) { gnetwork = &(gdata.networks[ss]); /*----- send server stuff ----- */ if (changesec) { sendserver(); if (gdata.curtime%INAMNT_SIZE == (INAMNT_SIZE-1)) gnetwork->inamnt[0] = 0; else gnetwork->inamnt[gdata.curtime%INAMNT_SIZE+1] = 0; } /*----- see if we can send out some xdcc lists */ if (changesec && gnetwork->serverstatus == SERVERSTATUS_CONNECTED) { if (!irlist_size((&gnetwork->serverq_normal)) && !irlist_size(&(gnetwork->serverq_slow))) sendxdlqueue(); } } gnetwork = NULL; /*----- see if its time to change maxb */ if (changehour) { gdata.maxb = gdata.overallmaxspeed; if (gdata.overallmaxspeeddayspeed != gdata.overallmaxspeed) { struct tm *localt; localt = localtime(&gdata.curtime); if ((unsigned int)localt->tm_hour >= gdata.overallmaxspeeddaytimestart && (unsigned int)localt->tm_hour < gdata.overallmaxspeeddaytimeend && ( gdata.overallmaxspeeddaydays & (1 << (unsigned int)localt->tm_wday)) ) gdata.maxb = gdata.overallmaxspeeddayspeed; } isrotatelog(); expire_options(); } /*----- see if we've hit a transferlimit or need to reset counters */ if (changesec) { unsigned int ii; unsigned int transferlimits_over = 0; for (ii=0; ii<NUMBER_TRANSFERLIMITS; ii++) { /* reset counters? */ if ((!gdata.transferlimits[ii].ends) || (gdata.transferlimits[ii].ends < gdata.curtime)) { struct tm *localt; if (gdata.transferlimits[ii].limit && gdata.transferlimits[ii].ends) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Resetting %s transfer limit, used %" LLPRINTFMT "uMB of the %" LLPRINTFMT "uMB limit", transferlimit_type_to_string(ii), gdata.transferlimits[ii].used / 1024 / 1024, gdata.transferlimits[ii].limit / 1024 / 1024); } /* find our next end time */ localt = localtime(&gdata.curtime); localt->tm_sec = localt->tm_min = localt->tm_hour = 0; /* midnight */ switch (ii) { case TRANSFERLIMIT_DAILY: /* tomorrow */ localt->tm_mday++; break; case TRANSFERLIMIT_WEEKLY: /* next sunday morning */ localt->tm_mday += 7 - localt->tm_wday; break; case TRANSFERLIMIT_MONTHLY: /* next month */ localt->tm_mday = gdata.start_of_month; localt->tm_mon++; break; default: outerror(OUTERROR_TYPE_CRASH, "unknown type %u", ii); } /* tm_wday and tm_yday are ignored in mktime() */ gdata.transferlimits[ii].ends = mktime(localt); gdata.transferlimits[ii].used = 0; if ( ii == TRANSFERLIMIT_DAILY ) reset_download_limits(); } if (!transferlimits_over && gdata.transferlimits[ii].limit && (gdata.transferlimits[ii].used >= gdata.transferlimits[ii].limit)) { transferlimits_over = 1 + ii; if (!gdata.transferlimits_over) { char *tempstr = transfer_limit_exceeded_msg(ii); ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "All %" LLPRINTFMT "uMB of the %s transfer limit used. Stopping transfers.", gdata.transferlimits[ii].limit / 1024 / 1024, transferlimit_type_to_string(ii)); /* remove queued users */ queue_all_remove(&gdata.mainqueue, tempstr); queue_all_remove(&gdata.idlequeue, tempstr); /* stop transfers */ for (tr = irlist_get_head(&gdata.trans); tr; tr = irlist_get_next(tr)) { if (tr->tr_status != TRANSFER_STATUS_DONE) { gnetwork = &(gdata.networks[tr->net]); t_closeconn(tr,tempstr,0); } } gnetwork = NULL; mydelete(tempstr); } } } if (gdata.transferlimits_over != transferlimits_over) { if (!transferlimits_over) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "No longer over any transfer limits. Transfers are now allowed."); } gdata.transferlimits_over = transferlimits_over; } } /*----- gdata.autoignore_threshold seconds ----- */ if (changesec && ((unsigned)gdata.curtime > (lastignoredec + gdata.autoignore_threshold))) { igninfo *ignore; lastignoredec += gdata.autoignore_threshold; ignore = irlist_get_head(&gdata.ignorelist); while(ignore) { ignore->bucket--; if ((ignore->flags & IGN_IGNORING) && (ignore->bucket == 0)) { ignore->flags &= ~IGN_IGNORING; ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Ignore removed for %s",ignore->hostmask); write_statefile(); } if (ignore->bucket == 0) { mydelete(ignore->hostmask); ignore = irlist_delete(&gdata.ignorelist, ignore); } else { ignore = irlist_get_next(ignore); } } } /*----- periodicmsg_time seconds ----- */ if (changesec) { send_periodicmsg(); } updatecontext(); /*----- 5 seconds ----- */ if (changesec && (gdata.curtime - last5sec > 4)) { last5sec = gdata.curtime; updatecontext(); /*----- server timeout ----- */ for (ss=0; ss<gdata.networks_online; ss++) { gnetwork = &(gdata.networks[ss]); if (gdata.needsshutdown) continue; if ((gnetwork->serverstatus == SERVERSTATUS_CONNECTED) && (gdata.curtime > gnetwork->lastservercontact + SRVRTOUT)) { if (gnetwork->servertime < 3) { const char *servname = gnetwork->curserveractualname ? gnetwork->curserveractualname : gnetwork->curserver.hostname; size_t len = 6 + strlen(servname); char *tempstr3 = mymalloc(len + 1); snprintf(tempstr3, len + 1, "PING %s\n", servname); writeserver_ssl(tempstr3, len); if (gdata.debug > 0) { tempstr3[len-1] = '\0'; len--; ioutput(OUT_S, COLOR_MAGENTA, "<NORES<: %s", tempstr3); } mydelete(tempstr3); gnetwork->servertime++; } else if (gnetwork->servertime == 3) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_RED, "Closing Server Connection on %s: No Response for %u minutes.", gnetwork->name, SRVRTOUT/60); close_server(); gnetwork->servertime = 0; } } /*----- ping server ----- */ if (gnetwork->recentsent) { pingserver(); gnetwork->recentsent--; } } } /* networks */ gnetwork = NULL; /*----- 4 seconds ----- */ if (changesec && (gdata.curtime - last4sec > 3)) { /*----- update lastspeed, check minspeed ----- */ tr = irlist_get_head(&gdata.trans); while(tr) { if ( tr->con.connecttime+(MIN_TL/2) > gdata.curtime ) /* initial */ { tr->lastspeed = (tr->lastspeed)*DCL_SPDW_I + (((float)(tr->bytessent-tr->lastspeedamt))/1024.0)*(1.0-DCL_SPDW_I)/((float)(gdata.curtime-last4sec)*1.0); } else /* ongoing */ { tr->lastspeed = (tr->lastspeed)*DCL_SPDW_O + (((float)(tr->bytessent-tr->lastspeedamt))/1024.0)*(1.0-DCL_SPDW_O)/((float)(gdata.curtime-last4sec)*1.0); } tr->lastspeedamt = tr->bytessent; t_checkminspeed(tr); tr = irlist_get_next(tr); } ul = irlist_get_head(&gdata.uploads); while(ul) { if ( ul->con.connecttime+(MIN_TL/2) > gdata.curtime ) /* initial */ { ul->lastspeed = (ul->lastspeed)*DCL_SPDW_I + (((float)(ul->bytesgot-ul->lastspeedamt))/1024.0)*(1.0-DCL_SPDW_I)/((float)(gdata.curtime-last4sec)*1.0); } else /* ongoing */ { ul->lastspeed = (ul->lastspeed)*DCL_SPDW_O + (((float)(ul->bytesgot-ul->lastspeedamt))/1024.0)*(1.0-DCL_SPDW_O)/((float)(gdata.curtime-last4sec)*1.0); } ul->lastspeedamt = ul->bytesgot; ul = irlist_get_next(ul); } last4sec = gdata.curtime; } updatecontext(); /*----- check for size change ----- */ if (changesec) checktermsize(); updatecontext(); for (ss=0; ss<gdata.networks_online; ss++) { gnetwork = &(gdata.networks[ss]); /*----- plist stuff ----- */ if ((gnetwork->serverstatus == SERVERSTATUS_CONNECTED) && changemin && irlist_size(&gdata.xdccs) && !gdata.transferlimits_over && (irlist_size(&(gnetwork->serverq_channel)) < irlist_size(&gdata.xdccs)) && (!gdata.queuesize || irlist_size(&gdata.mainqueue) < gdata.queuesize) && (gdata.nolisting <= gdata.curtime)) { char *tchanf = NULL, *tchanm = NULL, *tchans = NULL; for(ch = irlist_get_head(&(gnetwork->channels)); ch; ch = irlist_get_next(ch)) { if ((ch->flags & CHAN_ONCHAN) && (ch->nextann < gdata.curtime) && ch->plisttime && (((gdata.curtime / 60) % ch->plisttime) == ch->plistoffset)) { ch->nextmsg = gdata.curtime + ch->delay; if (ch->pgroup != NULL) { ioutput(OUT_S|OUT_D, COLOR_NO_COLOR, "Plist sent to %s (pgroup)", ch->name); pubplist = mycalloc(sizeof(userinput)); pubplist->method = method_xdl_channel; pubplist->net = gnetwork->net; pubplist->level = ADMIN_LEVEL_PUBLIC; a_fillwith_plist(pubplist, ch->name, ch); u_parseit(pubplist); mydelete(pubplist); continue; } if (ch->flags & CHAN_MINIMAL) { if (tchanm) { strncat(tchanm,",",maxtextlength-strlen(tchanm)-1); strncat(tchanm,ch->name,maxtextlength-strlen(tchanm)-1); } else { tchanm = mymalloc(maxtextlength); strncpy(tchanm,ch->name,maxtextlength-1); } } else if (ch->flags & CHAN_SUMMARY) { if (tchans) { strncat(tchans,",",maxtextlength-strlen(tchans)-1); strncat(tchans,ch->name,maxtextlength-strlen(tchans)-1); } else { tchans = mymalloc(maxtextlength); strncpy(tchans,ch->name,maxtextlength-1); } } else { if (tchanf) { strncat(tchanf,",",maxtextlength-strlen(tchanf)-1); strncat(tchanf,ch->name,maxtextlength-strlen(tchanf)-1); } else { tchanf = mymalloc(maxtextlength); strncpy(tchanf,ch->name,maxtextlength-1); } } } } if (tchans) { if (gdata.restrictprivlist && !gdata.creditline && !irlist_size(&gdata.headline)) { ioutput(OUT_S|OUT_D, COLOR_NO_COLOR, "Can't send Summary Plist to %s (restrictprivlist is set and no creditline or headline, summary makes no sense!)", tchans); } else { ioutput(OUT_S|OUT_D, COLOR_NO_COLOR, "Plist sent to %s (summary)", tchans); pubplist = mycalloc(sizeof(userinput)); a_fillwith_msg2(pubplist, tchans, "XDL"); pubplist->method = method_xdl_channel_sum; u_parseit(pubplist); mydelete(pubplist); } mydelete(tchans); } if (tchanf) { ioutput(OUT_S|OUT_D, COLOR_NO_COLOR, "Plist sent to %s (full)", tchanf); pubplist = mycalloc(sizeof(userinput)); a_fillwith_plist(pubplist, tchanf, NULL); pubplist->method = method_xdl_channel; u_parseit(pubplist); mydelete(pubplist); mydelete(tchanf); } if (tchanm) { ioutput(OUT_S|OUT_D, COLOR_NO_COLOR, "Plist sent to %s (minimal)", tchanm); pubplist = mycalloc(sizeof(userinput)); a_fillwith_msg2(pubplist, tchanm, "XDL"); pubplist->method = method_xdl_channel_min; u_parseit(pubplist); mydelete(pubplist); mydelete(tchanm); } } } /* networks */ gnetwork = NULL; updatecontext(); /*----- low bandwidth send, save state file ----- */ if (changesec && (gdata.curtime - last3min > 180)) { last3min = gdata.curtime; xdccsent = 0; for (i=0; i<XDCC_SENT_SIZE; i++) xdccsent += (ir_uint64)gdata.xdccsent[i]; xdccsent /= XDCC_SENT_SIZE*1024; if ((xdccsent < (unsigned)gdata.lowbdwth) && !gdata.exiting && irlist_size(&gdata.mainqueue) && (irlist_size(&gdata.trans) < gdata.maxtrans)) { check_idle_queue(0); send_from_queue(1, 0, NULL); } write_files(); } updatecontext(); for (ss=0; ss<gdata.networks_online; ss++) { gnetwork = &(gdata.networks[ss]); /*----- queue notify ----- */ if (changesec && gdata.notifytime && (!gdata.quietmode) && ((unsigned)gdata.curtime > (gnetwork->lastnotify + (gdata.notifytime*60)))) { gnetwork->lastnotify = gdata.curtime; if (gnetwork->serverstatus == SERVERSTATUS_CONNECTED) { if ((irlist_size(&(gnetwork->serverq_fast)) >= 10) || (irlist_size(&(gnetwork->serverq_normal)) >= 10) || (irlist_size(&(gnetwork->serverq_slow)) >= 50)) { ioutput(OUT_S|OUT_D|OUT_L, COLOR_NO_COLOR, "notifications skipped on %s, server queue is rather large", gnetwork->name); } else { notifyqueued(); notifybandwidth(); notifybandwidthtrans(); } } } } /* networks */ gnetwork = NULL; updatecontext(); /*----- log stats / remote admin stats ----- */ if ( changesec && ((unsigned)gdata.curtime >= (last2min + gdata.status_time_dcc_chat))) { last2min = gdata.curtime; if (gdata.logstats) { logstat(); chat_writestatus(); } } updatecontext(); /* look to see if any files changed */ if (changesec) look_for_file_remove(); updatecontext(); /*----- 20 seconds ----- */ if (changesec && (gdata.curtime - last20sec > 19)) { expire_badip(); if (gdata.logfd != FD_UNUSED) { /* cycle */ close(gdata.logfd); gdata.logfd = FD_UNUSED; } updatecontext(); for (ss=0; ss<gdata.networks_online; ss++) { gnetwork = &(gdata.networks[ss]); /* try rejoining channels not on */ ch = irlist_get_head(&(gnetwork->channels)); while(ch) { if ((gnetwork->serverstatus == SERVERSTATUS_CONNECTED) && !(ch->flags & CHAN_ONCHAN)) { joinchannel(ch); } ch = irlist_get_next(ch); } } /* networks */ gnetwork = NULL; last20sec = gdata.curtime; updatecontext(); for (ss=0; ss<gdata.networks_online; ss++) { gnetwork = &(gdata.networks[ss]); /* try to regain nick */ if (!gnetwork->user_nick || strcmp(get_config_nick(), gnetwork->user_nick)) { writeserver(WRITESERVER_NORMAL, "NICK %s", get_config_nick()); } } /* networks */ gnetwork = NULL; updatecontext(); /* update status line */ if (!gdata.background && !gdata.noscreen) { char tempstr[maxtextlength]; char tempstr2[maxtextlengthshort]; if (gdata.attop) gotobot(); tostdout(IRVT_SAVE_CURSOR); getstatusline(tempstr,maxtextlength); tempstr[min2(maxtextlength-2,gdata.termcols-4)] = '\0'; snprintf(tempstr2, maxtextlengthshort, IRVT_CURSOR_HOME1 "[ %%-%us ]", gdata.termlines - 1, gdata.termcols - 4); tostdout(tempstr2,tempstr); tostdout(IRVT_CURSOR_HOME2 IRVT_UNSAVE_CURSOR, gdata.termlines, gdata.termcols); } admin_jobs(); #ifdef USE_RUBY rehash_myruby(1); #endif /* USE_RUBY */ delayed_announce(); } updatecontext(); if (changemin) { reverify_restrictsend(); update_hour_dinoex(lastmin); check_idle_queue(0); clean_uploadhost(); auto_rehash(); } updatecontext(); if ((gdata.md5build.file_fd != FD_UNUSED) && FD_ISSET(gdata.md5build.file_fd, &gdata.readset)) { ssize_t howmuch; #if defined(_OS_CYGWIN) int reads_per_loop = 32; #else /* _OS_CYGWIN */ int reads_per_loop = 64; #endif /* _OS_CYGWIN */ assert(gdata.md5build.xpack); while (reads_per_loop--) { howmuch = read(gdata.md5build.file_fd, gdata.sendbuff, BUFFERSIZE); if (gdata.debug >30) { ioutput(OUT_S, COLOR_YELLOW, "MD5: [Pack %u] read %ld", number_of_pack(gdata.md5build.xpack), (long)howmuch); } if ((howmuch < 0) && (errno != EAGAIN)) { outerror(OUTERROR_TYPE_WARN, "MD5: [Pack %u] Can't read data from file '%s': %s", number_of_pack(gdata.md5build.xpack), gdata.md5build.xpack->file, strerror(errno)); event_close(gdata.md5build.file_fd); gdata.md5build.file_fd = FD_UNUSED; gdata.md5build.xpack = NULL; break; } else if (howmuch < 0) { break; } else if (howmuch == 0) { /* EOF */ outerror(OUTERROR_TYPE_WARN, "MD5: [Pack %u] Can't read data from file '%s': %s", number_of_pack(gdata.md5build.xpack), gdata.md5build.xpack->file, "truncated"); start_md5_hash(gdata.md5build.xpack, number_of_pack(gdata.md5build.xpack)); break; } /* else got data */ MD5Update(&gdata.md5build.md5sum, gdata.sendbuff, howmuch); if (!gdata.nocrc32) crc32_update((char *)gdata.sendbuff, howmuch); gdata.md5build.bytes += howmuch; if (gdata.md5build.bytes == gdata.md5build.xpack->st_size) { complete_md5_hash(); break; } } } if (!gdata.nomd5sum && changesec && (!gdata.md5build.xpack)) { unsigned int packnum = 1; /* see if any pack needs a md5sum calculated */ if (gdata.nomd5_start <= gdata.curtime) for (xd = irlist_get_head(&gdata.xdccs); xd; xd = irlist_get_next(xd), packnum++) { if (!gdata.nocrc32) { if (!xd->has_crc32) xd->has_md5sum = 0; /* force recheck with crc */ } if (!xd->has_md5sum) { if (verifyshell(&gdata.md5sum_exclude, xd->file)) continue; if (!gdata.attop) gototop(); start_md5_hash(xd, packnum); break; } } } updatecontext(); if (gdata.exiting && has_closed_servers()) { for (chat = irlist_get_head(&gdata.dccchats); chat; chat = irlist_delete(&gdata.dccchats,chat)) { writedccchat(chat, 0, "iroffer exited, Closing DCC Chat\n"); shutdowndccchat(chat,1); } mylog("iroffer exited\n\n"); exit_iroffer(0); } updatecontext(); if (gdata.needsrehash) { gdata.needsrehash = 0; urehash = mycalloc(sizeof(userinput)); a_fillwith_msg2(urehash, NULL, "REHASH"); urehash->method = method_out_all; /* just OUT_S|OUT_L|OUT_D it */ urehash->net = 0; urehash->level = ADMIN_LEVEL_FULL; u_parseit(urehash); mydelete(urehash); } updatecontext(); chat = irlist_get_head(&gdata.dccchats); while (chat) { if (chat->status == DCCCHAT_UNUSED) { chat = irlist_delete(&gdata.dccchats,chat); } else { flushdccchat(chat); chat = irlist_get_next(chat); } } if (gdata.autoadd_time > 0) { if (changesec && ((unsigned)gdata.curtime > (lastautoadd + gdata.autoadd_time))) { lastautoadd = gdata.curtime; autoadd_all(); } } /* END */ updatecontext(); if (gdata.needsclear) drawbot(); changehour=changemin=0; }
void t_checkminspeed(transfer * const t) { char *hostmask; char *tempstr2; updatecontext(); if (t->tr_status != TRANSFER_STATUS_SENDING) return; /* no checking unless we're sending */ if (t->con.connecttime+MIN_TL > gdata.curtime) return; /* no checking until time has passed */ if (t->nomin || (t->xpack->minspeed) == 0.0) return; /* no minspeed for this transfer */ if ( t->lastspeed+0.11 > t->xpack->minspeed ) return; /* over minspeed */ if (gdata.no_minspeed_on_free) { if (irlist_size(&gdata.trans) < gdata.slotsmax) return; /* free slots */ } tempstr2 = mymalloc(maxtextlength); snprintf(tempstr2, maxtextlength, "Under Min Speed Requirement, %2.1fK/sec is less than %2.1fK/sec", t->lastspeed,t->xpack->minspeed); t_closeconn(t,tempstr2,0); mydelete(tempstr2); if (gdata.punishslowusers) { igninfo *ignore; transfer *tr; gnetwork_t *backup; for (tr = irlist_get_head(&gdata.trans); tr; tr = irlist_get_next(tr)) { if ((tr->tr_status != TRANSFER_STATUS_DONE) && (strcasecmp(tr->nick,t->nick) == 0)) { t_closeconn(tr, "You are being punished for your slowness", 0); } } queue_punish_abuse("You are being punished for your slowness", t->net, t->nick); hostmask = to_hostmask( "*", t->hostname); ignore = get_ignore(hostmask); mydelete(hostmask); ignore->flags |= IGN_IGNORING; ignore->bucket = (gdata.punishslowusers*60)/gdata.autoignore_threshold; backup = gnetwork; gnetwork = &(gdata.networks[t->net]); ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Punish-ignore activated for (%s on %s) (%s) %u minutes", t->nick, gdata.networks[ t->net ].name, ignore->hostmask, gdata.punishslowusers); notice(t->nick, "Punish-ignore activated for %s (%s) %u minutes", t->nick, ignore->hostmask, gdata.punishslowusers); gnetwork = backup; write_statefile(); } }
void t_setup_send(transfer * const t) { char *msg; SIGNEDSOCK int addrlen; updatecontext(); t->tr_status = TRANSFER_STATUS_SENDING; if (gdata.debug > 0) { ioutput(OUT_S, COLOR_YELLOW, "clientsock = %d", t->con.clientsocket); } if (t->xpack->file_fd == FD_UNUSED) { t->xpack->file_fd = open(t->xpack->file, O_RDONLY | ADDED_OPEN_FLAGS); if (t->xpack->file_fd < 0) { int errno2 = errno; t->xpack->file_fd = FD_UNUSED; outerror(OUTERROR_TYPE_WARN_LOUD,"Cant Access Offered File '%s': %s",t->xpack->file,strerror(errno)); t_closeconn(t, "File Error, Report the Problem to the Owner", errno2); return; } t->xpack->file_fd_location = 0; if (gdata.mirc_dcc64) if (t->xpack->st_size > 0xFFFFFFFFL) t->mirc_dcc64 = 1; } t->bytessent = t->startresume; ir_setsockopt(t->con.clientsocket); t->con.lastcontact = gdata.curtime; t->con.connecttime = gdata.curtime; t->connecttimems = gdata.curtimems; t->lastspeed = t->xpack->minspeed; t->lastspeedamt = t->startresume; addrlen = (t->con.family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6); if ((getpeername(t->con.clientsocket, &(t->con.remote.sa), &(addrlen))) < 0) outerror(OUTERROR_TYPE_WARN, "Couldn't get Remote IP: %s", strerror(errno)); if (t_check_ip_access(t)) return; if (t->con.family == AF_INET) { t->remoteip = ntohl(t->con.remote.sin.sin_addr.s_addr); } if ((getsockname(t->con.clientsocket, &(t->con.local.sa), &(addrlen))) < 0) outerror(OUTERROR_TYPE_WARN, "Couldn't get Local IP: %s", strerror(errno)); msg = mymalloc(maxtextlength); my_getnameinfo(msg, maxtextlength -1, &(t->con.remote.sa)); mydelete(t->con.remoteaddr); t->con.remoteaddr = mystrdup(msg); my_getnameinfo(msg, maxtextlength -1, &(t->con.local.sa)); t->con.localaddr = mystrdup(msg); mydelete(msg); ioutput(OUT_S|OUT_L|OUT_D, COLOR_YELLOW, "XDCC [%02i:%s on %s]: Connection established (%s -> %s)", t->id, t->nick, gdata.networks[ t->net ].name, t->con.remoteaddr, t->con.localaddr); }
void t_flushed (transfer * const t) { ir_uint64 timetookms; char *tempstr; updatecontext(); if (t->lastack < t->xpack->st_size) { return; } tempstr = mymalloc(maxtextlength); tempstr[0] = 0; timetookms = gdata.curtimems - t->connecttimems; if (timetookms < 1U) { timetookms = 1; } if (timetookms > (60*60*1000U)) { snprintf(tempstr+strlen(tempstr), maxtextlength-strlen(tempstr), " %" LLPRINTFMT "u hr", timetookms/60/60/1000); } if ((timetookms%(60*60*1000U)) > (60*1000U)) { snprintf(tempstr+strlen(tempstr), maxtextlength-strlen(tempstr), " %" LLPRINTFMT "u min", (timetookms%(60*60*1000))/60/1000); } snprintf(tempstr+strlen(tempstr), maxtextlength-strlen(tempstr), " %" LLPRINTFMT "u.%03" LLPRINTFMT "u sec", (timetookms%(60*1000))/1000, (timetookms%1000)); ioutput(OUT_S|OUT_L|OUT_D, COLOR_YELLOW, "XDCC [%02i:%s on %s]: Transfer Completed (%" LLPRINTFMT "d kB,%s, %0.1f kB/sec)", t->id, t->nick, gdata.networks[ t->net ].name, (t->xpack->st_size-t->startresume)/1024, tempstr, ((float)(t->xpack->st_size-t->startresume))/1024.0/((float)timetookms/1000.0)); ioutput(OUT_S|OUT_L|OUT_D, COLOR_YELLOW, "Log: Pack %u, Nick %s" ", Network %s" ", Sent %" LLPRINTFMT "d kB" ", Recv %" LLPRINTFMT "d kB" ", File %s", number_of_pack(t->xpack), t->nick, gdata.networks[ t->net ].name, (t->xpack->st_size-t->startresume)/1024, t->bytesgot/1024, t->xpack->desc ); if (t->quietmode == 0) { if (t->xpack->has_md5sum) { notice(t->nick, "** Transfer Completed (%" LLPRINTFMT "d kB,%s, %0.1f kB/sec, md5sum: " MD5_PRINT_FMT ")", (t->xpack->st_size-t->startresume)/1024, tempstr, ((float)(t->xpack->st_size-t->startresume))/1024.0/((float)timetookms/1000.0), MD5_PRINT_DATA(t->xpack->md5sum)); } else { notice(t->nick, "** Transfer Completed (%" LLPRINTFMT "d kB,%s, %0.1f kB/sec)", (t->xpack->st_size-t->startresume)/1024, tempstr, ((float)(t->xpack->st_size-t->startresume))/1024.0/((float)timetookms/1000.0)); } } if (gdata.download_completed_msg) { notice_slow(t->nick, "%s", gdata.download_completed_msg); } if ( ((float)(t->xpack->st_size-t->startresume))/1024.0/((float)timetookms/1000.0) > gdata.record ) { gdata.record = ((float)(t->xpack->st_size-t->startresume))/1024.0/((float)timetookms/1000.0); } if (gdata.debug > 0) { ioutput(OUT_S, COLOR_YELLOW, "clientsock = %d", t->con.clientsocket); } shutdown_close(t->con.clientsocket); t->xpack->file_fd_count--; if (!t->xpack->file_fd_count && (t->xpack->file_fd != FD_UNUSED)) { close(t->xpack->file_fd); t->xpack->file_fd = FD_UNUSED; t->xpack->file_fd_location = 0; } t->tr_status = TRANSFER_STATUS_DONE; t->xpack->gets++; if ((t->xpack->dlimit_max != 0) && (t->xpack->gets >= t->xpack->dlimit_used)) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_YELLOW, "Reached Pack Download Limit %u for %s", t->xpack->dlimit_max, t->xpack->desc); /* remove queued users */ queue_pack_limit(&gdata.mainqueue, t->xpack); queue_pack_limit(&gdata.idlequeue, t->xpack); } mydelete(tempstr); }
/* Get the pgm file used as fixed mask */ unsigned char *get_pgm(FILE *picture, int width, int height) { int x = 0 ,y = 0, maxval; char line[256]; unsigned char *image; line[255]=0; if (!fgets(line, 255, picture)) { motion_log(LOG_ERR, 1, "Could not read from ppm file"); return NULL; } if (strncmp(line, "P5", 2)) { motion_log(LOG_ERR, 1, "This is not a ppm file, starts with '%s'", line); return NULL; } /* skip comment */ line[0] = '#'; while (line[0] == '#') if (!fgets(line, 255, picture)) return NULL; /* check size */ if (sscanf(line, "%d %d", &x, &y) != 2) { motion_log(LOG_ERR, 1, "Failed reading size in pgm file"); return NULL; } if (x != width || y != height) { motion_log(LOG_ERR, 1, "Wrong image size %dx%d should be %dx%d", x, y, width, height); return NULL; } /* Maximum value */ line[0] = '#'; while (line[0] == '#') if (!fgets(line, 255, picture)) return NULL; if (sscanf(line, "%d", &maxval) != 1) { motion_log(LOG_ERR, 1, "Failed reading maximum value in pgm file"); return NULL; } /* read data */ image = mymalloc(width * height); for (y = 0; y < height; y++) { if ((int)fread(&image[y * width], 1, width, picture) != width) motion_log(LOG_ERR, 1, "Failed reading image data from pgm file"); for (x = 0; x < width; x++) image[y * width + x] = (int)image[y * width + x] * 255 / maxval; } return image; }
/* handle irc server connectipn */ void irc_perform(int changesec) { channel_t *ch; unsigned int ss; unsigned int i; unsigned int j; int length; int timeout; updatecontext(); for (ss=0; ss<gdata.networks_online; ++ss) { gnetwork = &(gdata.networks[ss]); if (gdata.needsswitch) { switchserver(-1); continue; } /*----- see if gdata.ircserver is sending anything to us ----- */ if (gnetwork->serverstatus == SERVERSTATUS_CONNECTED) { if (FD_ISSET(gnetwork->ircserver, &gdata.readset)) { char tempbuffa[INPUT_BUFFER_LENGTH]; gnetwork->lastservercontact = gdata.curtime; gnetwork->servertime = 0; memset(&tempbuffa, 0, INPUT_BUFFER_LENGTH); length = readserver_ssl(&tempbuffa, INPUT_BUFFER_LENGTH); if (length < 1) { if (errno != EAGAIN) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_RED, "Closing Server Connection on %s: %s", gnetwork->name, (length<0) ? strerror(errno) : "Closed"); if (gdata.exiting) { gnetwork->recentsent = 0; } close_server(); mydelete(gnetwork->curserveractualname); } continue; } j = strlen(gnetwork->server_input_line); for (i=0; i<(unsigned int)length; ++i) { if ((tempbuffa[i] == '\n') || (j == (INPUT_BUFFER_LENGTH-1))) { if (j && (gnetwork->server_input_line[j-1] == 0x0D)) { --j; } gnetwork->server_input_line[j] = '\0'; ir_parseline(gnetwork->server_input_line); j = 0; } else { gnetwork->server_input_line[j] = tempbuffa[i]; ++j; } } gnetwork->server_input_line[j] = '\0'; } continue; } if (gnetwork->serverstatus == SERVERSTATUS_SSL_HANDSHAKE) { if ((FD_ISSET(gnetwork->ircserver, &gdata.writeset)) || (FD_ISSET(gnetwork->ircserver, &gdata.readset))) { handshake_ssl(); } if (changesec) irc_server_timeout(); continue; } if (gnetwork->serverstatus == SERVERSTATUS_TRYING) { if (FD_ISSET(gnetwork->ircserver, &gdata.writeset)) { int callval_i; int connect_error; SIGNEDSOCK int connect_error_len = sizeof(connect_error); SIGNEDSOCK int addrlen; callval_i = getsockopt(gnetwork->ircserver, SOL_SOCKET, SO_ERROR, &connect_error, &connect_error_len); if (callval_i < 0) { outerror(OUTERROR_TYPE_WARN, "Couldn't determine connection status: %s on %s", strerror(errno), gnetwork->name); close_server(); continue; } if (connect_error) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Server Connection Failed: %s on %s", strerror(connect_error), gnetwork->name); close_server(); continue; } ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Server Connection to %s Established, Logging In", gnetwork->name); gnetwork->serverstatus = SERVERSTATUS_CONNECTED; gnetwork->connecttime = gdata.curtime; gnetwork->botstatus = BOTSTATUS_LOGIN; ch = irlist_get_head(&(gnetwork->channels)); if (ch == NULL) { gnetwork->botstatus = BOTSTATUS_JOINED; start_sends(); } FD_CLR(gnetwork->ircserver, &gdata.writeset); addrlen = sizeof(gnetwork->myip); bzero((char *) &(gnetwork->myip), sizeof(gnetwork->myip)); if (getsockname(gnetwork->ircserver, &(gnetwork->myip.sa), &addrlen) >= 0) { if (gdata.debug > 0) { char *msg; msg = mymalloc(maxtextlength); my_getnameinfo(msg, maxtextlength -1, &(gnetwork->myip.sa)); ioutput(OUT_S, COLOR_YELLOW, "using %s", msg); mydelete(msg); } if (!gnetwork->usenatip) { gnetwork->ourip = ntohl(gnetwork->myip.sin.sin_addr.s_addr); if (gdata.debug > 0) { ioutput(OUT_S, COLOR_YELLOW, "ourip = " IPV4_PRINT_FMT, IPV4_PRINT_DATA(gnetwork->ourip)); } } } else { outerror(OUTERROR_TYPE_WARN, "couldn't get ourip on %s", gnetwork->name); } handshake_ssl(); } if (changesec) irc_server_timeout(); continue; } if (gnetwork->serverstatus == SERVERSTATUS_RESOLVING) { if (FD_ISSET(gnetwork->serv_resolv.sp_fd[0], &gdata.readset)) { res_addrinfo_t remote; length = read(gnetwork->serv_resolv.sp_fd[0], &remote, sizeof(res_addrinfo_t)); kill(gnetwork->serv_resolv.child_pid, SIGKILL); FD_CLR(gnetwork->serv_resolv.sp_fd[0], &gdata.readset); if (length != sizeof(res_addrinfo_t)) { ioutput(OUT_S|OUT_L|OUT_D, COLOR_RED, "Error resolving server %s on %s", gnetwork->curserver.hostname, gnetwork->name); gnetwork->serverstatus = SERVERSTATUS_NEED_TO_CONNECT; } else { /* continue with connect */ if (connectirc2(&remote)) { /* failed */ gnetwork->serverstatus = SERVERSTATUS_NEED_TO_CONNECT; } } } if (changesec) { timeout = irc_server_is_timeout(); if (timeout > 0) { kill(gnetwork->serv_resolv.child_pid, SIGKILL); ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR, "Server Resolve Timed Out (%u seconds) on %s", timeout, gnetwork->name); gnetwork->serverstatus = SERVERSTATUS_NEED_TO_CONNECT; } } continue; } if (gnetwork->offline) continue; if (gnetwork->serverstatus == SERVERSTATUS_NEED_TO_CONNECT) { if (changesec) { timeout = irc_server_is_timeout(); if (timeout > 0) { if (gdata.debug > 0) { ioutput(OUT_S, COLOR_YELLOW, "Reconnecting to server (%u seconds) on %s", timeout, gnetwork->name); } switchserver(-1); } } continue; } } /* networks */ gnetwork = NULL; /* reset after done on all networks */ if (gdata.needsswitch) gdata.needsswitch = 0; }
void subfind_determine_sub_halo_properties(struct unbind_data *d, int num, double *totmass, double *pos, double *vel, double *cm, double *veldisp, double *vmax, double *vmaxrad, double *spin, MyIDType * mostboundid, double *halfmassrad, double *mass_tab) { int i, j, p; double s[3], v[3], max, vel_to_phys, H_of_a, atime, minpot; double lx, ly, lz, dv[3], dx[3], disp; double boxhalf, boxsize, ddxx; sort_r2list *rr_list = 0; int minindex; double mass, maxrad; boxsize = All.BoxSize; boxhalf = 0.5 * boxsize; if(All.ComovingIntegrationOn) { vel_to_phys = 1.0 / All.Time; H_of_a = hubble_function(All.Time); atime = All.Time; } else { vel_to_phys = atime = 1; H_of_a = 0; } for(i = 0, minindex = -1, minpot = 1.0e30; i < num; i++) { p = d[i].index; if(P[p].u.DM_Potential < minpot || minindex == -1) { minpot = P[p].u.DM_Potential; minindex = p; } } for(j = 0; j < 3; j++) pos[j] = P[minindex].Pos[j]; /* pos[] now holds the position of minimum potential */ /* we take it that as the center */ for(i = 0, minindex = -1, minpot = 1.0e30; i < num; i++) { p = d[i].index; if(P[p].v.DM_BindingEnergy < minpot || minindex == -1) { minpot = P[p].v.DM_BindingEnergy; minindex = p; } } *mostboundid = P[minindex].ID; /* let's get bulk velocity and the center-of-mass */ for(j = 0; j < 3; j++) s[j] = v[j] = 0; for(j = 0; j < 6; j++) mass_tab[j] = 0; for(i = 0, mass = 0; i < num; i++) { p = d[i].index; for(j = 0; j < 3; j++) { #ifdef PERIODIC ddxx = NEAREST(P[p].Pos[j] - pos[j]); #else ddxx = P[p].Pos[j] - pos[j]; #endif s[j] += P[p].Mass * ddxx; v[j] += P[p].Mass * P[p].Vel[j]; } mass += P[p].Mass; mass_tab[P[p].Type] += P[p].Mass; } *totmass = mass; for(j = 0; j < 3; j++) { s[j] /= mass; /* center of mass */ v[j] /= mass; vel[j] = vel_to_phys * v[j]; } for(j = 0; j < 3; j++) { s[j] += pos[j]; #ifdef PERIODIC while(s[j] < 0) s[j] += boxsize; while(s[j] >= boxsize) s[j] -= boxsize; #endif cm[j] = s[j]; } disp = lx = ly = lz = 0; rr_list = mymalloc(sizeof(sort_r2list) * num); for(i = 0; i < num; i++) { p = d[i].index; rr_list[i].r = 0; rr_list[i].mass = P[p].Mass; for(j = 0; j < 3; j++) { #ifdef PERIODIC ddxx = NEAREST(P[p].Pos[j] - s[j]); #else ddxx = P[p].Pos[j] - s[j]; #endif dx[j] = atime * ddxx; dv[j] = vel_to_phys * (P[p].Vel[j] - v[j]); dv[j] += H_of_a * dx[j]; disp += P[p].Mass * dv[j] * dv[j]; /* for rotation curve computation, take minimum of potential as center */ #ifdef PERIODIC ddxx = NEAREST(P[p].Pos[j] - pos[j]); #else ddxx = P[p].Pos[j] - pos[j]; #endif ddxx = atime * ddxx; rr_list[i].r += ddxx * ddxx; } lx += P[p].Mass * (dx[1] * dv[2] - dx[2] * dv[1]); ly += P[p].Mass * (dx[2] * dv[0] - dx[0] * dv[2]); lz += P[p].Mass * (dx[0] * dv[1] - dx[1] * dv[0]); rr_list[i].r = sqrt(rr_list[i].r); } *veldisp = sqrt(disp / (3 * mass)); /* convert to 1d velocity dispersion */ spin[0] = lx / mass; spin[1] = ly / mass; spin[2] = lz / mass; qsort(rr_list, num, sizeof(sort_r2list), subfind_compare_dist_rotcurve); *halfmassrad = rr_list[num / 2].r; /* compute cumulative mass */ for(i = 1; i < num; i++) rr_list[i].mass = rr_list[i - 1].mass + rr_list[i].mass; for(i = num - 1, max = 0, maxrad = 0; i > 5; i--) if(rr_list[i].mass / rr_list[i].r > max) { max = rr_list[i].mass / rr_list[i].r; maxrad = rr_list[i].r; } *vmax = sqrt(All.G * max); *vmaxrad = maxrad; myfree(rr_list); }
/* This routine allocates memory for * particle storage, both the collisionless and the SPH particles. * The memory for the ordered binary tree of the timeline * is also allocated. */ void allocate_memory(void) { size_t bytes; double bytes_tot = 0; int NTaskTimesThreads; NTaskTimesThreads = maxThreads * NTask; Exportflag = (int *) mymalloc("Exportflag", NTaskTimesThreads * sizeof(int)); Exportindex = (int *) mymalloc("Exportindex", NTaskTimesThreads * sizeof(int)); Exportnodecount = (int *) mymalloc("Exportnodecount", NTaskTimesThreads * sizeof(int)); Send_count = (int *) mymalloc("Send_count", sizeof(int) * NTask); Send_offset = (int *) mymalloc("Send_offset", sizeof(int) * NTask); Recv_count = (int *) mymalloc("Recv_count", sizeof(int) * NTask); Recv_offset = (int *) mymalloc("Recv_offset", sizeof(int) * NTask); #ifdef VORONOI Mesh_Send_count = (int *) mymalloc("Mesh_Send_count", sizeof(int) * NTask); Mesh_Send_offset = (int *) mymalloc("Mesh_Send_offset", sizeof(int) * NTask); Mesh_Recv_count = (int *) mymalloc("Mesh_Recv_count", sizeof(int) * NTask); Mesh_Recv_offset = (int *) mymalloc("Mesh_Recv_offset", sizeof(int) * NTask); #endif ProcessedFlag = (unsigned char *) mymalloc("ProcessedFlag", bytes = All.MaxPart * sizeof(unsigned char)); bytes_tot += bytes; NextActiveParticle = (int *) mymalloc("NextActiveParticle", bytes = All.MaxPart * sizeof(int)); bytes_tot += bytes; NextInTimeBin = (int *) mymalloc("NextInTimeBin", bytes = All.MaxPart * sizeof(int)); bytes_tot += bytes; PrevInTimeBin = (int *) mymalloc("PrevInTimeBin", bytes = All.MaxPart * sizeof(int)); bytes_tot += bytes; if(All.MaxPart > 0) { if(!(P = (struct particle_data *) mymalloc("P", bytes = All.MaxPart * sizeof(struct particle_data)))) { printf("failed to allocate memory for `P' (%g MB).\n", bytes / (1024.0 * 1024.0)); endrun(1); } bytes_tot += bytes; if(ThisTask == 0) printf("\nAllocated %g MByte for particle storage.\n\n", bytes_tot / (1024.0 * 1024.0)); } if(All.MaxPartSph > 0) { bytes_tot = 0; if(! (SphP = (struct sph_particle_data *) mymalloc("SphP", bytes = All.MaxPartSph * sizeof(struct sph_particle_data)))) { printf("failed to allocate memory for `SphP' (%g MB).\n", bytes / (1024.0 * 1024.0)); endrun(1); } bytes_tot += bytes; if(ThisTask == 0) printf("Allocated %g MByte for storage of SPH data.\n\n", bytes_tot / (1024.0 * 1024.0)); } #ifdef LT_STELLAREVOLUTION if(All.MaxPartMet > 0) { bytes_tot = 0; if(! (MetP = (struct met_particle_data *) mymalloc("MetP", bytes = All.MaxPartMet * sizeof(struct met_particle_data)))) { printf("failed to allocate memory for `MetP' (%g MB).\n", bytes / (1024.0 * 1024.0)); endrun(1); } bytes_tot += bytes; if(ThisTask == 0) printf("Allocated %g MByte for storage of MET data.\n\n", bytes_tot / (1024.0 * 1024.0)); } #endif #if defined(BLACK_HOLES) && defined(DETACH_BLACK_HOLES) if(All.MaxPartBH > 0) { bytes_tot = 0; if(! (BHP = (struct bh_particle_data *) mymalloc("BHP", bytes = All.MaxPartBH * sizeof(struct bh_particle_data)))) { printf("failed to allocate memory for `BHP' (%g MB).\n", bytes / (1024.0 * 1024.0)); endrun(1); } bytes_tot += bytes; if(ThisTask == 0) printf("Allocated %g MByte for storage of BH data.\n\n", bytes_tot / (1024.0 * 1024.0)); } #endif #ifdef WRITE_KEY_FILES if(All.MaxPart > 0) { bytes_tot = 0; KeyIndex = mymalloc("KeyIndex", bytes = All.MaxPart * sizeof(peanokey)); bytes_tot += bytes; NPartPerKey = mymalloc("KeyNpart", bytes = All.MaxPart * sizeof(int)); bytes_tot += bytes; PartKeyOffset = mymalloc("KeyOffset", bytes = All.MaxPart * sizeof(int)); bytes_tot += bytes; if(ThisTask == 0) printf("Allocated %g MByte for storage of KEY data.\n\n", bytes_tot / (1024.0 * 1024.0)); } #endif }
static boolean ngram_read_bin_v5(FILE *fp, NGRAM_INFO *ndata) { int i,n,len; char *w, *p; #ifdef WORDS_INT unsigned short *buf; #endif NGRAM_TUPLE_INFO *t; /* read some info extended from version 5 */ rdn(fp, &(ndata->n), sizeof(int), 1); rdn(fp, &(ndata->dir), sizeof(int), 1); rdn(fp, &(ndata->bigram_index_reversed), sizeof(boolean), 1); jlog("Stat: ngram_read_bin_v5: this is %s %d-gram file\n", (ndata->dir == DIR_LR) ? "forward" : "backward", ndata->n); /* read total info and set max_word_num */ ndata->d = (NGRAM_TUPLE_INFO *)mymalloc(sizeof(NGRAM_TUPLE_INFO) * ndata->n); memset(ndata->d, 0, sizeof(NGRAM_TUPLE_INFO) * ndata->n); for(n=0;n<ndata->n;n++) { rdn(fp, &(ndata->d[n].totalnum), sizeof(NNID), 1); } ndata->max_word_num = ndata->d[0].totalnum; /* read wname */ rdn(fp, &len, sizeof(int), 1); w = mymalloc(len); rdn(fp, w, 1, len); /* assign... */ ndata->wname = (char **)mymalloc(sizeof(char *) * ndata->max_word_num); ndata->wname[0] = NULL; p = w; i = 0; while (p < w + len) { ndata->wname[i++] = p; while(*p != '\0') p++; p++; } if (i != ndata->max_word_num) { jlog("Error: ngram_read_bin_v5: wname error??\n"); return FALSE; } /* read N-gram */ for(n=0;n<ndata->n;n++) { jlog("stat: ngram_read_bin_v5: reading %d-gram\n", n+1); t = &(ndata->d[n]); rdn(fp, &(t->is24bit), sizeof(boolean), 1); rdn(fp, &(t->ct_compaction), sizeof(boolean), 1); rdn(fp, &(t->bgnlistlen), sizeof(NNID), 1); rdn(fp, &(t->context_num), sizeof(NNID), 1); if (n > 0) { if (t->is24bit) { t->bgn_upper = (NNID_UPPER *)mymalloc_big(sizeof(NNID_UPPER), t->bgnlistlen); rdn(fp, t->bgn_upper, sizeof(NNID_UPPER), t->bgnlistlen); t->bgn_lower = (NNID_LOWER *)mymalloc_big(sizeof(NNID_LOWER), t->bgnlistlen); rdn(fp, t->bgn_lower, sizeof(NNID_LOWER), t->bgnlistlen); } else { t->bgn = (NNID *)mymalloc_big(sizeof(NNID), t->bgnlistlen); rdn(fp, t->bgn, sizeof(NNID), t->bgnlistlen); } t->num = (WORD_ID *)mymalloc_big(sizeof(WORD_ID), t->bgnlistlen); #ifdef WORDS_INT rdn_wordid(fp, t->num, t->bgnlistlen, need_conv); #else rdn(fp, t->num, sizeof(WORD_ID), t->bgnlistlen); #endif t->nnid2wid = (WORD_ID *)mymalloc_big(sizeof(WORD_ID), t->totalnum); #ifdef WORDS_INT rdn_wordid(fp, t->nnid2wid, t->totalnum, need_conv); #else rdn(fp, t->nnid2wid, sizeof(WORD_ID), t->totalnum); #endif } else { t->bgn_upper = NULL; t->bgn_lower = NULL; t->bgn = NULL; t->num = NULL; t->bgnlistlen = 0; t->nnid2wid = NULL; } t->prob = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), t->totalnum); rdn(fp, t->prob, sizeof(LOGPROB), t->totalnum); rdn(fp, &i, sizeof(int), 1); if (i == 1) { t->bo_wt = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), t->context_num); rdn(fp, t->bo_wt, sizeof(LOGPROB), t->context_num); } else { t->bo_wt = NULL; } rdn(fp, &i, sizeof(int), 1); if (i == 1) { t->nnid2ctid_upper = (NNID_UPPER *)mymalloc_big(sizeof(NNID_UPPER), t->totalnum); t->nnid2ctid_lower = (NNID_LOWER *)mymalloc_big(sizeof(NNID_LOWER), t->totalnum); rdn(fp, t->nnid2ctid_upper, sizeof(NNID_UPPER), t->totalnum); rdn(fp, t->nnid2ctid_lower, sizeof(NNID_LOWER), t->totalnum); } else { t->nnid2ctid_upper = NULL; t->nnid2ctid_lower = NULL; } } rdn(fp, &i, sizeof(int), 1); if (i == 1) { ndata->bo_wt_1 = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), ndata->d[0].context_num); rdn(fp, ndata->bo_wt_1, sizeof(LOGPROB), ndata->d[0].context_num); } else { ndata->bo_wt_1 = NULL; } rdn(fp, &i, sizeof(int), 1); if (i == 1) { jlog("Stat: ngram_read_bin_v5: reading additional LR 2-gram\n"); ndata->p_2 = (LOGPROB *)mymalloc_big(sizeof(LOGPROB), ndata->d[1].totalnum); rdn(fp, ndata->p_2, sizeof(LOGPROB), ndata->d[1].totalnum); } else { ndata->p_2 = NULL; } return TRUE; }
/* start a transfer now */ static void fetch_now(const userinput *const u, const char *uploaddir, char *name, char *url) { off_t resumesize; fetch_curl_t *ft; char *fullfile; FILE *writefd; struct stat s; int retval; resumesize = 0; fullfile = mystrjoin(uploaddir, name, '/'); writefd = fopen(fullfile, "w+x"); /* NOTRANSLATE */ if ((writefd == NULL) && (errno == EEXIST)) { retval = stat(fullfile, &s); if (retval < 0) { outerror(OUTERROR_TYPE_WARN_LOUD, "Cant Stat Upload File '%s': %s", fullfile, strerror(errno)); a_respond(u, "File Error, File couldn't be opened for writing"); mydelete(fullfile); return; } resumesize = s.st_size; writefd = fopen(fullfile, "a+"); /* NOTRANSLATE */ } if (writefd == NULL) { outerror(OUTERROR_TYPE_WARN_LOUD, "Cant Access Upload File '%s': %s", fullfile, strerror(errno)); a_respond(u, "File Error, File couldn't be opened for writing"); mydelete(fullfile); return; } updatecontext(); ft = irlist_add(&fetch_trans, sizeof(fetch_curl_t)); ft->u.method = u->method; if (u->snick != NULL) { ft->u.snick = mystrdup(u->snick); } ft->u.fd = u->fd; ft->u.chat = u->chat; ft->id = ++fetch_id; ft->net = gnetwork->net; ft->name = mystrdup(name); ft->url = mystrdup(url); ft->uploaddir = mystrdup(uploaddir); ft->fullname = fullfile; fullfile = NULL; ft->writefd = writefd; ft->resumesize = resumesize; ft->errorbuf = mymalloc(CURL_ERROR_SIZE); ft->errorbuf[0] = 0; ft->starttime = gdata.curtime; if (curl_fetch(u, ft)) { clean_fetch(ft); return; } a_respond(u, "fetch '%s' started", ft->name); ++fetch_started; }
void* g_memdup(const void* src, size_t s) { void* dst = mymalloc(s); memcpy(dst, src, s); return dst; }
/** * <JA> * GMMの計算のための初期化. 起動時に一度だけ呼ばれる. * * @param recog [i/o] エンジンインスタンス * </JA> * <EN> * Initialization for computing GMM likelihoods. This will be called * once on startup. * * @param recog [i/o] engine instance * </EN> * * @callgraph * @callergraph * */ boolean gmm_init(Recog *recog) { HTK_HMM_INFO *gmm; HTK_HMM_Data *d; GMMCalc *gc; int i; gmm = recog->gmm; /* check GMM format */ /* tied-mixture GMM is not supported */ if (gmm->is_tied_mixture) { jlog("ERROR: gmm_init: tied-mixture GMM is not supported\n"); return FALSE; } /* assume 3 state GMM (only one output state) */ for(d=gmm->start;d;d=d->next) { if (d->state_num > 3) { jlog("ERROR: gmm_init: more than three states (one output state) defined in GMM [%s]\n", d->name); return FALSE; } } /* check if CMN needed */ /* allocate work area */ if (recog->gc == NULL) { gc = (GMMCalc *)mymalloc(sizeof(GMMCalc)); recog->gc = gc; } else { gc = recog->gc; } /* allocate buffers */ gc->gmm_score = (LOGPROB *)mymalloc(sizeof(LOGPROB) * gmm->totalhmmnum); #ifdef GMM_VAD gc->nframe = recog->jconf->detect.gmm_margin; gc->rates = (LOGPROB *)mymalloc(sizeof(LOGPROB) * gc->nframe); #endif gc->is_voice = (boolean *)mymalloc(sizeof(boolean) * gmm->totalhmmnum); i = 0; if (recog->jconf->reject.gmm_reject_cmn_string) { for(d=recog->gmm->start;d;d=d->next) { if (strstr(recog->jconf->reject.gmm_reject_cmn_string, d->name)) { gc->is_voice[i] = FALSE; } else { gc->is_voice[i] = TRUE; } i++; } } else { for(d=recog->gmm->start;d;d=d->next) { gc->is_voice[i] = TRUE; i++; } } /* initialize work area */ gc->OP_nstream = gmm->opt.stream_info.num; for(i=0;i<gc->OP_nstream;i++) { gc->OP_veclen_stream[i] = gmm->opt.stream_info.vsize[i]; } gmm_gprune_safe_init(gc, gmm, recog->jconf->reject.gmm_gprune_num); /* check if variances are inversed */ if (!gmm->variance_inversed) { /* here, inverse all variance values for faster computation */ htk_hmm_inverse_variances(gmm); gmm->variance_inversed = TRUE; } return TRUE; }
void initscreen(int startup, int clear) { struct winsize win; char *tempstr; struct termios tio; updatecontext(); if (gdata.background == 2) return; /* clear */ gdata.attop = 0; if ( gdata.noscreen ) return; if (clear) { tostdout(IRVT_CURSOR_HOME0 IRVT_ERASE_DOWN IRVT_SCROLL_ALL); } gdata.termlines = 80; gdata.termcols = 24; if (isatty(fileno(stdin)) == 0) { outerror(OUTERROR_TYPE_CRASH, "cannot use foreground mode on a non-terminal"); } if ((ioctl(0, TIOCGWINSZ, &win) == 0) && win.ws_col && win.ws_row) { gdata.termcols = win.ws_col; gdata.termlines = win.ws_row; } if (tcgetattr(fileno(stdin), &tio) < 0) { outerror(OUTERROR_TYPE_CRASH, "can't get terminal settings: %s", strerror(errno)); } if (startup) { gdata.startup_tio = tio; } tio.c_lflag &= ~(ECHO | ICANON); tio.c_cc[VMIN] = 0; tio.c_cc[VTIME] = 4; if (tcsetattr(fileno(stdin), TCSANOW, &tio) < 0) { outerror(OUTERROR_TYPE_CRASH, "can't set terminal settings: %s", strerror(errno)); } /* last 2 lines */ tempstr = mymalloc(maxtextlength); getstatusline(tempstr,maxtextlength); tempstr[between(0,gdata.termcols-4,maxtextlength-1)] = '\0'; tostdout(IRVT_CURSOR_HOME1 "[ %-*s ]", gdata.termlines - 1, gdata.termcols - 4, tempstr); mydelete(tempstr); drawbot(); /* scrolling */ tostdout(IRVT_SCROLL_LINES1, gdata.termlines - 2); }
boolean aptree_write(FILE *fp, APATNODE *root, boolean (*save_data_func)(void *, FILE *fp)) { int count_node, count_branch, count_data, maxbit; int *left, *right, *value; int num, did; boolean err; if (root == NULL) return TRUE; /* count statistics */ count_branch = count_data = 0; maxbit = 0; aptree_count(root, &count_branch, &count_data, &maxbit); count_node = count_branch + count_data; jlog("Stat: aptree_write: %d nodes (%d branch + %d data), maxbit=%d\n", count_node, count_branch, count_data, maxbit); /* allocate */ left = (int *)mymalloc(sizeof(int) * count_node); right = (int *)mymalloc(sizeof(int) * count_node); value = (int *)mymalloc(sizeof(int) * count_node); /* make index */ did = num = 0; aptree_build_index(root, &num, &did, left, right, value); #if 0 { int i; for(i=0;i<count_node;i++) { printf("%d: %d %d %d\n", i, left[i], right[i], value[i]); } } #endif /* write tree to file */ if (myfwrite(&count_node, sizeof(int), 1, fp) < 1) { jlog("Error: aptree_write: fail to write header\n"); return FALSE; } if (myfwrite(&count_data, sizeof(int), 1, fp) < 1) { jlog("Error: aptree_write: fail to write header\n"); return FALSE; } if (myfwrite(left, sizeof(int), count_node, fp) < count_node) { jlog("Error: aptree_write: fail to write %d bytes\n", sizeof(int) * count_node); return FALSE; } if (myfwrite(right, sizeof(int), count_node, fp) < count_node) { jlog("Error: aptree_write: fail to write %d bytes\n", sizeof(int) * count_node); return FALSE; } if (myfwrite(value, sizeof(int), count_node, fp) < count_node) { jlog("Error: aptree_write: fail to write %d bytes\n", sizeof(int) * count_node); return FALSE; } if (save_data_func != NULL) { /* write leaf node data */ err = FALSE; aptree_write_leaf(fp, root, save_data_func, &err); } if (err) { jlog("Error: aptree_write: error occured when writing tree leaf data\n"); return FALSE; } free(value); free(right); free(left); return TRUE; }
/********************************************************************** * public interface dict_mysql_lookup * find database entry return 0 if no alias found, set dict_errno * on errors to DICT_ERRBO_RETRY and set dict_errno to 0 on success *********************************************************************/ static const char *dict_mysql_lookup(DICT *dict, const char *name) { MYSQL_RES *query_res; MYSQL_ROW row; DICT_MYSQL *dict_mysql; PLMYSQL *pldb; static VSTRING *result; static VSTRING *query = 0; int i, j, numrows; char *name_escaped = 0; dict_mysql = (DICT_MYSQL *) dict; pldb = dict_mysql->pldb; /* initialization for query */ query = vstring_alloc(24); vstring_strcpy(query, ""); if ((name_escaped = (char *) mymalloc((sizeof(char) * (strlen(name) * 2) +1))) == NULL) { msg_fatal("dict_mysql_lookup: out of memory."); } /* prepare the query */ mysql_escape_string(name_escaped, name, (unsigned int) strlen(name)); vstring_sprintf(query, "select %s from %s where %s = '%s' %s", dict_mysql->name->select_field, dict_mysql->name->table, dict_mysql->name->where_field, name_escaped, dict_mysql->name->additional_conditions); if (msg_verbose) msg_info("dict_mysql_lookup using sql query: %s", vstring_str(query)); /* free mem associated with preparing the query */ myfree(name_escaped); /* do the query - set dict_errno & cleanup if there's an error */ if ((query_res = plmysql_query(pldb, vstring_str(query), dict_mysql->name->dbname, dict_mysql->name->username, dict_mysql->name->password)) == 0) { dict_errno = DICT_ERR_RETRY; vstring_free(query); return 0; } dict_errno = 0; /* free the vstring query */ vstring_free(query); numrows = mysql_num_rows(query_res); if (msg_verbose) msg_info("dict_mysql_lookup: retrieved %d rows", numrows); if (numrows == 0) { mysql_free_result(query_res); return 0; } if (result == 0) result = vstring_alloc(10); vstring_strcpy(result, ""); for (i = 0; i < numrows; i++) { row = mysql_fetch_row(query_res); if (i > 0) vstring_strcat(result, ","); for (j = 0; j < mysql_num_fields(query_res); j++) { if (row[j] == 0) { if (msg_verbose > 1) msg_info("dict_mysql_lookup: null field #%d row #%d", j, i); mysql_free_result(query_res); return (0); } if (j > 0) vstring_strcat(result, ","); vstring_strcat(result, row[j]); if (msg_verbose > 1) msg_info("dict_mysql_lookup: retrieved field: %d: %s", j, row[j]); } } mysql_free_result(query_res); return vstring_str(result); }
boolean aptree_read(FILE *fp, APATNODE **root, BMALLOC_BASE **mroot, void *data, boolean (*load_data_func)(void **, void *, FILE *)) { int count_node, count_branch, count_data, maxbit; int *left, *right, *value; int num, did; boolean err; APATNODE *nodelist; APATNODE *node; int i; if (*root != NULL) { jlog("Error: aptree_read: root node != NULL!\n"); return FALSE; } /* read header */ if (myfread(&count_node, sizeof(int), 1, fp) < 1) { jlog("Error: aptree_read: fail to read header\n"); return FALSE; } if (myfread(&count_data, sizeof(int), 1, fp) < 1) { jlog("Error: aptree_read: fail to read header\n"); return FALSE; } jlog("Stat: aptree_read: %d nodes (%d branch + %d data)\n", count_node, count_node - count_data, count_data); /* prepare buffer */ left = (int *)mymalloc(sizeof(int) * count_node); right = (int *)mymalloc(sizeof(int) * count_node); value = (int *)mymalloc(sizeof(int) * count_node); /* read data */ if (myfread(left, sizeof(int), count_node, fp) < count_node) { jlog("Error: aptree_read: fail to read %d bytes\n", sizeof(int) * count_node); return FALSE; } if (myfread(right, sizeof(int), count_node, fp) < count_node) { jlog("Error: aptree_read: fail to read %d bytes\n", sizeof(int) * count_node); return FALSE; } if (myfread(value, sizeof(int), count_node, fp) < count_node) { jlog("Error: aptree_read: fail to read %d bytes\n", sizeof(int) * count_node); return FALSE; } /* allocate nodes */ nodelist = (APATNODE *)mybmalloc2(sizeof(APATNODE) * count_node, mroot); for(i=0;i<count_node;i++) { node = &(nodelist[i]); if (left[i] == -1) { node->left0 = NULL; } else { node->left0 = &(nodelist[left[i]]); } if (right[i] == -1) { node->right1 = NULL; } else { node->right1 = &(nodelist[right[i]]); } if (left[i] == -1 && right[i] == -1) { /* load leaf data node */ if ((*load_data_func)(&(node->value.data), data, fp) == FALSE) { jlog("Error: aptree_read: failed to load leaf data entity\n"); return FALSE; } } else { /* set thres bit */ node->value.thres_bit = value[i]; } } /* set root node */ *root = &(nodelist[0]); free(value); free(right); free(left); return TRUE; }
//ATK-RM04 串口以太网测试 //用于测试TCP/UDP连接 //返回值:0,正常 // 其他,错误代码 u8 atk_rm04_cometh_test(void) { u8 netpro=0; //网络模式 u8 key; u8 timex=0; u8 ipbuf[16]; //IP缓存 u8 *p; u16 t=999; //加速第一次获取链接状态 u8 res=0; u16 rlen=0; u8 constate=0; //连接状态 p=mymalloc(SRAMIN,32); //申请32字节内存 atk_rm04_send_cmd("at+netmode=1","ok",500); //设置串口以太网模式 atk_rm04_send_cmd("at+dhcpd=0","ok",500); //DHCP服务器关闭(仅AP模式有效) atk_rm04_send_cmd("at+dhcpc=1","ok",500); //DHCP客户端使能(net_ip无效) PRESTA: netpro=atk_rm04_netpro_sel(50,30,(u8*)ATK_RM04_NETMODE_TBL[1]); //选择网络模式 if(netpro&0X02)atk_rm04_send_cmd("at+remotepro=udp","ok",500); //UDP协议 else atk_rm04_send_cmd("at+remotepro=tcp","ok",500); //TCP协议 sprintf((char*)p,"at+remoteport=%s",portnum); atk_rm04_send_cmd(p,"ok",500); //设置 端口号. if(netpro&0X01) //客户端 { if(atk_rm04_ip_set("ETH-COM 远端IP设置",(u8*)ATK_RM04_WORKMODE_TBL[netpro],(u8*)portnum,ipbuf))goto PRESTA; //IP输入 sprintf((char*)p,"at+remoteip=%s",ipbuf); atk_rm04_send_cmd(p,"ok",500); //设置远端(连接)IP地址. atk_rm04_send_cmd("at+mode=client","ok",500); //设置为客户端 }else atk_rm04_send_cmd("at+mode=server","ok",500); //设置为服务端 LCD_Clear(WHITE); POINT_COLOR=RED; Show_Str_Mid(0,30,"ATK-RM04 ETH-COM 测试",16,240); Show_Str(30,50,200,16,"正在配置ATK-RM04模块,请稍等...",12,0); if(atk_rm04_send_cmd("at+net_commit=1","\r\n",4000))//提交网络配置,最长可能需要等待40s { LCD_Fill(30,50,239,50+12,WHITE); //清除之前的显示 Show_Str(30,50,200,16,"配置ATK-RM04模块失败!",12,0); delay_ms(800); res=1; }else { atk_rm04_send_cmd("at+reconn=1","ok",500); //重启串口转换服务 LCD_Fill(30,50,239,50+12,WHITE);//清除之前的显示 Show_Str(30,50,200,16,"配置ATK-RM04模块成功!",12,0); delay_ms(600); Show_Str(30,50,210,16,"KEY_UP:退出测试 KEY0:发送数据",12,0); atk_rm04_quit_trans(); //退出透传 while(1) //等待ATK-RM04连接上路由器 { atk_rm04_get_wanip(p); //获取WAN IP if(p[0]!=0)break; //成功获取到了IP地址 Show_Str(30,80,200,12,"ATK-RM04 连接路由器失败",12,0); //连接失败 delay_ms(800); Show_Str(30,80,200,12,"ATK-RM04 等待连接中....",12,0); delay_ms(800); } LCD_Fill(30,80,239,80+12,WHITE); if((netpro&0X01)==0)atk_rm04_get_wanip(ipbuf);//服务器模式,获取WAN IP sprintf((char*)p,"IP地址:%s 端口:%s",ipbuf,(u8*)portnum); Show_Str(30,65,200,12,p,12,0); //显示IP地址和端口 Show_Str(30,80,200,12,"状态:",12,0); //连接状态 Show_Str(120,80,200,12,"模式:",12,0); //连接状态 Show_Str(30,100,200,12,"发送数据:",12,0); //发送数据 Show_Str(30,115,200,12,"接收数据:",12,0); //接收数据 POINT_COLOR=BLUE; Show_Str(120+30,80,200,12,(u8*)ATK_RM04_WORKMODE_TBL[netpro],12,0); //连接状态 USART3_RX_STA=0; while(1) { key=KEY_Scan(0); if(key==WKUP_PRES) //KEY_UP 退出测试 { res=0; break; }else if(key==KEY0_PRES) //KEY0 发送数据 { sprintf((char*)p,"ATK-RM04 %s测试%02d\r\n",ATK_RM04_WORKMODE_TBL[netpro],t/10);//测试数据 Show_Str(30+54,100,200,12,p,12,0); u3_printf("%s",p); //发送该数据到ATK-RM04模块 timex=100; } if(timex)timex--; if(timex==1)LCD_Fill(30+54,100,239,112,WHITE); t++; delay_ms(10); if(USART3_RX_STA&0X8000) //接收到一次数据了 { rlen=USART3_RX_STA&0X7FFF; //得到本次接收到的数据长度 USART3_RX_BUF[rlen]=0; //添加结束符 printf("%s",USART3_RX_BUF); //发送到串口 sprintf((char*)p,"收到%d字节,内容如下",rlen);//接收到的字节数 LCD_Fill(30+54,115,239,130,WHITE); POINT_COLOR=BRED; Show_Str(30+54,115,156,12,p,12,0); //显示接收到的数据长度 POINT_COLOR=BLUE; LCD_Fill(30,130,239,319,WHITE); Show_Str(30,130,180,190,USART3_RX_BUF,12,0);//显示接收到的数据 USART3_RX_STA=0; if(constate==0)t=1000; //状态为还未连接,立即更新连接状态 else t=0; //状态为已经连接了,10秒后再检查 } if(t==1000)//连续10秒钟没有收到任何数据,检查连接是不是还存在. { constate=atk_rm04_consta_check()-'0';//得到连接状态 if(constate)Show_Str(30+30,80,200,12,"连接成功",12,0); //连接状态 else Show_Str(30+30,80,200,12,"连接失败",12,0); t=0; } if((t%20)==0)LED0=!LED0; atk_rm04_at_response(1); } } myfree(SRAMIN,p); //释放内存 atk_rm04_quit_trans(); //退出透传 return res; }
int subfind_process_group_serial(int gr, int Offs) { int i, j, k, p, len, subnr, totlen, ss, ngbs, ndiff, N, head = 0, head_attach, count_cand; int listofdifferent[2], count, prev; int ngb_index, part_index, nsubs, rank; double SubMass, SubPos[3], SubVel[3], SubCM[3], SubVelDisp, SubVmax, SubVmaxRad, SubSpin[3], SubHalfMass, SubMassTab[6]; MyIDType SubMostBoundID; static struct unbind_data *ud; while(P[Offs].GrNr != Group[gr].GrNr) { Offs++; if(Offs >= NumPart) { printf("don't find a particle for groupnr=%d\n", Group[gr].GrNr); endrun(312); } } N = Group[gr].Len; GrNr = Group[gr].GrNr; for(i = 0; i < N; i++) { if(P[Offs + i].GrNr != Group[gr].GrNr) { printf ("task=%d, gr=%d: don't have the number of particles for GrNr=%d group-len=%d found=%d before=%d\n", ThisTask, gr, Group[gr].GrNr, N, P[Offs + i].GrNr, P[Offs - 1].GrNr); endrun(312); } } candidates = mymalloc(N * sizeof(struct cand_dat)); Head = mymalloc(N * sizeof(int)); Next = mymalloc(N * sizeof(int)); Tail = mymalloc(N * sizeof(int)); Len = mymalloc(N * sizeof(int)); ud = mymalloc(N * sizeof(struct unbind_data)); Head -= Offs; Next -= Offs; Tail -= Offs; Len -= Offs; for(i = 0; i < N; i++) { ud[i].index = Offs + i; } subfind_loctree_findExtent(N, ud); subfind_loctree_treebuild(N, ud); /* build tree for all particles of this group */ for(i = Offs; i < Offs + N; i++) Head[i] = Next[i] = Tail[i] = -1; /* note: particles are already ordered in the order of decreasing density */ for(i = 0, count_cand = 0; i < N; i++) { part_index = Offs + i; subfind_locngb_treefind(P[part_index].Pos, All.DesLinkNgb, P[part_index].DM_Hsml); /* note: returned neighbours are already sorted by distance */ for(k = 0, ndiff = 0, ngbs = 0; k < All.DesLinkNgb && ngbs < MAX_NGB_CHECK && ndiff < 2; k++) { ngb_index = R2list[k].index; if(ngb_index != part_index) /* to exclude the particle itself */ { /* we only look at neighbours that are denser */ if(P[ngb_index].u.DM_Density > P[part_index].u.DM_Density) { ngbs++; if(Head[ngb_index] >= 0) /* neighbor is attached to a group */ { if(ndiff == 1) if(listofdifferent[0] == Head[ngb_index]) continue; /* a new group has been found */ listofdifferent[ndiff++] = Head[ngb_index]; } else { printf("this may not occur.\n"); printf ("ThisTask=%d gr=%d k=%d i=%d part_index=%d ngb_index = %d head[ngb_index]=%d P[part_index].DM_Density=%g %g GrNrs= %d %d \n", ThisTask, gr, k, i, part_index, ngb_index, Head[ngb_index], P[part_index].u.DM_Density, P[ngb_index].u.DM_Density, P[part_index].GrNr, P[ngb_index].GrNr); endrun(2); } } } } switch (ndiff) /* treat the different possible cases */ { case 0: /* this appears to be a lonely maximum -> new group */ head = part_index; Head[part_index] = Tail[part_index] = part_index; Len[part_index] = 1; Next[part_index] = -1; break; case 1: /* the particle is attached to exactly one group */ head = listofdifferent[0]; Head[part_index] = head; Next[Tail[head]] = part_index; Tail[head] = part_index; Len[head]++; Next[part_index] = -1; break; case 2: /* the particle merges two groups together */ head = listofdifferent[0]; head_attach = listofdifferent[1]; if(Len[head_attach] > Len[head]) /* other group is longer, swap them */ { head = listofdifferent[1]; head_attach = listofdifferent[0]; } /* only in case the attached group is long enough we bother to register is as a subhalo candidate */ if(Len[head_attach] >= All.DesLinkNgb) { candidates[count_cand].len = Len[head_attach]; candidates[count_cand].head = Head[head_attach]; count_cand++; } /* now join the two groups */ Next[Tail[head]] = head_attach; Tail[head] = Tail[head_attach]; Len[head] += Len[head_attach]; ss = head_attach; do { Head[ss] = head; } while((ss = Next[ss]) >= 0); /* finally, attach the particle */ Head[part_index] = head; Next[Tail[head]] = part_index; Tail[head] = part_index; Len[head]++; Next[part_index] = -1; break; default: printf("can't be! (a)\n"); endrun(1); break; } } /* add the full thing as a subhalo candidate */ for(i = 0, prev = -1; i < N; i++) { if(Head[Offs + i] == Offs + i) if(Next[Tail[Offs + i]] == -1) { if(prev < 0) head = Offs + i; if(prev >= 0) Next[prev] = Offs + i; prev = Tail[Offs + i]; } } candidates[count_cand].len = N; candidates[count_cand].head = head; count_cand++; /* go through them once and assign the rank */ for(i = 0, p = head, rank = 0; i < N; i++) { Len[p] = rank++; p = Next[p]; } /* for each candidate, we now pull out the rank of its head */ for(k = 0; k < count_cand; k++) candidates[k].rank = Len[candidates[k].head]; for(i = Offs; i < Offs + N; i++) Tail[i] = -1; for(k = 0, nsubs = 0; k < count_cand; k++) { for(i = 0, p = candidates[k].head, len = 0; i < candidates[k].len; i++, p = Next[p]) if(Tail[p] < 0) ud[len++].index = p; if(len >= All.DesLinkNgb) len = subfind_unbind(ud, len); if(len >= All.DesLinkNgb) { /* ok, we found a substructure */ for(i = 0; i < len; i++) Tail[ud[i].index] = nsubs; /* we use this to flag the substructures */ candidates[k].nsub = nsubs; candidates[k].bound_length = len; nsubs++; } else { candidates[k].nsub = -1; candidates[k].bound_length = 0; } } #ifdef VERBOSE printf("\nGroupLen=%d (gr=%d)\n", N, gr); printf("Number of substructures: %d\n", nsubs); #endif Group[gr].Nsubs = nsubs; Group[gr].Pos[0] = Group[gr].CM[0]; Group[gr].Pos[1] = Group[gr].CM[1]; Group[gr].Pos[2] = Group[gr].CM[2]; qsort(candidates, count_cand, sizeof(struct cand_dat), subfind_compare_serial_candidates_boundlength); /* now we determine the parent subhalo for each candidate */ for(k = 0; k < count_cand; k++) { candidates[k].subnr = k; candidates[k].parent = 0; } qsort(candidates, count_cand, sizeof(struct cand_dat), subfind_compare_serial_candidates_rank); for(k = 0; k < count_cand; k++) { for(j = k + 1; j < count_cand; j++) { if(candidates[j].rank > candidates[k].rank + candidates[k].len) break; if(candidates[k].rank + candidates[k].len >= candidates[j].rank + candidates[j].len) { if(candidates[k].bound_length >= All.DesLinkNgb) candidates[j].parent = candidates[k].subnr; } else { printf("k=%d|%d has rank=%d and len=%d. j=%d has rank=%d and len=%d bound=%d\n", k, count_cand, (int) candidates[k].rank, candidates[k].len, (int) candidates[k].bound_length, candidates[j].rank, (int) candidates[j].len, candidates[j].bound_length); endrun(121235513); } } } qsort(candidates, count_cand, sizeof(struct cand_dat), subfind_compare_serial_candidates_subnr); /* now determine the properties */ for(k = 0, subnr = 0, totlen = 0; k < nsubs; k++) { len = candidates[k].bound_length; #ifdef VERBOSE printf("subnr=%d SubLen=%d\n", subnr, len); #endif totlen += len; for(i = 0, p = candidates[k].head, count = 0; i < candidates[k].len; i++) { if(Tail[p] == candidates[k].nsub) ud[count++].index = p; p = Next[p]; } if(count != len) endrun(12); subfind_determine_sub_halo_properties(ud, len, &SubMass, &SubPos[0], &SubVel[0], &SubCM[0], &SubVelDisp, &SubVmax, &SubVmaxRad, &SubSpin[0], &SubMostBoundID, &SubHalfMass, &SubMassTab[0]); if(Nsubgroups >= MaxNsubgroups) endrun(899); if(subnr == 0) { for(j = 0; j < 3; j++) Group[gr].Pos[j] = SubPos[j]; } SubGroup[Nsubgroups].Len = len; if(subnr == 0) SubGroup[Nsubgroups].Offset = Group[gr].Offset; else SubGroup[Nsubgroups].Offset = SubGroup[Nsubgroups - 1].Offset + SubGroup[Nsubgroups - 1].Len; SubGroup[Nsubgroups].GrNr = GrNr - 1; SubGroup[Nsubgroups].SubNr = subnr; SubGroup[Nsubgroups].SubParent = candidates[k].parent; SubGroup[Nsubgroups].Mass = SubMass; SubGroup[Nsubgroups].SubMostBoundID = SubMostBoundID; SubGroup[Nsubgroups].SubVelDisp = SubVelDisp; SubGroup[Nsubgroups].SubVmax = SubVmax; SubGroup[Nsubgroups].SubVmaxRad = SubVmaxRad; SubGroup[Nsubgroups].SubHalfMass = SubHalfMass; for(j = 0; j < 3; j++) { SubGroup[Nsubgroups].Pos[j] = SubPos[j]; SubGroup[Nsubgroups].CM[j] = SubCM[j]; SubGroup[Nsubgroups].Vel[j] = SubVel[j]; SubGroup[Nsubgroups].Spin[j] = SubSpin[j]; } #ifdef SAVE_MASS_TAB for(j = 0; j < 6; j++) SubGroup[Nsubgroups].MassTab[j] = SubMassTab[j]; #endif Nsubgroups++; /* Let's now assign the subgroup number */ for(i = 0; i < len; i++) P[ud[i].index].SubNr = subnr; subnr++; } #ifdef VERBOSE printf("Fuzz=%d\n", N - totlen); #endif myfree(ud); myfree(Len + Offs); myfree(Tail + Offs); myfree(Next + Offs); myfree(Head + Offs); myfree(candidates); return Offs; }
/** * Build filterbank information and generate tables for MFCC comptutation. * * @param w [i/o] MFCC calculation work area * @param para [in] configuration parameters * * @return the generated filterbank information. */ boolean InitFBank(MFCCWork *w, Value *para) { float mlo, mhi, ms, melk; int k, chan, maxChan, nv2; /* Calculate FFT size */ w->fb.fftN = 2; w->fb.n = 1; while(para->framesize > w->fb.fftN){ w->fb.fftN *= 2; w->fb.n++; } nv2 = w->fb.fftN / 2; w->fb.fres = 1.0E7 / (para->smp_period * w->fb.fftN * 700.0); maxChan = para->fbank_num + 1; w->fb.klo = 2; w->fb.khi = nv2; mlo = 0; mhi = Mel(nv2 + 1, w->fb.fres); /* lo pass filter */ if (para->lopass >= 0) { mlo = 1127*log(1+(float)para->lopass/700.0); w->fb.klo = ((float)para->lopass * para->smp_period * 1.0e-7 * w->fb.fftN) + 2.5; if (w->fb.klo<2) w->fb.klo = 2; } /* hi pass filter */ if (para->hipass >= 0) { mhi = 1127*log(1+(float)para->hipass/700.0); w->fb.khi = ((float)para->hipass * para->smp_period * 1.0e-7 * w->fb.fftN) + 0.5; if (w->fb.khi>nv2) w->fb.khi = nv2; } /* Create vector of fbank centre frequencies */ w->fb.cf = (float *)mymalloc((maxChan + 1) * sizeof(float)); ms = mhi - mlo; for (chan = 1; chan <= maxChan; chan++) w->fb.cf[chan] = ((float)chan / maxChan)*ms + mlo; if (para->vtln_alpha != 1.0) { /* Modify fbank center frequencies for VTLN */ if (VTLN_recreate_fbank_cf(w->fb.cf, para, mlo, mhi, maxChan) == FALSE) { return FALSE; } } /* Create loChan map, loChan[fftindex] -> lower channel index */ w->fb.loChan = (short *)mymalloc((nv2 + 1) * sizeof(short)); for(k = 1, chan = 1; k <= nv2; k++){ if (k < w->fb.klo || k > w->fb.khi) w->fb.loChan[k] = -1; else { melk = Mel(k, w->fb.fres); while (w->fb.cf[chan] < melk && chan <= maxChan) ++chan; w->fb.loChan[k] = chan - 1; } } /* Create vector of lower channel weights */ w->fb.loWt = (float *)mymalloc((nv2 + 1) * sizeof(float)); for(k = 1; k <= nv2; k++) { chan = w->fb.loChan[k]; if (k < w->fb.klo || k > w->fb.khi) w->fb.loWt[k] = 0.0; else { if (chan > 0) w->fb.loWt[k] = (w->fb.cf[chan + 1] - Mel(k, w->fb.fres)) / (w->fb.cf[chan + 1] - w->fb.cf[chan]); else w->fb.loWt[k] = (w->fb.cf[1] - Mel(k, w->fb.fres)) / (w->fb.cf[1] - mlo); } } /* Create workspace for fft */ w->fb.Re = (float *)mymalloc((w->fb.fftN + 1) * sizeof(float)); w->fb.Im = (float *)mymalloc((w->fb.fftN + 1) * sizeof(float)); w->sqrt2var = sqrt(2.0 / para->fbank_num); return TRUE; }
int subfind_unbind(struct unbind_data *ud, int len) { double *bnd_energy, energy_limit, weakly_bound_limit = 0; int i, j, p, minindex, unbound, phaseflag; double ddxx, s[3], dx[3], v[3], dv[3], pos[3]; double vel_to_phys, H_of_a, atime, pot, minpot = 0; double boxsize, boxhalf; double TotMass; boxsize = All.BoxSize; boxhalf = 0.5 * All.BoxSize; if(All.ComovingIntegrationOn) { vel_to_phys = 1.0 / All.Time; H_of_a = hubble_function(All.Time); atime = All.Time; } else { vel_to_phys = atime = 1; H_of_a = 0; } bnd_energy = (double *) mymalloc(len * sizeof(double)); phaseflag = 0; /* this means we will recompute the potential for all particles */ do { subfind_loctree_treebuild(len, ud); /* let's compute the potential */ if(phaseflag == 0) /* redo it for all the particles */ { for(i = 0, minindex = -1, minpot = 1.0e30; i < len; i++) { p = ud[i].index; pot = subfind_loctree_treeevaluate_potential(p); /* note: add self-energy */ P[p].u.DM_Potential = pot + P[p].Mass / All.SofteningTable[P[p].Type]; P[p].u.DM_Potential *= All.G / atime; if(All.TotN_gas > 0 && (FOF_PRIMARY_LINK_TYPES & 1) == 0 && All.OmegaBaryon > 0) P[p].u.DM_Potential *= All.Omega0 / (All.Omega0 - All.OmegaBaryon); if(P[p].u.DM_Potential < minpot || minindex == -1) { minpot = P[p].u.DM_Potential; minindex = p; } } for(j = 0; j < 3; j++) pos[j] = P[minindex].Pos[j]; /* position of minimum potential */ } else { /* we only repeat for those close to the unbinding threshold */ for(i = 0; i < len; i++) { p = ud[i].index; if(P[p].v.DM_BindingEnergy >= weakly_bound_limit) { pot = subfind_loctree_treeevaluate_potential(p); /* note: add self-energy */ P[p].u.DM_Potential = pot + P[p].Mass / All.SofteningTable[P[p].Type]; P[p].u.DM_Potential *= All.G / atime; if(All.TotN_gas > 0 && (FOF_PRIMARY_LINK_TYPES & 1) == 0 && All.OmegaBaryon > 0) P[p].u.DM_Potential *= All.Omega0 / (All.Omega0 - All.OmegaBaryon); } } } /* let's get bulk velocity and the center-of-mass */ v[0] = v[1] = v[2] = 0; s[0] = s[1] = s[2] = 0; for(i = 0, TotMass = 0; i < len; i++) { p = ud[i].index; for(j = 0; j < 3; j++) { #ifdef PERIODIC ddxx = NEAREST(P[p].Pos[j] - pos[j]); #else ddxx = P[p].Pos[j] - pos[j]; #endif s[j] += P[p].Mass * ddxx; v[j] += P[p].Mass * P[p].Vel[j]; } TotMass += P[p].Mass; } for(j = 0; j < 3; j++) { v[j] /= TotMass; s[j] /= TotMass; /* center-of-mass */ s[j] += pos[j]; #ifdef PERIODIC while(s[j] < 0) s[j] += boxsize; while(s[j] >= boxsize) s[j] -= boxsize; #endif } for(i = 0; i < len; i++) { p = ud[i].index; for(j = 0; j < 3; j++) { dv[j] = vel_to_phys * (P[p].Vel[j] - v[j]); #ifdef PERIODIC dx[j] = atime * NEAREST(P[p].Pos[j] - s[j]); #else dx[j] = atime * (P[p].Pos[j] - s[j]); #endif dv[j] += H_of_a * dx[j]; } P[p].v.DM_BindingEnergy = P[p].u.DM_Potential + 0.5 * (dv[0] * dv[0] + dv[1] * dv[1] + dv[2] * dv[2]); #ifdef DENSITY_SPLIT_BY_TYPE if(P[p].Type == 0) P[p].v.DM_BindingEnergy += P[p].w.int_energy; #endif bnd_energy[i] = P[p].v.DM_BindingEnergy; } qsort(bnd_energy, len, sizeof(double), subfind_compare_binding_energy); /* largest comes first! */ energy_limit = bnd_energy[(int) (0.25 * len)]; for(i = 0, unbound = 0; i < len - 1; i++) { if(bnd_energy[i] > 0) unbound++; else unbound--; if(unbound <= 0) break; } weakly_bound_limit = bnd_energy[i]; /* now omit unbound particles, but at most 1/4 of the original size */ for(i = 0, unbound = 0; i < len; i++) { p = ud[i].index; if(P[p].v.DM_BindingEnergy > 0 && P[p].v.DM_BindingEnergy > energy_limit) { unbound++; ud[i] = ud[len - 1]; i--; len--; } } if(len < All.DesLinkNgb) break; if(phaseflag == 0) { if(unbound > 0) phaseflag = 1; } else { if(unbound == 0) { phaseflag = 0; /* this will make us repeat everything once more for all particles */ unbound = 1; } } } while(unbound > 0); myfree(bnd_energy); return (len); }
static int ial_siocglif(INET_ADDR_LIST *addr_list, INET_ADDR_LIST *mask_list, int af) { const char *myname = "inet_addr_local[siocglif]"; struct lifconf lifc; struct lifreq *lifr; struct lifreq *lifr_mask; struct lifreq *the_end; struct sockaddr *sa; int sock; VSTRING *buf; /* * See also comments in ial_siocgif() */ if (af != AF_INET && af != AF_INET6) msg_fatal("%s: address family was %d, must be AF_INET (%d) or " "AF_INET6 (%d)", myname, af, AF_INET, AF_INET6); sock = ial_socket(af); if (sock < 0) return (0); buf = vstring_alloc(1024); for (;;) { memset(&lifc, 0, sizeof(lifc)); lifc.lifc_family = AF_UNSPEC; /* XXX Why??? */ lifc.lifc_len = vstring_avail(buf); lifc.lifc_buf = vstring_str(buf); if (ioctl(sock, SIOCGLIFCONF, (char *) &lifc) < 0) { if (errno != EINVAL) msg_fatal("%s: ioctl SIOCGLIFCONF: %m", myname); } else if (lifc.lifc_len < vstring_avail(buf) / 2) break; VSTRING_SPACE(buf, vstring_avail(buf) * 2); } the_end = (struct lifreq *) (lifc.lifc_buf + lifc.lifc_len); for (lifr = lifc.lifc_req; lifr < the_end;) { sa = (struct sockaddr *) &lifr->lifr_addr; if (sa->sa_family != af) { lifr = NEXT_INTERFACE(lifr); continue; } if (af == AF_INET) { if (SOCK_ADDR_IN_ADDR(sa).s_addr == INADDR_ANY) { lifr = NEXT_INTERFACE(lifr); continue; } #ifdef HAS_IPV6 } else if (af == AF_INET6) { if (IN6_IS_ADDR_UNSPECIFIED(&SOCK_ADDR_IN6_ADDR(sa))) { lifr = NEXT_INTERFACE(lifr); continue; } } #endif inet_addr_list_append(addr_list, sa); if (mask_list) { lifr_mask = (struct lifreq *) mymalloc(sizeof(struct lifreq)); memcpy((void *) lifr_mask, (void *) lifr, sizeof(struct lifreq)); if (ioctl(sock, SIOCGLIFNETMASK, lifr_mask) < 0) msg_fatal("%s: ioctl(SIOCGLIFNETMASK): %m", myname); /* XXX: Check whether sa_len/family are honoured --dcs */ inet_addr_list_append(mask_list, (struct sockaddr *) &lifr_mask->lifr_addr); myfree((void *) lifr_mask); } lifr = NEXT_INTERFACE(lifr); } vstring_free(buf); (void) close(sock); return (0); }
void qmgr_transport_alloc(QMGR_TRANSPORT *transport, QMGR_TRANSPORT_ALLOC_NOTIFY notify) { QMGR_TRANSPORT_ALLOC *alloc; /* * Sanity checks. */ if (transport->flags & QMGR_TRANSPORT_STAT_DEAD) msg_panic("qmgr_transport: dead transport: %s", transport->name); if (transport->flags & QMGR_TRANSPORT_STAT_RATE_LOCK) msg_panic("qmgr_transport: rate-locked transport: %s", transport->name); if (transport->pending >= QMGR_TRANSPORT_MAX_PEND) msg_panic("qmgr_transport: excess allocation: %s", transport->name); /* * When this message delivery transport is rate-limited, do not select it * again before the end of a message delivery transaction. */ if (transport->xport_rate_delay > 0) transport->flags |= QMGR_TRANSPORT_STAT_RATE_LOCK; /* * Connect to the well-known port for this delivery service, and wake up * when a process announces its availability. Allow only a limited number * of delivery process allocation attempts for this transport. In case of * problems, back off. Do not hose the system when it is in trouble * already. * * Use non-blocking connect(), so that Linux won't block the queue manager * until the delivery agent calls accept(). * * When the connection to delivery agent cannot be completed, notify the * event handler so that it can throttle the transport and defer the todo * queues, just like it does when communication fails *after* connection * completion. * * Before Postfix 2.4, the event handler was not invoked after connect() * error, and mail was not deferred. Because of this, mail would be stuck * in the active queue after triggering a "connection refused" condition. */ alloc = (QMGR_TRANSPORT_ALLOC *) mymalloc(sizeof(*alloc)); alloc->transport = transport; alloc->notify = notify; transport->pending += 1; if ((alloc->stream = mail_connect(MAIL_CLASS_PRIVATE, transport->name, NON_BLOCKING)) == 0) { msg_warn("connect to transport %s/%s: %m", MAIL_CLASS_PRIVATE, transport->name); event_request_timer(qmgr_transport_event, (void *) alloc, 0); return; } #if (EVENTS_STYLE != EVENTS_STYLE_SELECT) && defined(CA_VSTREAM_CTL_DUPFD) #ifndef THRESHOLD_FD_WORKAROUND #define THRESHOLD_FD_WORKAROUND 128 #endif vstream_control(alloc->stream, CA_VSTREAM_CTL_DUPFD(THRESHOLD_FD_WORKAROUND), CA_VSTREAM_CTL_END); #endif event_enable_read(vstream_fileno(alloc->stream), qmgr_transport_event, (void *) alloc); /* * Guard against broken systems. */ event_request_timer(qmgr_transport_abort, (void *) alloc, var_daemon_timeout); }