Example #1
0
 /**
  *  创建群组
  *
  *  @param pPdu      收到的packet包指针
  *  @param conn_uuid 该包过来的socket 描述符
  */
 void createGroup(CImPdu* pPdu, uint32_t conn_uuid)
 {
     IM::Group::IMGroupCreateReq msg;
     IM::Group::IMGroupCreateRsp msgResp;
     if(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
     {
         CImPdu* pPduRes = new CImPdu;
         
         uint32_t nUserId = msg.user_id();
         string strGroupName = msg.group_name();
         IM::BaseDefine::GroupType nGroupType = msg.group_type();
         if(IM::BaseDefine::GroupType_IsValid(nGroupType))
         {
             string strGroupAvatar = msg.group_avatar();
             set<uint32_t> setMember;
             uint32_t nMemberCnt = msg.member_id_list_size();
             for(uint32_t i=0; i<nMemberCnt; ++i)
             {
                 uint32_t nUserId = msg.member_id_list(i);
                 setMember.insert(nUserId);
             }
             log("createGroup.%d create %s, userCnt=%u", nUserId, strGroupName.c_str(), setMember.size());
             
             uint32_t nGroupId = CGroupModel::getInstance()->createGroup(nUserId, strGroupName, strGroupAvatar, nGroupType, setMember);
             msgResp.set_user_id(nUserId);
             msgResp.set_group_name(strGroupName);
             for(auto it=setMember.begin(); it!=setMember.end();++it)
             {
                 msgResp.add_user_id_list(*it);
             }
             if(nGroupId != INVALID_VALUE)
             {
                 msgResp.set_result_code(0);
                 msgResp.set_group_id(nGroupId);
             }
             else
             {
                 msgResp.set_result_code(1);
             }
             
             
             log("createGroup.%d create %s, userCnt=%u, result:%d", nUserId, strGroupName.c_str(), setMember.size(), msgResp.result_code());
             
             msgResp.set_attach_data(msg.attach_data());
             pPduRes->SetPBMsg(&msgResp);
             pPduRes->SetSeqNum(pPdu->GetSeqNum());
             pPduRes->SetServiceId(IM::BaseDefine::SID_GROUP);
             pPduRes->SetCommandId(IM::BaseDefine::CID_GROUP_CREATE_RESPONSE);
             CProxyConn::AddResponsePdu(conn_uuid, pPduRes);
         }
         else
         {
             log("invalid group type.userId=%u, groupType=%u, groupName=%s", nUserId, nGroupType, strGroupName.c_str());
         }
     }
     else
     {
         log("parse pb failed");
     }
 }
Example #2
0
double RNG::nfix(slong h, ulong i)
{
  const double r = 3.442620; 	// The starting of the right tail
  
  double x, y;
  for(;;) {
    x = h * wn[i];

    // If i == 0, handle the base strip
    if (i == 0) {
      do {
	x = -log(rand_open01()) * 0.2904764;   // .2904764 is 1/r
	y = -log(rand_open01());
      } while (y + y < x * x);
      return ((h > 0) ? r + x : -r - x);
    }
    
    // If i > 0, handle the wedges of other strips
    if (fn[i] + rand_open01() * (fn[i - 1] - fn[i]) < exp(-.5 * x * x))
      return x;
    
    // start all over
    h = UL32toSL32(rand_int32());
    i = h & 127;
    if (ULONG32(std::abs(h)) < kn[i])
      return (h * wn[i]);
  }

} // RNG::nfix
Example #3
0
File: _math.c Project: 10sr/cpython
double
_Py_acosh(double x)
{
    if (Py_IS_NAN(x)) {
        return x+x;
    }
    if (x < 1.) {                       /* x < 1;  return a signaling NaN */
        errno = EDOM;
#ifdef Py_NAN
        return Py_NAN;
#else
        return (x-x)/(x-x);
#endif
    }
    else if (x >= two_pow_p28) {        /* x > 2**28 */
        if (Py_IS_INFINITY(x)) {
            return x+x;
        }
        else {
            return log(x)+ln2;          /* acosh(huge)=log(2x) */
        }
    }
    else if (x == 1.) {
        return 0.0;                     /* acosh(1) = 0 */
    }
    else if (x > 2.) {                  /* 2 < x < 2**28 */
        double t = x*x;
        return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
    }
    else {                              /* 1 < x <= 2 */
        double t = x - 1.0;
        return m_log1p(t + sqrt(2.0*t + t*t));
    }
}
Example #4
0
/* Function to call genotypes from post probs
   NOTE: probs must be normalized, that is, sum (or logsum) to 1!
      geno              : array with probs
      n_geno            : number of genotypes in array
      log_scale         : are the probs in log scale?
      N_prob_thresh     : minimum prob to use data.
                          If highest prob is lower, data set as missing
      call_prob_thresh  : minimum prob to call a genotype. 
                          If highest prob is lower, leave geno as probs
      miss_data         : how the missing data is handled
          0 = missing data (all genot with equal prob)
	  1 = sample random genotype
	  2 = call the highest prob geno (since missing data, probably major/major)
*/
void call_geno(double *geno, int n_geno, bool log_scale, double N_prob_thresh, double call_prob_thresh, int miss_data){
  if(N_prob_thresh > call_prob_thresh)
    error(__FUNCTION__, "missing data threshold must be smaller than calling genotype threshold!");

  int max_pos = array_max_pos(geno, n_geno);
  int min_pos = array_min_pos(geno, n_geno);
  double max_pp = (log_scale ? exp(geno[max_pos]) : geno[max_pos]);

  // If missing data
  if(geno[min_pos] == geno[max_pos]){
    if(miss_data == 0)
      max_pp = -1;
    else if(miss_data == 1)
      max_pos = rand() % 3;
  }


  if(max_pp < N_prob_thresh)
    for (int g = 0; g < n_geno; g++)
      geno[g] = (log_scale ? log((double) 1/n_geno) : (double) 1/n_geno);


  if(max_pp >= call_prob_thresh){
    for (int g = 0; g < n_geno; g++)
      geno[g] = (log_scale ? -INF : 0);

    geno[max_pos] = (log_scale ? log(1) : 1);
  }
}
Example #5
0
void update_fminus_Saha(double **logfminus_hist, double *logfminus_Ly_hist[],
                        double xe, double TR, double nH, TWO_PHOTON_PARAMS *twog,
			double zstart, double dlna, unsigned iz, double z, int func_select){

    double fplus[NVIRT];
    double fplus_Ly[2];
    unsigned b;
    double common_fact;       

    if (func_select == 0) {
       for (b = 0; b < NVIRT; b++) logfminus_hist[b][iz] = -twog->Eb_tab[b]/TR;  
       logfminus_Ly_hist[0][iz] = -E21/TR;
       logfminus_Ly_hist[1][iz] = -E31/TR;
       logfminus_Ly_hist[2][iz] = -E41/TR;         
    }
    else {
        fplus_from_fminus(fplus, fplus_Ly, logfminus_hist, logfminus_Ly_hist, TR,
                          zstart, dlna, iz, z, twog->Eb_tab);
  
         for (b = 0; b < NVIRT; b++) logfminus_hist[b][iz] = log(fplus[b]);  /* free streaming */

         common_fact = log(nH*xe*xe/(1.-xe)/(3.016103031869581e21 *TR*sqrt(TR)));
         logfminus_Ly_hist[0][iz] = common_fact + EI/4./TR;         /* Saha equilibrium with the continuum */
         logfminus_Ly_hist[1][iz] = common_fact + EI/9./TR;
         logfminus_Ly_hist[2][iz] = common_fact + EI/16./TR; 
    }     
}
void init()
{
 int m,i,j;
 m=int(log((double)n)/log(2.0));
 for(i=1;i<=m;i++)
   for(j=n+1-p[i];j>=1;j--)
   {
	   f[j][i]=f[j][i-1]>f[j+p[i-1]][i-1]?f[j][i-1]:f[j+p[i-1]][i-1];
	   if(h[j+p[i-1]-1]==h[j+p[i-1]])
	   {
		 f[j][i]=f[j][i]>right[j][i-1]+left[j+p[i-1]][i-1]?f[j][i]:right[j][i-1]+left[j+p[i-1]][i-1];
		 if(h[j]==h[j+p[i-1]-1])
			 left[j][i]=left[j][i-1]+left[j+p[i-1]][i-1];
		 else
			 left[j][i]=left[j][i-1];
		 if(h[j+p[i-1]]==h[j+p[i]-1])
			 right[j][i]=right[j+p[i-1]][i-1]+right[j][i-1];
		 else
			 right[j][i]=right[j+p[i-1]][i-1];
	   }
	   else
	   {
		left[j][i]=left[j][i-1];
		right[j][i]=right[j+p[i-1]][i-1];
	   }
   }
}
Example #7
0
void model_parameters::preliminary_calculations(void)
{

#if defined(USE_ADPVM)

  admaster_slave_variable_interface(*this);

#endif
  // get the data out of the columns of the data matrix
  landings=column(data,1);
  biomass=column(data,2);
  
  // calculate observed surplus production (Pobs)
  for(int i=1;i<=nobs-1;i++)
  {
  Pobs(i)=biomass(i+1)-biomass(i)+landings(i);			
  }
  
  // set starting values
  lnMSY=log(0.6*max(Pobs));
  lnK=log(max(biomass));
  n=2;
  
  
}
Example #8
0
// NormFloat64 returns a normally distributed float64 in the range
// [-math.MaxFloat64, +math.MaxFloat64] with
// standard normal distribution (mean = 0, stddev = 1).
// To produce a different normal distribution, callers can
// adjust the output using:
//
//  sample = NormFloat64() * desiredStdDev + desiredMean
//
real_t rstdnorm_zig(void) {
        for (;;) {
                int32_t j = gen_rand32(); // Possibly negative
                int32_t i = j & 0x7F;
                real_t x = (real_t)(j) * (real_t)(wn[i]);
                if (absInt32(j) < kn[i]) {
                        // This case should be hit better than 99% of the time.
                        return x;
                }

                if (i == 0) {
                        // This extra work is only required for the base strip.
                        for (;;) {
                                x = -log(runif()) * (1.0 / rn);
                                real_t y = -log(runif());
                                if (y+y >= x*x) {
                                        break;
                                }
                        }
                        if (j > 0) {
                                return rn + x;
                        }
                        return -rn - x;
                }
                if (fn[i]+runif()*(fn[i-1]-fn[i]) < exp(-.5*x*x)) {
                        return x;
                }
        }
        errx(EXIT_FAILURE,"Unreachable: %s (%s:%d)",__func__,__FILE__,__LINE__);
}
Example #9
0
void
bfdesign (float fpass, float apass, float fstop, float astop,
	int *npoles, float *f3db)
/*****************************************************************************
Butterworth filter:  compute number of poles and -3 db frequency
for a low-pass or high-pass filter, given a frequency response
constrained at two frequencies.
******************************************************************************
Input:
fpass		frequency in pass band at which amplitude is >= apass
apass		amplitude in pass band corresponding to frequency fpass
fstop 		frequency in stop band at which amplitude is <= astop
astop		amplitude in stop band corresponding to frequency fstop

Output:
npoles		number of poles
f3db		frequency at which amplitude is sqrt(0.5) (-3 db)
******************************************************************************
Notes:
(1) Nyquist frequency equals 0.5

(2) The following conditions must be true:
	(0.0<fpass && fpass<0.5) &&
	(0.0<fstop && fstop<0.5) &&
	(fpass!=fstop) &&
	(0.0<astop && astop<apass && apass<1.0)

(3) if (fpass<fstop)
		a low-pass filter is assumed
	else
		a high-pass filter is assumed
******************************************************************************
Author:		Dave Hale, Colorado School of Mines, 06/02/89
*****************************************************************************/
{
	float wpass,wstop,fnpoles,w3db;

	/* warp frequencies according to bilinear transform */
	wpass = 2.0*tan(PI*fpass);
	wstop = 2.0*tan(PI*fstop);

	/* if lowpass filter, then */
	if (fstop>fpass) {
		fnpoles = log((1.0/(apass*apass)-1.0)/(1.0/(astop*astop)-1.0))
			/ log(pow(wpass/wstop,2.0));
		w3db = wpass/pow((1.0/(apass*apass)-1.0),0.5/fnpoles);

	/* else, if highpass filter, then */
	} else {
		fnpoles = log((1.0/(apass*apass)-1.0)/(1.0/(astop*astop)-1.0))
			/ log(pow(wstop/wpass,2.0));
		w3db = wpass*pow((1.0/(apass*apass)-1.0),0.5/fnpoles);
	}

	/* determine integer number of poles */
	*npoles = 1+(int)fnpoles;

	/* determine (unwarped) -3 db frequency */
	*f3db = atan(0.5*w3db)/PI;
}
Example #10
0
slong
hypgeom_estimate_terms(const mag_t z, int r, slong prec)
{
    double y, t;

    t = mag_get_d(z);

    if (t == 0)
        return 1;

    if (r == 0)
    {
        if (t >= 1)
        {
            flint_printf("z must be smaller than 1\n");
            abort();
        }

        y = (log(1-t) - prec * LOG2) / log(t) + 1;
    }
    else
    {
        y = (prec * LOG2) / (d_root(t, r) * EXP1 * r);
        y = (prec * LOG2) / (r * d_lambertw(y)) + 1;
    }

    if (y >= WORD_MAX / 2)
    {
        flint_printf("error: series will converge too slowly\n");
        abort();
    }

    return y;
}
Example #11
0
//最大熵和法
int EdgeDetection::MESM(float p[256])
{
	int i,t,T;
	float p1,p2,h1,h,fei,tempfei;
	fei=-65535.0;	
	for(t=0;t<255;t++){	//算熵和,并求出最大的熵和		
		p1=p2=h1=h=0.0;
		for(i=0;i<=t;i++)
			p1+=p[i];
		p2=1-p1;
		for(i=0;i<=t;i++)
			if(p1>MINNUM)
				if(fabs(p[i]/p1)>MINNUM)
					h1+=-1*(p[i]/p1)*(float)(log(p[i]/p1));
		for(i=0;i<=t;i++)
			if(fabs(p[i])>MINNUM)
				h+=-1*p[i]*(float)(log(p[i]));
		if(p1>MINNUM&&p2>MINNUM)
			tempfei=(float)(log(p1*p2))+h/p1+(h1-h)/p2;
		else
			tempfei=-65535.0;
		if(tempfei>fei) {
			fei=tempfei;
			T=t;
		}
	}
	return T;
}
Example #12
0
File: asinh.c Project: GregorR/musl
double asinh(double x)
{
	double t,w;
	int32_t hx,ix;

	GET_HIGH_WORD(hx, x);
	ix = hx & 0x7fffffff;
	if (ix >= 0x7ff00000)   /* x is inf or NaN */
		return x+x;
	if (ix < 0x3e300000) {  /* |x| < 2**-28 */
		/* return x inexact except 0 */
		if (huge+x > 1.0)
			return x;
	}
	if (ix > 0x41b00000) {  /* |x| > 2**28 */
		w = log(fabs(x)) + ln2;
	} else if (ix > 0x40000000) {  /* 2**28 > |x| > 2.0 */
		t = fabs(x);
		w = log(2.0*t + 1.0/(sqrt(x*x+1.0)+t));
	} else {                /* 2.0 > |x| > 2**-28 */
		t = x*x;
		w =log1p(fabs(x) + t/(1.0+sqrt(1.0+t)));
	}
	if (hx > 0)
		return w;
	return -w;
}
Example #13
0
float draw_mass_stellar_cen(float mhalo, float z, struct Params p, gsl_rng *rng){
    /*
    Prob. density function for stellar mass, given halo mass and redshift. Uses 
    the form from Moster et al. (2010). Central galaxies.
    */
    float M2, mean_ms, sigma;
    
    // Mean stellar mass as fn. of halo mass
    mean_ms = mass_stellar_cen(mhalo, z, p);
    
    // Scatter as a fn. of halo mass [Eq. 12 of Moster et al. (2010)]
    M2 = pow(10., p.ms_cen_logM2);
    sigma = p.ms_cen_sigmainf 
          + p.ms_cen_sigma1 * (1. - 2./M_PI*atan(p.ms_cen_xi * log10(mhalo/M2)));
    sigma *= log(10.); // sigma in dex
    
    // Ensure that sigma is +ve, and larger than the value needed for 
    // integration to converge
    if(sigma < 2e-2){ sigma = 2e-2; }
    
    // Return pdf
    return gsl_ran_lognormal(rng, 
                             log(mean_ms),
                             sigma);
    /*return exp(-log(mstar/mean_ms)**2./(2.*sigma**2.)) \
         / (np.sqrt(2.*np.pi)*sigma*Ms); */
}
Example #14
0
 /**
  *  获取正式群列表
  *
  *  @param pPdu      收到的packet包指针
  *  @param conn_uuid 该包过来的socket 描述符
  */
 void getNormalGroupList(CImPdu* pPdu, uint32_t conn_uuid)
 {
     IM::Group::IMNormalGroupListReq msg;
     IM::Group::IMNormalGroupListRsp msgResp;
     if(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
     {
         CImPdu* pPduRes = new CImPdu;
         
         uint32_t nUserId = msg.user_id();
         
         list<IM::BaseDefine::GroupVersionInfo> lsGroup;
         CGroupModel::getInstance()->getUserGroup(nUserId, lsGroup, IM::BaseDefine::GROUP_TYPE_NORMAL);
         msgResp.set_user_id(nUserId);
         for(auto it=lsGroup.begin(); it!=lsGroup.end(); ++it)
         {
             IM::BaseDefine::GroupVersionInfo* pGroupVersion = msgResp.add_group_version_list();
             pGroupVersion->set_group_id(it->group_id());
             pGroupVersion->set_version(it->version());
         }
         
         log("getNormalGroupList. userId=%u, count=%d", nUserId, msgResp.group_version_list_size());
         
         msgResp.set_attach_data(msg.attach_data());
         pPduRes->SetPBMsg(&msgResp);
         pPduRes->SetSeqNum(pPdu->GetSeqNum());
         pPduRes->SetServiceId(IM::BaseDefine::SID_GROUP);
         pPduRes->SetCommandId(IM::BaseDefine::CID_GROUP_NORMAL_LIST_RESPONSE);
         CProxyConn::AddResponsePdu(conn_uuid, pPduRes);
     }
     else
     {
         log("parse pb failed");
     }
 }
Example #15
0
    bool compact(const string& ns, string &errmsg, bool validate, BSONObjBuilder& result, double pf, int pb) {
        massert( 14028, "bad ns", NamespaceString::normal(ns.c_str()) );
        massert( 14027, "can't compact a system namespace", !str::contains(ns, ".system.") ); // items in system.indexes cannot be moved there are pointers to those disklocs in NamespaceDetails

        bool ok;
        {
            writelock lk;
            BackgroundOperation::assertNoBgOpInProgForNs(ns.c_str());
            Client::Context ctx(ns);
            NamespaceDetails *d = nsdetails(ns.c_str());
            massert( 13660, str::stream() << "namespace " << ns << " does not exist", d );
            massert( 13661, "cannot compact capped collection", !d->capped );
            log() << "compact " << ns << " begin" << endl;
            if( pf != 0 || pb != 0 ) { 
                log() << "paddingFactor:" << pf << " paddingBytes:" << pb << endl;
            } 
            try { 
                ok = _compact(ns.c_str(), d, errmsg, validate, result, pf, pb);
            }
            catch(...) { 
                log() << "compact " << ns << " end (with error)" << endl;
                throw;
            }
            log() << "compact " << ns << " end" << endl;
        }
        return ok;
    }
Example #16
0
double logPoisson3(double k, double lambda)
{
	double offset = 0.0;
	if (lambda > 0)
	{
		offset = lambda * log(lambda) - lambda - logFactorial(lambda);
	}

	if (k == 0)
	{
		if (lambda == 0)
		{
			return 0.0;
		}
		else
		{
			return -lambda - offset;
		}
	}
	else
	{
		if (lambda == 0)
		{
			return -logFactorial(k) - offset;
		}
		else
		{
			return k * log(lambda) - lambda - logFactorial(k) - offset;
		}
	}
}
// determine the count of tiles required for a page at a given zoom level
USHORT RenderCache::GetTileRes(DisplayModel *dm, int pageNo)
{
    RectD mediabox = dm->engine->PageMediabox(pageNo);
    RectD pixelbox = dm->engine->Transform(mediabox, pageNo, dm->ZoomReal(), dm->Rotation());

    float factorW = (float)pixelbox.dx / (maxTileSize.dx + 1);
    float factorH = (float)pixelbox.dy / (maxTileSize.dy + 1);
    // using the geometric mean instead of the maximum factor
    // so that the tile area doesn't get too small in comparison
    // to maxTileSize (but remains smaller)
    float factorAvg = sqrtf(factorW * factorH);

    // use larger tiles when fitting page or width or when a page is smaller
    // than the visible canvas width/height or when rendering pages
    // without clipping optimizations
    if (dm->ZoomVirtual() == ZOOM_FIT_PAGE || dm->ZoomVirtual() == ZOOM_FIT_WIDTH ||
        pixelbox.dx <= dm->viewPort.dx || pixelbox.dy < dm->viewPort.dy ||
        !dm->engine->HasClipOptimizations(pageNo)) {
        factorAvg /= 2.0;
    }

    USHORT res = 0;
    if (factorAvg > 1.5)
        res = (USHORT)ceilf(log(factorAvg) / log(2.0f));
    // limit res to 30, so that (1 << res) doesn't overflow for 32-bit signed int
    return min(res, 30);
}
bool
SeekableZStream::Init(const void *buf)
{
  const SeekableZStreamHeader *header = SeekableZStreamHeader::validate(buf);
  if (!header) {
    log("Not a seekable zstream");
    return false;
  }

  buffer = reinterpret_cast<const unsigned char *>(buf);
  totalSize = header->totalSize;
  chunkSize = header->chunkSize;
  lastChunkSize = header->lastChunkSize;
  offsetTable.Init(&header[1], header->nChunks);

  /* Sanity check */
  if ((chunkSize == 0) ||
      (chunkSize % PAGE_SIZE) ||
      (chunkSize > 8 * PAGE_SIZE) ||
      (offsetTable.numElements() < 1) ||
      (lastChunkSize == 0) ||
      (lastChunkSize > chunkSize)) {
    log("Malformed or broken seekable zstream");
    return false;
  }

  return true;
}
Example #19
0
static char *value_string(char *buf, int buf_size, double val, const char *unit)
{
    if (unit == unit_second_str && use_value_sexagesimal_format) {
        double secs;
        int hours, mins;
        secs  = val;
        mins  = (int)secs / 60;
        secs  = secs - mins * 60;
        hours = mins / 60;
        mins %= 60;
        snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
    } else if (use_value_prefix) {
        const char *prefix_string;
        int index;

        if (unit == unit_byte_str && use_byte_value_binary_prefix) {
            index = (int) (log(val)/log(2)) / 10;
            index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
            val /= pow(2, index*10);
            prefix_string = binary_unit_prefixes[index];
        } else {
            index = (int) (log10(val)) / 3;
            index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
            val /= pow(10, index*3);
            prefix_string = decimal_unit_prefixes[index];
        }

        snprintf(buf, buf_size, "%.3f %s%s", val, prefix_string, show_value_unit ? unit : "");
    } else {
        snprintf(buf, buf_size, "%f %s", val, show_value_unit ? unit : "");
    }

    return buf;
}
Example #20
0
/* scan_file is called once during boot-up.  It scans through the mail file
   and indexes all entries currently in the mail file. */
int scan_file(void)
{
  FILE *mail_file;
  header_block_type next_block;
  int total_messages = 0, block_num = 0;
  char buf[100];

  if (!(mail_file = fopen(MAIL_FILE, "r"))) {
    log("Mail file non-existant... creating new file.");
    mail_file = fopen(MAIL_FILE, "w");
    fclose(mail_file);
    return 1;
  }
  while (fread(&next_block, sizeof(header_block_type), 1, mail_file)) {
    if (next_block.block_type == HEADER_BLOCK) {
      index_mail(next_block.header_data.to, block_num * BLOCK_SIZE);
      total_messages++;
    } else if (next_block.block_type == DELETED_BLOCK)
      push_free_list(block_num * BLOCK_SIZE);
    block_num++;
  }

  file_end_pos = ftell(mail_file);
  fclose(mail_file);
  sprintf(buf, "   %ld bytes read.", file_end_pos);
  log(buf);
  if (file_end_pos % BLOCK_SIZE) {
    log("SYSERR: Error booting mail system -- Mail file corrupt!");
    log("SYSERR: Mail disabled!");
    return 0;
  }
  sprintf(buf, "   Mail file read -- %d messages.", total_messages);
  log(buf);
  return 1;
}				/* end of scan_file */
Example #21
0
void timer_expired( const std::string& id, const boost::system::error_code& e ) {
	log() << " " << id << " enter." << std::endl;
	log() << e.message() << std::endl;
	//std::this_thread::sleep_for( std::chrono::seconds(3));
	log() << " " << id << " leave." << std::endl;

}
Example #22
0
//加载最高分
bool CGeneralManager::LoadHighScore()
{
	string strPath = FileUtils::getInstance()->getWritablePath() + string(HIGHSCORE_FILEPATH);

	string strContent = FileUtils::getInstance()->getStringFromFile(strPath);
	rapidjson::Document oDoc;
	oDoc.Parse<0>(strContent.c_str());
	if (oDoc.HasParseError() || oDoc.IsNull())
	{
		log("CGeneralManager::LoadUserData Load 'oDoc' Error.");
		return false;
	}

	for (int i = 0; i < oDoc["HighScore"].Size(); i++)
	{
		if (oDoc["HighScore"][i].IsNull())
		{
			log("CGeneralManager::LoadUserData Load 'oDoc[HighScore][%d]' Error.", i);
			return false;
		}

		int iValue = oDoc["HighScore"][i].GetInt();
		m_mapHighScore[i] = iValue;
	}

	return true;
}
void GammaCompressor::compressUnsignedInt(ofstream * invertedFile, unsigned int number, unsigned char * bitCode, int * currentBit)
{
    int numberSizeByBit;
    int cpt;
    if (number > 0) {
        numberSizeByBit = int(floor(log(number) / log(2)))+1;
    }
    else {
        numberSizeByBit = 0;
    }
    cpt = numberSizeByBit;
    while (cpt > 1) {
        writeBit(invertedFile, bitCode, currentBit, true);
        cpt--;
    }
    writeBit(invertedFile, bitCode, currentBit, false);
    if (number == 0) {
        writeBit(invertedFile, bitCode, currentBit, false);
    }
    else if (number == 1) {
        writeBit(invertedFile, bitCode, currentBit, true);
    }
    else {
        cpt = numberSizeByBit-1;
        number =number % int(pow(2, cpt));
        while (cpt > 0) {
            writeBit(invertedFile, bitCode, currentBit, number / int(pow(2, cpt - 1)) == 1);
            number = number % int(pow(2, cpt-1));
            cpt--;
        }
    }

}
Example #24
0
void main (void)
{
    log ("Calling overlay 1 from main");

    /* The symbols _OVERLAY1_LOAD__ and _OVERLAY1_SIZE__ were generated by the
     * linker. They contain the overlay area address and size specific to a
     * certain program.
     */
    if (loadfile ("ovrldemo.1", _OVERLAY1_LOAD__, _OVERLAY1_SIZE__)) {

        /* The linker makes sure that the call to foo() ends up at the right mem
         * addr. However it's up to user to make sure that the - right - overlay
         * is actually loaded before making the the call.
         */
        foo ();
    }

    log ("Calling overlay 2 from main");

    /* Replacing one overlay with another one can only happen from the main
     * program. This implies that an overlay can never load another overlay.
     */
    if (loadfile ("ovrldemo.2", _OVERLAY2_LOAD__, _OVERLAY2_SIZE__)) {
        bar ();
    }

    log ("Calling overlay 3 from main");
    if (loadfile ("ovrldemo.3", _OVERLAY3_LOAD__, _OVERLAY3_SIZE__)) {
        foobar ();
    }

    cgetc ();
}
Example #25
0
void read_rates(HRATEEFF *rate_table){

   FILE *fA = fopen(ALPHA_FILE, "r");
   FILE *fR = fopen(RR_FILE, "r"); 

   unsigned i, j, l;

   maketab(log(TR_MIN), log(TR_MAX), NTR, rate_table->logTR_tab);
   maketab(TM_TR_MIN, TM_TR_MAX, NTM, rate_table->TM_TR_tab);
   rate_table->DlogTR = rate_table->logTR_tab[1] - rate_table->logTR_tab[0];
   rate_table->DTM_TR = rate_table->TM_TR_tab[1] - rate_table->TM_TR_tab[0];  

   for (i = 0; i < NTR; i++) {  
      for (j = 0; j < NTM; j++) {  
	 for (l = 0; l <= 1; l++) {
           fscanf(fA, "%le", &(rate_table->logAlpha_tab[l][j][i]));
           rate_table->logAlpha_tab[l][j][i] = log(rate_table->logAlpha_tab[l][j][i]);
        }
      }
    
      fscanf(fR, "%le", &(rate_table->logR2p2s_tab[i]));
      rate_table->logR2p2s_tab[i] = log(rate_table->logR2p2s_tab[i]);
      
   }
   fclose(fA);
   fclose(fR);
}
Example #26
0
static enum ihex_record parse_ihex(const char *line, uint32_t *offset, uint32_t *length, uint8_t **data) {
    enum ihex_record type;

    if(sscanf(line, ":%02X%04X%02X", length, offset, &type) != 3) {
        log("Got invalid IHEX record \"%s\"", line);
        return IHEX_INVALID;
    }

    if(type == IHEX_DATA) {
        const char *p = line + 9;
        if(strlen(p) - 2 < *length * 2) {
            log("Record too short");
            return IHEX_INVALID;
        }

        if(data) {
            *data = malloc(*length);

            for(int i=0; i < *length; i++) {
                (*data)[i] = HEX2DEC(p[2*i]) << 4 |
                             HEX2DEC(p[2*i+1]);
            }
        }
    }

    return type;
}
Example #27
0
_HOOK_IMPL(int,SdAVDec_DemuxStart, unsigned int dmxHandle, int eDemuxOut) {
	log("SdDemux_Start, dmxHandle=0x%08X, eDemuxOut=0x%08X\n", dmxHandle, eDemuxOut);
	g_dmxHandle = dmxHandle;
	log("g_dmxHandle=0x%08X\n", g_dmxHandle);
	_HOOK_DISPATCH(SdAVDec_DemuxStart, dmxHandle, eDemuxOut);
	return (int)h_ret;
}
Example #28
0
int lock_type_unlock(int type)
{
	char *name;
	char *device;
	int	i;
	int   size;

	lock_init_locknames();

	if (!(device = rindex(setup.modem.device, '/')))
		device = setup.modem.device;
	else
		device++;
	
	i = 0;
	
	while (TRUE)
	{
		if (locks[i].file == NULL)
		{
			log(L_WARN, "Lock setup for type %d not found.\n", type);

			returnerror();
		}

		if (locks[i].type == type) break;

		i++;
	}

	size = (strlen(locks[i].file) + strlen(device) + 2);
	
	if ((name = (char *)malloc(size)))
	{
		printstring(name, locks[i].file, device);

		log(L_DEBUG, "Unlocking %s (%s)...\n", locks[i].desc, name);

		if (*(locks[i].fd) != -1)
		{
			lock_unlocking(*(locks[i].fd), 5);

			close(*(locks[i].fd));

			*(locks[i].fd) = -1;
		}

		if (unlink(name) != 0)
		{
			log(L_WARN, "Can't remove lock \"%s\".\n", name);
		}

		free(name);

		returnok();
	}
	else log(L_FATAL, "Not enough memory to allocate lockname.\n");
				
	returnerror();
}
Example #29
0
File: _math.c Project: 10sr/cpython
double
_Py_asinh(double x)
{
    double w;
    double absx = fabs(x);

    if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
        return x+x;
    }
    if (absx < two_pow_m28) {           /* |x| < 2**-28 */
        return x;                       /* return x inexact except 0 */
    }
    if (absx > two_pow_p28) {           /* |x| > 2**28 */
        w = log(absx)+ln2;
    }
    else if (absx > 2.0) {              /* 2 < |x| < 2**28 */
        w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx));
    }
    else {                              /* 2**-28 <= |x| < 2= */
        double t = x*x;
        w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t)));
    }
    return copysign(w, x);

}
Example #30
0
SPSO11::SPSO11(ParamMap& v):Swarm<CodeVReal,ParticleSPSO11>(v[param_popSize],v[param_evalCountFlag]),m_impr(0){

	m_name="SPSO11";
    m_algPar<<"Population size: "<<m_popsize;
	initializePara(1. / (2 * log(2)), 0.5 + log(2), 0.5 + log(2));
	m_p=  1 - pow(1 - 1. / (m_popsize), 3);
}