本文整理汇总了C++中ceil函数的典型用法代码示例。如果您正苦于以下问题:C++ ceil函数的具体用法?C++ ceil怎么用?C++ ceil使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ceil函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: QgsDebugMsg
QgsRasterBlock * QgsRasterDataProvider::block( int theBandNo, QgsRectangle const & theExtent, int theWidth, int theHeight )
{
QgsDebugMsg( QString( "theBandNo = %1 theWidth = %2 theHeight = %3" ).arg( theBandNo ).arg( theWidth ).arg( theHeight ) );
QgsDebugMsg( QString( "theExtent = %1" ).arg( theExtent.toString() ) );
QgsRasterBlock *block = new QgsRasterBlock( dataType( theBandNo ), theWidth, theHeight, noDataValue( theBandNo ) );
if ( block->isEmpty() )
{
QgsDebugMsg( "Couldn't create raster block" );
return block;
}
// Read necessary extent only
QgsRectangle tmpExtent = extent().intersect( &theExtent );
if ( tmpExtent.isEmpty() )
{
QgsDebugMsg( "Extent outside provider extent" );
block->setIsNoData();
return block;
}
double xRes = theExtent.width() / theWidth;
double yRes = theExtent.height() / theHeight;
double tmpXRes, tmpYRes;
double providerXRes = 0;
double providerYRes = 0;
if ( capabilities() & ExactResolution )
{
providerXRes = extent().width() / xSize();
providerYRes = extent().height() / ySize();
tmpXRes = qMax( providerXRes, xRes );
tmpYRes = qMax( providerYRes, yRes );
if ( doubleNear( tmpXRes, xRes ) ) tmpXRes = xRes;
if ( doubleNear( tmpYRes, yRes ) ) tmpYRes = yRes;
}
else
{
tmpXRes = xRes;
tmpYRes = yRes;
}
if ( tmpExtent != theExtent ||
tmpXRes > xRes || tmpYRes > yRes )
{
// Read smaller extent or lower resolution
// Calculate row/col limits (before tmpExtent is aligned)
int fromRow = qRound(( theExtent.yMaximum() - tmpExtent.yMaximum() ) / yRes );
int toRow = qRound(( theExtent.yMaximum() - tmpExtent.yMinimum() ) / yRes ) - 1;
int fromCol = qRound(( tmpExtent.xMinimum() - theExtent.xMinimum() ) / xRes ) ;
int toCol = qRound(( tmpExtent.xMaximum() - theExtent.xMinimum() ) / xRes ) - 1;
QgsDebugMsg( QString( "fromRow = %1 toRow = %2 fromCol = %3 toCol = %4" ).arg( fromRow ).arg( toRow ).arg( fromCol ).arg( toCol ) );
if ( fromRow < 0 || fromRow >= theHeight || toRow < 0 || toRow >= theHeight ||
fromCol < 0 || fromCol >= theWidth || toCol < 0 || toCol >= theWidth )
{
// Should not happen
QgsDebugMsg( "Row or column limits out of range" );
return block;
}
// If lower source resolution is used, the extent must beS aligned to original
// resolution to avoid possible shift due to resampling
if ( tmpXRes > xRes )
{
int col = floor(( tmpExtent.xMinimum() - extent().xMinimum() ) / providerXRes );
tmpExtent.setXMinimum( extent().xMinimum() + col * providerXRes );
col = ceil(( tmpExtent.xMaximum() - extent().xMinimum() ) / providerXRes );
tmpExtent.setXMaximum( extent().xMinimum() + col * providerXRes );
}
if ( tmpYRes > yRes )
{
int row = floor(( extent().yMaximum() - tmpExtent.yMaximum() ) / providerYRes );
tmpExtent.setYMaximum( extent().yMaximum() - row * providerYRes );
row = ceil(( extent().yMaximum() - tmpExtent.yMinimum() ) / providerYRes );
tmpExtent.setYMinimum( extent().yMaximum() - row * providerYRes );
}
int tmpWidth = qRound( tmpExtent.width() / tmpXRes );
int tmpHeight = qRound( tmpExtent.height() / tmpYRes );
tmpXRes = tmpExtent.width() / tmpWidth;
tmpYRes = tmpExtent.height() / tmpHeight;
QgsDebugMsg( QString( "Reading smaller block tmpWidth = %1 theHeight = %2" ).arg( tmpWidth ).arg( tmpHeight ) );
QgsDebugMsg( QString( "tmpExtent = %1" ).arg( tmpExtent.toString() ) );
block->setIsNoData();
QgsRasterBlock *tmpBlock = new QgsRasterBlock( dataType( theBandNo ), tmpWidth, tmpHeight, noDataValue( theBandNo ) );
readBlock( theBandNo, tmpExtent, tmpWidth, tmpHeight, tmpBlock->data() );
int pixelSize = dataTypeSize( theBandNo );
double xMin = theExtent.xMinimum();
double yMax = theExtent.yMaximum();
double tmpXMin = tmpExtent.xMinimum();
double tmpYMax = tmpExtent.yMaximum();
//.........这里部分代码省略.........
开发者ID:carsonfarmer,项目名称:Quantum-GIS,代码行数:101,代码来源:qgsrasterdataprovider.cpp
示例2: startProgress
//.........这里部分代码省略.........
const double model_high = map_model.getMax()[ConsensusFeature::RT];
const double scene_high = map_scene.getMax()[ConsensusFeature::RT];
// OLD STUFF
// const double rt_low = (maps[0].getMin()[ConsensusFeature::RT] + maps[1].getMin()[ConsensusFeature::RT]) / 2.;
// const double rt_high = (maps[0].getMax()[ConsensusFeature::RT] + maps[1].getMax()[ConsensusFeature::RT]) / 2.;
// Initialize the hash tables: shift_hash_
// OLD STUFF: was: rt_scaling_hash_, rt_low_hash_, and rt_high_hash_
{
// (over)estimate the required number of buckets for shifting
double max_shift = param_.getValue("max_shift");
// actually the largest possible shift can be much smaller, depending on the data
do
{
if (max_shift < 0)
max_shift = -max_shift;
// [email protected]@@mh........ , [email protected]@@mh...
// [email protected]@@sh... , [email protected]@@sh........
double diff;
diff = model_high - scene_low;
if (diff < 0)
diff = -diff;
if (max_shift > diff)
max_shift = diff;
diff = model_low - scene_high;
if (diff < 0)
diff = -diff;
if (max_shift > diff)
max_shift = diff;
}
while (0);
const Int shift_buckets_num_half = 4 + (Int) ceil((max_shift) / shift_bucket_size);
const Int shift_buckets_num = 1 + 2 * shift_buckets_num_half;
shift_hash_.getData().clear();
shift_hash_.getData().resize(shift_buckets_num);
shift_hash_.setMapping(shift_bucket_size, shift_buckets_num_half, 0);
}
setProgress(++actual_progress);
//**************************************************************************
// compute the ratio of the total intensities of both maps, for normalization
double total_intensity_ratio;
do
{
double total_int_model_map = 0;
for (Size i = 0; i < model_map.size(); ++i)
{
total_int_model_map += model_map[i].getIntensity();
}
setProgress(++actual_progress);
double total_int_scene_map = 0;
for (Size i = 0; i < scene_map.size(); ++i)
{
total_int_scene_map += scene_map[i].getIntensity();
}
setProgress(++actual_progress);
// ... and finally ...
total_intensity_ratio = total_int_model_map / total_int_scene_map;
}
while (0); // (the extra syntax helps with code folding in eclipse!)
setProgress((actual_progress = 20));
/// The serial number is incremented for each invocation of this, to avoid overwriting of hash table dumps.
开发者ID:FabianAicheler,项目名称:OpenMS,代码行数:67,代码来源:PoseClusteringShiftSuperimposer.cpp
示例3: CCopasiMessage
/**
* This function synchronizes step size and number
*/
bool CTSSAProblem::sync()
{
bool success = true;
C_FLOAT64 Tmp = *mpDuration;
C_FLOAT64 StepSize = *mpStepSize;
C_FLOAT64 StepNumber = (C_FLOAT64) * mpStepNumber;
if (mStepNumberSetLast)
{
StepSize = Tmp / (C_FLOAT64) * mpStepNumber;
/* Assure that the step size is not to small for machine accuracy */
if (fabs(StepSize) < 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration))
{
CCopasiMessage(CCopasiMessage::WARNING,
MCTSSAProblem + 3, StepSize);
StepSize = 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration);
/* Assure that the step size has the appropriate sign. */
StepSize = (Tmp < 0.0) ? - fabs(StepSize) : fabs(StepSize);
StepNumber = fabs(ceil(Tmp / StepSize));
}
}
else
{
if (fabs(StepSize) < 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration))
{
CCopasiMessage(CCopasiMessage::WARNING,
MCTSSAProblem + 3, StepSize);
StepSize = 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(*mpDuration);
/* Assure that the step size has the appropriate sign. */
StepSize = (Tmp < 0.0) ? - fabs(StepSize) : fabs(StepSize);
}
StepNumber = fabs(ceil(Tmp / StepSize));
/* Protect against overflow */
if ((C_FLOAT64) ULONG_MAX < StepNumber)
{
CCopasiMessage(CCopasiMessage::WARNING,
MCTSSAProblem + 2, StepNumber);
StepNumber = (C_FLOAT64) ULONG_MAX;
StepSize = Tmp / StepNumber;
success = false;
}
/* Assure that the step size has the appropriate sign. */
StepSize = (Tmp < 0.0) ? - fabs(StepSize) : fabs(StepSize);
}
*mpStepSize = StepSize;
*mpStepNumber = (unsigned C_INT32) StepNumber;
if (!success) throw 1;
return success;
}
开发者ID:copasi,项目名称:COPASI,代码行数:65,代码来源:CTSSAProblem.cpp
示例4: main
//.........这里部分代码省略.........
if ( outFile == NULL )
{
fprintf( stderr, "ERROR: --output-file must be specified\n" );
exit( 1 );
}
/* Complete file name with details of the input variables */
sprintf(tail, "%s-Phenom_M%3.1f_R%2.1f.dat", outFile, totalMass, massRatio);
optarg_len = strlen(tail) + strlen(outFile) + 1;
outFileLong = (CHAR *)calloc(optarg_len, sizeof(CHAR));
strcpy(outFileLong, tail);
/* check sample rate is enough */
if (sampleRate > 4.*params.fCut) /* Changed by Ajith. 5 May 2008 */
{
dt = 1./sampleRate;
}
else
{
sampleRate = 4.*params.fCut;
dt = 1./sampleRate;
}
/* Estimation of the time duration of the binary */
/* See Sathya (1994) for the Newtonian and PN1 chirp times */
/* The merger time is overestimated */
newtonianChirpTime =
(5./(256.*eta))*pow(totalMass*LAL_MTSUN_SI,-5./3.)*pow(LAL_PI*fLow,-8./3.);
PN1ChirpTime =
5.*(743.+924.*eta)/(64512.*eta*totalMass*LAL_MTSUN_SI*pow(LAL_PI*fLow,2.));
mergTime = 2000.*totalMass*LAL_MTSUN_SI;
totTime = 1.2 * (newtonianChirpTime + PN1ChirpTime + mergTime);
numPts = (UINT4) ceil(totTime/dt);
df = 1/(numPts * dt);
/* Compute Amplitude and Phase from the paper (Eq. 4.19) */
Aeff = XLALHybridP1Amplitude(¶ms, fLow, df, eta, totalMass, numPts/2+1);
Phieff = XLALHybridP1Phase(¶ms, fLow, df, eta, totalMass, numPts/2 +1);
/* Construct u(f) = Aeff*e^(i*Phieff) */
XLALComputeComplexVector(&uFPlus, &uFCross, Aeff, Phieff);
/* Scale this to units of M */
for (i = 0; i < numPts/2 + 1; i++) {
num = uFPlus->data[i];
num.re *= 1./(dt*totalMass*LAL_MTSUN_SI);
num.im *= 1./(dt*totalMass*LAL_MTSUN_SI);
uFPlus->data[i] = num;
num = uFCross->data[i];
num.re *= 1./(dt*totalMass*LAL_MTSUN_SI);
num.im *= 1./(dt*totalMass*LAL_MTSUN_SI);
uFCross->data[i] = num;
}
/* Inverse Fourier transform */
LALCreateReverseREAL4FFTPlan( &status, &prevPlus, numPts, 0 );
LALCreateReverseREAL4FFTPlan( &status, &prevCross, numPts, 0 );
hPlus = XLALCreateREAL4Vector(numPts);
hCross = XLALCreateREAL4Vector(numPts);
LALReverseREAL4FFT( &status, hPlus, uFPlus, prevPlus );
LALReverseREAL4FFT( &status, hCross, uFCross, prevCross );
/* The LAL implementation of the FFT omits the factor 1/n */
for (i = 0; i < numPts; i++) {
开发者ID:smirshekari,项目名称:lalsuite,代码行数:67,代码来源:LALHybridTest.c
示例5: main
int
main(int argc, char ** argv)
{
if ( argc != 3 ) {
fprintf(stderr, "Usage: %s <infile.iv> <outfile.iv>\n", argv[0]);
return -1;
}
SoDB::init();
SoNodeKit::init();
SoInteraction::init();
SoGenerateSceneGraphAction::initClass();
SoTweakAction::initClass();
SoInput in;
SoNode * scene, * graph;
if ( !in.openFile(argv[1]) ) {
fprintf(stderr, "%s: error opening \"%s\" for reading.\n", argv[0], argv[1]);
return -1;
}
scene = SoDB::readAll(&in);
if ( scene == NULL ) {
fprintf(stderr, "%s: error parsing \"%s\"\n", argv[0], argv[1]);
return -1;
}
scene->ref();
SoGenerateSceneGraphAction action;
// action.setDropTypeIfNameEnabled(TRUE);
action.apply(scene);
graph = action.getGraph();
if ( graph == NULL ) {
fprintf(stderr, "%s: error generating scene graph\n", argv[0]);
return -1;
}
graph->ref();
scene->unref();
scene = NULL;
// figure out camera settings and needed rendering canvas size
SoGetBoundingBoxAction bbaction(SbViewportRegion(64,64)); // just something
bbaction.apply(graph);
SbBox3f bbox = bbaction.getBoundingBox();
SbVec3f min = bbox.getMin();
SbVec3f max = bbox.getMax();
float bwidth = max[0] - min[0];
float bheight = max[1] - min[1];
// fprintf(stdout, "min: %g %g %g\n", min[0], min[1], min[2]);
// fprintf(stdout, "max: %g %g %g\n", max[0], max[1], max[2]);
// place camera
SoSearchAction search;
search.setType(SoCamera::getClassTypeId());
search.setInterest(SoSearchAction::FIRST);
search.apply(graph);
SoPath * campath = search.getPath();
SoOrthographicCamera * cam = (SoOrthographicCamera *) campath->getTail();
assert(cam != NULL);
SbVec3f pos = cam->position.getValue();
cam->position.setValue(SbVec3f(min[0] + ((max[0]-min[0])/2.0),
min[1] + ((max[1]-min[1])/2.0),
pos[2]));
cam->height.setValue(bheight);
if ( TRUE ) { // FIXME: only write .iv-scene if asked
SoOutput out;
if ( !out.openFile(argv[2]) ) {
fprintf(stderr, "%s: error opening \"%s\" for writing.\n", argv[0], argv[2]);
return -1;
}
SoWriteAction writer(&out);
// writer.setCoinFormattingEnabled(TRUE);
writer.apply(graph);
}
int width = (int) ceil(bwidth * 150.0) + 2;
int height = (int) ceil(bheight * 150.0);
fprintf(stderr, "image: %d x %d\n", width, height);
if ( TRUE ) { // FIXME: only write image if asked
SoOffscreenRenderer renderer(SbViewportRegion(width, height));
SoGLRenderAction * glra = renderer.getGLRenderAction();
glra->setNumPasses(9);
// FIXME: auto-crop image afterwards? seems like it's a perfect fit right now
renderer.setComponents(SoOffscreenRenderer::RGB_TRANSPARENCY);
renderer.setBackgroundColor(SbColor(1.0,1.0,1.0));
renderer.render(graph);
// FIXME: support command line option filename
// FIXME: also support .eps
renderer.writeToFile("output.png", "png");
}
graph->unref();
return 0;
}
开发者ID:Alexpux,项目名称:SmallChange,代码行数:96,代码来源:iv2scenegraph.cpp
示例6: getTile
int cScene::getTile(glm::vec3 p) {
//std::cout << floor(playerx) << " " << ceil(playerz) + 0.5f << std::endl;
return map[ceil(playerx + 0.1f)][ceil(playerz) + 0.5f];
}
开发者ID:addja,项目名称:keep-running-n-nobody-gets-hurt,代码行数:4,代码来源:cScene.cpp
示例7: GenerateGiantSteps
static
void GenerateGiantSteps(const GF2EX& f, const GF2EX& h, long l, long verbose)
{
double t;
if (verbose) { cerr << "generating giant steps..."; t = GetTime(); }
GF2EXModulus F;
build(F, f);
GF2EXArgument H;
#if 0
double n2 = sqrt(double(F.n));
double n4 = sqrt(n2);
double n34 = n2*n4;
long sz = long(ceil(n34/sqrt(sqrt(2.0))));
#else
long sz = 2*SqrRoot(F.n);
#endif
build(H, h, F, sz);
GF2EX h1;
h1 = h;
long i;
long HexOutput = GF2X::HexOutput;
GF2X::HexOutput = 1;
if (!use_files) {
GiantStepFile.kill();
GiantStepFile.SetLength(l);
}
for (i = 1; i <= l-1; i++) {
if (use_files) {
ofstream s;
OpenWrite(s, FileName(GF2EX_stem, "giant", i));
s << h1 << "\n";
s.close();
}
else
GiantStepFile(i) = h1;
CompMod(h1, h1, H, F);
if (verbose) cerr << "+";
}
if (use_files) {
ofstream s;
OpenWrite(s, FileName(GF2EX_stem, "giant", i));
s << h1 << "\n";
s.close();
}
else
GiantStepFile(i) = h1;
if (verbose)
cerr << (GetTime()-t) << "\n";
GF2X::HexOutput = HexOutput;
}
开发者ID:av-elier,项目名称:fast-exponentiation-algs,代码行数:66,代码来源:GF2EXFactoring.c
示例8: config_cnameset
F_NONNULL
static void config_cnameset(const char* res_name, const char* stanza, cnset_t* cnset, const vscf_data_t* cfg) {
dmn_assert(res_name); dmn_assert(stanza); dmn_assert(cnset); dmn_assert(cfg);
if(!vscf_is_hash(cfg))
log_fatal("plugin_weighted: resource '%s' stanza '%s' value must be a hash", res_name, stanza);
cnset->count = vscf_hash_get_len(cfg);
// service_types
cnset->num_svcs = 0;
const vscf_data_t* res_stypes = vscf_hash_get_data_byconstkey(cfg, "service_types", true);
if (res_stypes) {
cnset->count--; // minus one for service_types entry
cnset->num_svcs = vscf_array_get_len(res_stypes);
if(cnset->num_svcs) {
cnset->svc_names = malloc(cnset->num_svcs * sizeof(char*));
for(unsigned i = 0; i < cnset->num_svcs; i++) {
const vscf_data_t* this_svc_cfg = vscf_array_get_data(res_stypes, i);
if(!vscf_is_simple(this_svc_cfg))
log_fatal("plugin_weighted: resource '%s' (%s): service_types values must be strings", res_name, stanza);
cnset->svc_names[i] = strdup(vscf_simple_get_data(this_svc_cfg));
}
}
}
else {
cnset->num_svcs = 1;
cnset->svc_names = malloc(sizeof(char*));
cnset->svc_names[0] = strdup(DEFAULT_SVCNAME);
}
// up threshold as double
double up_thresh = 0.5;
const vscf_data_t* thresh_cfg = vscf_hash_get_data_byconstkey(cfg, "up_thresh", true);
if(thresh_cfg) {
cnset->count--; // minus one for up_thresh entry
if(!vscf_is_simple(thresh_cfg) || !vscf_simple_get_as_double(thresh_cfg, &up_thresh)
|| up_thresh <= 0.0 || up_thresh > 1.0)
log_fatal("plugin_weighted: resource '%s' (%s): 'up_thresh' must be a floating point value in the range (0.0 - 1.0]", res_name, stanza);
}
// multi option is processed for count-correctness, but ignored (it's not legal
// here, but may be present due to inheritance of defaults!)
if(vscf_hash_get_data_byconstkey(cfg, "multi", true))
cnset->count--;
if(cnset->count > MAX_ITEMS_PER_SET)
log_fatal("plugin_weighted: resource '%s' (%s): number of cnames cannot be more than %u", res_name, stanza, MAX_ITEMS_PER_SET);
if(!cnset->count)
log_fatal("plugin_weighted: resource '%s' (%s): empty cname sets not allowed", res_name, stanza);
cnset->items = calloc(cnset->count, sizeof(res_citem_t));
cname_iter_data_t cid = {
.cnset = cnset,
.res_name = res_name,
.stanza = stanza,
.item_idx = 0,
};
vscf_hash_iterate(cfg, true, config_item_cname, &cid);
cnset->weight = 0;
for(unsigned i = 0; i < cnset->count; i++) {
const unsigned cwt = cnset->items[i].weight;
dmn_assert(cwt);
cnset->weight += cwt;
}
dmn_assert(cnset->weight);
cnset->up_weight = ceil(up_thresh * cnset->weight);
}
F_NONNULL
static void config_auto(resource_t* res, const vscf_data_t* res_cfg) {
dmn_assert(res); dmn_assert(res_cfg); dmn_assert(vscf_is_hash(res_cfg));
// mark all possible parameter-keys
vscf_hash_get_data_byconstkey(res_cfg, "service_types", true);
vscf_hash_get_data_byconstkey(res_cfg, "multi", true);
vscf_hash_get_data_byconstkey(res_cfg, "up_thresh", true);
// make a copy that contains no parameters, only item-name keys
vscf_data_t* res_cfg_noparams = vscf_clone(res_cfg, true);
if(!vscf_hash_get_len(res_cfg_noparams))
log_fatal("plugin_weighted: resource '%s' (direct) contains no weighted items", res->name);
const char* first_name = vscf_hash_get_key_byindex(res_cfg_noparams, 0, NULL);
const vscf_data_t* first_cfg = vscf_hash_get_data_byindex(res_cfg_noparams, 0);
if(vscf_is_hash(first_cfg)) { // grouped address mode...
if(!vscf_hash_get_len(first_cfg))
log_fatal("plugin_weighted: resource '%s' (direct): group '%s': contains no addresses", res->name, first_name);
const char* lb_name = vscf_hash_get_key_byindex(first_cfg, 0, NULL);
const vscf_data_t* lb_cfg = vscf_hash_get_data_byindex(first_cfg, 0);
if(!vscf_is_array(lb_cfg) || !vscf_array_get_len(lb_cfg) || !vscf_is_simple(vscf_array_get_data(lb_cfg, 0)))
log_fatal("plugin_weighted: resource '%s' (direct): group '%s': item '%s': value must be an array of [ IP, weight ]", res->name, first_name, lb_name);
const char* first_addr_txt = vscf_simple_get_data(vscf_array_get_data(lb_cfg, 0));
dmn_anysin_t temp_sin;
int addr_err = gdnsd_anysin_getaddrinfo(first_addr_txt, NULL, &temp_sin);
if(addr_err)
//.........这里部分代码省略.........
开发者ID:jasperla,项目名称:gdnsd,代码行数:101,代码来源:weighted.c
示例9: renderer_overlay_wallpaper
static int renderer_overlay_wallpaper( GdkPixbuf *background,
const char *wallpaper,
MMB_Screen *screen,
int clip )
{
GError *error = NULL;
GdkPixbuf *image = gdk_pixbuf_new_from_file( wallpaper, &error );
if ( error != NULL ) {
fprintf( stderr, "Failed to parse image: %s\n" , error->message );
return 0;
}
double wp_width = gdk_pixbuf_get_width( image );
double wp_height = gdk_pixbuf_get_height( image );
for ( int monitor = 0; monitor < screen->num_monitors; monitor++ ) {
MMB_Rectangle rectangle = screen->monitors[monitor];
double w_scale = wp_width/( double )( rectangle.w );
double h_scale = wp_height/( double )( rectangle.h );
// Picture is small then screen, center it.
if ( w_scale < 1 && h_scale < 1 ) {
gdk_pixbuf_copy_area( image, 0,0,
wp_width, wp_height,
background,
rectangle.x + ( rectangle.w-wp_width )/2,
rectangle.y + ( rectangle.h-wp_height )/2
);
}
// Picture is smaller on one of the sides and we want to clip.
else if ( clip && ( w_scale < 1 || h_scale < 1 ) ) {
double x_off = ( ( float )rectangle.w-wp_width )/2.0;
double y_off = ( ( float )rectangle.h-wp_height )/2.0;
gdk_pixbuf_copy_area( image,
-( x_off < 0 )*x_off,-( y_off < 0 )*y_off,
wp_width+( x_off < 0 )*2*x_off,
wp_height+( y_off < 0 )*2*y_off,
background,
rectangle.x + ( ( x_off> 0 )?x_off:0 ),
rectangle.y + ( ( y_off> 0 )?y_off:0 ) );
}
// Picture is bigger/equal then screen.
// Scale to fit.
else {
int new_w= 0;
int new_h = 0;
double x_off = 0;
double y_off = 0;
if ( clip ) {
if ( w_scale < h_scale ) {
new_w = wp_width/w_scale;
new_h = wp_height/w_scale;
} else {
new_w = wp_width/h_scale;
new_h = wp_height/h_scale;
}
x_off = ( ( new_w-rectangle.w )/2.0 );
y_off = ( ( new_h-rectangle.h )/2.0 );
} else {
if ( w_scale > h_scale ) {
new_w = wp_width/w_scale;
new_h = wp_height/w_scale;
} else {
new_w = wp_width/h_scale;
new_h = wp_height/h_scale;
}
}
GdkPixbuf *scaled_wp = gdk_pixbuf_scale_simple( image, new_w, new_h, GDK_INTERP_HYPER );
gdk_pixbuf_copy_area(
scaled_wp,
( int )ceil( x_off ),( int )ceil( y_off ),
new_w-ceil(x_off)*2,
new_h-ceil(y_off)*2,
background,
rectangle.x + ( ( double )rectangle.w-new_w+x_off*2 )/2,
rectangle.y + ( ( double )rectangle.h-new_h+y_off*2 )/2 );
g_object_unref( scaled_wp );
}
}
g_object_unref( image );
return 1;
}
开发者ID:DaveDavenport,项目名称:MultiMonitorBackground,代码行数:90,代码来源:mmb.c
示例10: send_file
int send_file(HTHREAD_PTR descr, char *filename)
{
WSADATA wsa_data;
SOCKET data_socket = INVALID_SOCKET;
struct sockaddr_in send_data_addr;
HPACKET packet;
HPARTITION partition;
FILE *fp;
int return_code;
unsigned long at_location,
read_amount,
tries;
unsigned char packet_count;
char control_message[MAX_INPUT_LENGTH];
if(fopen_s(&fp, filename, "rb") > 0)
{
memset(control_message, 0, sizeof(MAX_INPUT_LENGTH));
control_message[0] = CONTROL_MESSAGE_NO_SUCH_FILE;
return_code = send(descr->socket, control_message, (int)strlen(control_message), 0);
return 1;
}
for(tries = 0; tries < CONTROL_MESSAGE_RECV_RETRIES; tries++)
{
memset(control_message, 0, sizeof(MAX_INPUT_LENGTH));
return_code = recv(descr->socket, control_message, MAX_INPUT_LENGTH-1, 0);
if(return_code < 1)
{
printf("failed to recv command: %d\n", WSAGetLastError());
closesocket(data_socket);
return 0;
}
if(control_message[0] == CONTROL_MESSAGE_OK_START_SENDING)
break;
}
if(tries >= CONTROL_MESSAGE_RECV_RETRIES)
{
printf("No CONTROL_MESSAGE_OK_START_SENDING from %s\n", inet_ntoa(descr->address.sin_addr));
closesocket(data_socket);
return 0;
}
WSAStartup(MAKEWORD(2,2), &wsa_data);
data_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
send_data_addr.sin_family = AF_INET;
send_data_addr.sin_port = htons(CONNECT_PORT_N);//descr->address.sin_port;
send_data_addr.sin_addr = descr->address.sin_addr;//inet_addr("123.456.789.1");
packet.partition_id = 0;
packet.reserved = 0;
while(!feof(fp))
{
memset(partition.packet_stats, 0, MAX_PARTITION_DIVISIONS+1);
partition.actual_size = (unsigned long)fread(partition.data, 1, PARTITION_LENGTH_TOTAL, fp);
packet_count = (unsigned char)ceil(partition.actual_size / PACKET_LENGTH_DATA);
memset(control_message, 0, sizeof(MAX_INPUT_LENGTH));
sprintf_s(control_message, MAX_INPUT_LENGTH, " %u", partition.actual_size);
control_message[0] = CONTROL_MESSAGE_SENDING_DATA;
return_code = send(descr->socket, control_message, (int)strlen(control_message)+1, 0);
if(return_code == SOCKET_ERROR)
{
printf("failed to send command: %d\n", WSAGetLastError());
closesocket(data_socket);
return 0;
}
while(1)
{
for(packet.packet_id = 0; packet.packet_id < packet_count; packet.packet_id++)
{
if(partition.packet_stats[packet.packet_id] != 1)
break;
}
if(packet.packet_id == packet_count)
break;
for(packet.packet_id = 0; packet.packet_id < packet_count; packet.packet_id++)
{
if(partition.packet_stats[packet.packet_id] != 1)
{
memset(packet.data, 0, sizeof(PARTITION_LENGTH_TOTAL));
at_location = packet.packet_id * PACKET_LENGTH_DATA;
read_amount = at_location + PACKET_LENGTH_DATA < partition.actual_size ? PACKET_LENGTH_DATA : partition.actual_size - at_location;
memcpy(packet.data, &partition.data[at_location], read_amount);
packet.crc = compute_crc((const unsigned char *)packet.data, PACKET_LENGTH_DATA);
return_code = sendto(data_socket, (char *)&packet, sizeof(packet), 0, (SOCKADDR *)&send_data_addr, sizeof(send_data_addr));
if(return_code == SOCKET_ERROR)
{
printf("failed to send command: %d\n", WSAGetLastError());
closesocket(data_socket);
return 0;
}
Sleep(5);
}
//.........这里部分代码省略.........
开发者ID:smakonin,项目名称:UFTP,代码行数:101,代码来源:uftpd.c
示例11: config_addrset
F_NONNULL
static void config_addrset(const char* res_name, const char* stanza, const bool ipv6, addrset_t* addrset, const vscf_data_t* cfg) {
dmn_assert(res_name); dmn_assert(stanza); dmn_assert(addrset); dmn_assert(cfg);
if(!vscf_is_hash(cfg))
log_fatal("plugin_weighted: resource '%s' stanza '%s' value must be a hash", res_name, stanza);
const vscf_data_t* parent = vscf_get_parent(cfg);
// inherit down the applicable res-level parameters
vscf_hash_inherit(parent, (vscf_data_t*)cfg, "service_types", true);
vscf_hash_inherit(parent, (vscf_data_t*)cfg, "multi", true);
vscf_hash_inherit(parent, (vscf_data_t*)cfg, "up_thresh", true);
// Get a starting assumption of our item count
addrset->count = vscf_hash_get_len(cfg);
/////// Process the parameters...
// service_types
addrset->num_svcs = 0;
const vscf_data_t* res_stypes = vscf_hash_get_data_byconstkey(cfg, "service_types", true);
if (res_stypes) {
addrset->count--; // minus one for service_types entry
addrset->num_svcs = vscf_array_get_len(res_stypes);
if(addrset->num_svcs) {
addrset->svc_names = malloc(addrset->num_svcs * sizeof(char*));
for(unsigned i = 0; i < addrset->num_svcs; i++) {
const vscf_data_t* this_svc_cfg = vscf_array_get_data(res_stypes, i);
if(!vscf_is_simple(this_svc_cfg))
log_fatal("plugin_weighted: resource '%s' (%s): service_types values must be strings", res_name, stanza);
addrset->svc_names[i] = strdup(vscf_simple_get_data(this_svc_cfg));
}
}
}
else {
addrset->num_svcs = 1;
addrset->svc_names = malloc(sizeof(char*));
addrset->svc_names[0] = strdup(DEFAULT_SVCNAME);
}
// multi option
addrset->multi = false;
const vscf_data_t* multi_cfg = vscf_hash_get_data_byconstkey(cfg, "multi", true);
if(multi_cfg) {
addrset->count--; // minus one for multi entry
if(!vscf_is_simple(multi_cfg) || !vscf_simple_get_as_bool(multi_cfg, &addrset->multi))
log_fatal("plugin_weighted: resource '%s' (%s): 'multi' must be a boolean value ('true' or 'false')", res_name, stanza);
}
// up threshold as double
double up_thresh = 0.5;
const vscf_data_t* thresh_cfg = vscf_hash_get_data_byconstkey(cfg, "up_thresh", true);
if(thresh_cfg) {
addrset->count--; // minus one for up_thresh entry
if(!vscf_is_simple(thresh_cfg) || !vscf_simple_get_as_double(thresh_cfg, &up_thresh)
|| up_thresh <= 0.0 || up_thresh > 1.0)
log_fatal("plugin_weighted: resource '%s' (%s): 'up_thresh' must be a floating point value in the range (0.0 - 1.0]", res_name, stanza);
}
if(addrset->count > MAX_ITEMS_PER_SET)
log_fatal("plugin_weighted: resource '%s' (%s): number of direct groups or addrs within one family cannot be more than %u", res_name, stanza, MAX_ITEMS_PER_SET);
if(!addrset->count)
log_fatal("plugin_weighted: resource '%s' (%s): empty address-family sets not allowed", res_name, stanza);
addrset->items = calloc(addrset->count, sizeof(res_aitem_t));
addrset->gmode = RES_ASET_UNKNOWN;
addr_iter_data_t aid = {
.item_idx = 0,
.addrset = addrset,
.res_name = res_name,
.stanza = stanza,
.ipv6 = ipv6
};
vscf_hash_iterate(cfg, true, config_addrset_item, &aid);
addrset->weight = 0;
addrset->max_weight = 0;
for(unsigned i = 0; i < addrset->count; i++) {
const unsigned iwt = addrset->items[i].weight;
const unsigned num_addrs = addrset->items[i].count;
dmn_assert(iwt); dmn_assert(addrset->items[i].max_weight);
addrset->weight += iwt;
if(addrset->max_weight < iwt)
addrset->max_weight = iwt;
if(addrset->max_addrs_pergroup < num_addrs)
addrset->max_addrs_pergroup = num_addrs;
}
dmn_assert(addrset->weight);
dmn_assert(addrset->max_weight);
addrset->up_weight = ceil(up_thresh * addrset->weight);
dmn_assert(addrset->up_weight);
}
typedef struct {
cnset_t* cnset;
const char* res_name;
const char* stanza;
//.........这里部分代码省略.........
开发者ID:jasperla,项目名称:gdnsd,代码行数:101,代码来源:weighted.c
示例12: switch
void CvGBTrees::find_gradient(const int k)
{
int* sample_data = sample_idx->data.i;
int* subsample_data = subsample_train->data.i;
float* grad_data = data->responses->data.fl;
float* resp_data = orig_response->data.fl;
float* current_data = sum_response->data.fl;
switch (params.loss_function_type)
// loss_function_type in
// {SQUARED_LOSS, ABSOLUTE_LOSS, HUBER_LOSS, DEVIANCE_LOSS}
{
case SQUARED_LOSS:
{
for (int i=0; i<get_len(subsample_train); ++i)
{
int s_step = (sample_idx->cols > sample_idx->rows) ? 1
: sample_idx->step/CV_ELEM_SIZE(sample_idx->type);
int idx = *(sample_data + subsample_data[i]*s_step);
grad_data[idx] = resp_data[idx] - current_data[idx];
}
}; break;
case ABSOLUTE_LOSS:
{
for (int i=0; i<get_len(subsample_train); ++i)
{
int s_step = (sample_idx->cols > sample_idx->rows) ? 1
: sample_idx->step/CV_ELEM_SIZE(sample_idx->type);
int idx = *(sample_data + subsample_data[i]*s_step);
grad_data[idx] = Sign(resp_data[idx] - current_data[idx]);
}
}; break;
case HUBER_LOSS:
{
float alpha = 0.2f;
int n = get_len(subsample_train);
int s_step = (sample_idx->cols > sample_idx->rows) ? 1
: sample_idx->step/CV_ELEM_SIZE(sample_idx->type);
float* residuals = new float[n];
for (int i=0; i<n; ++i)
{
int idx = *(sample_data + subsample_data[i]*s_step);
residuals[i] = fabs(resp_data[idx] - current_data[idx]);
}
icvSortFloat(residuals, n, 0.0f);
delta = residuals[int(ceil(n*alpha))];
for (int i=0; i<n; ++i)
{
int idx = *(sample_data + subsample_data[i]*s_step);
float r = resp_data[idx] - current_data[idx];
grad_data[idx] = (fabs(r) > delta) ? delta*Sign(r) : r;
}
delete[] residuals;
}; break;
case DEVIANCE_LOSS:
{
for (int i=0; i<get_len(subsample_train); ++i)
{
double exp_fk = 0;
double exp_sfi = 0;
int s_step = (sample_idx->cols > sample_idx->rows) ? 1
: sample_idx->step/CV_ELEM_SIZE(sample_idx->type);
int idx = *(sample_data + subsample_data[i]*s_step);
for (int j=0; j<class_count; ++j)
{
double res;
res = current_data[idx + j*sum_response->cols];
res = exp(res);
if (j == k) exp_fk = res;
exp_sfi += res;
}
int orig_label = int(resp_data[idx]);
/*
grad_data[idx] = (float)(!(k-class_labels->data.i[orig_label]+1)) -
(float)(exp_fk / exp_sfi);
*/
int ensemble_label = 0;
while (class_labels->data.i[ensemble_label] - orig_label)
ensemble_label++;
grad_data[idx] = (float)(!(k-ensemble_label)) -
(float)(exp_fk / exp_sfi);
}
}; break;
default: break;
}
} // CvGBTrees::find_gradient(...)
开发者ID:Rocky030,项目名称:opencv,代码行数:97,代码来源:gbt.cpp
示例13: DoClientThinks
void DoClientThinks( gentity_t *ent ) {
int lastCmd, lastTime;
int latestTime;
int drop_threshold = LAG_MAX_DROP_THRESHOLD;
int startPackets = ent->client->cmdcount;
if ( ent->client->cmdcount <= 0 )
return;
// allow some more movement if time has passed
latestTime = trap_Milliseconds();
if ( ent->client->lastCmdRealTime > latestTime ) {
// zinx - stoopid server went backwards in time, reset the delta
// instead of giving them even -less- movement ability
ent->client->cmddelta = 0;
} else {
ent->client->cmddelta -= (latestTime - ent->client->lastCmdRealTime);
}
if ( ent->client->cmdcount <= 1 && ent->client->cmddelta < 0 )
ent->client->cmddelta = 0;
ent->client->lastCmdRealTime = latestTime;
lastCmd = (ent->client->cmdhead + ent->client->cmdcount - 1) % LAG_MAX_COMMANDS;
lastTime = ent->client->ps.commandTime;
latestTime = ent->client->cmds[lastCmd].serverTime;
while ( ent->client->cmdcount > 0 ) {
usercmd_t *cmd = &ent->client->cmds[ent->client->cmdhead];
float speed, delta, scale;
int savedTime;
qboolean deltahax = qfalse;
int serverTime = cmd->serverTime;
int totalDelta = latestTime - cmd->serverTime;
int timeDelta;
if ( ent->client->pers.pmoveFixed ) {
serverTime = ((serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer;
}
timeDelta = serverTime - lastTime;
if ( totalDelta >= drop_threshold ) {
// zinx - whoops. too lagged.
drop_threshold = LAG_MIN_DROP_THRESHOLD;
lastTime = ent->client->ps.commandTime = cmd->serverTime;
goto drop_packet;
}
if ( totalDelta < 0 ) {
// zinx - oro? packet from the future
goto drop_packet;
}
if ( timeDelta <= 0 ) {
// zinx - packet from the past
goto drop_packet;
}
scale = 1.f / LAG_DECAY;
speed = G_CmdScale( ent, cmd );
delta = (speed * (float)timeDelta);
delta *= scale;
if ( timeDelta > 50 ) {
timeDelta = 50;
delta = (speed * (float)timeDelta);
delta *= scale;
deltahax = qtrue;
}
if ( (ent->client->cmddelta + delta) >= LAG_MAX_DELTA ) {
// too many commands this server frame
// if it'll fit in the next frame, just wait until then.
if ( delta < LAG_MAX_DELTA
&& (totalDelta + delta) < LAG_MIN_DROP_THRESHOLD )
break;
// try to split it up in to smaller commands
delta = ((float)LAG_MAX_DELTA - ent->client->cmddelta);
timeDelta = ceil(delta / speed); // prefer speedup
delta = (float)timeDelta * speed;
if ( timeDelta < 1 )
break;
delta *= scale;
deltahax = qtrue;
}
ent->client->cmddelta += delta;
if ( deltahax ) {
savedTime = cmd->serverTime;
cmd->serverTime = lastTime + timeDelta;
} else {
//.........这里部分代码省略.........
开发者ID:thewolfteam,项目名称:Reloaded,代码行数:101,代码来源:et-antiwarp.c
示例14: createPerm2
perm2 createPerm2(unsigned int *elems, unsigned int nelems, unsigned int t, static_bitsequence_builder * bmb) {//if uints is set to true the given array is of uints using 32 bits each
perm2 P;
unsigned int *b, *baux, nextelem, i, j, bptr,
aux, antbptr,nbwdptrs, elem,nbits, firstelem, cyclesize;
auxbwd2 *auxbwdptr;
P = new struct sperm2;
P->elems = elems;
P->nelems = nelems;
P->nbits = bits(nelems-1);
nbits = bits(nelems-1);
P->t = t;
if (t==1) {
P->bwdptrs = new unsigned int[uint_len(nelems,nbits)];
for(unsigned int m=0;m<uint_len(nelems,nbits);m++)
P->bwdptrs[m]=0;
assert(P->bwdptrs!=NULL);
P->nbwdptrs = nelems;
for (i=0; i<nelems; i++) {
unsigned int bg = elems[i];
assert(bg<nelems);
set_field(P->bwdptrs, nbits, bg, i);
}
P->bmap = NULL;
}
else {
auxbwdptr = new auxbwd2[(t+((int)ceil((double)nelems/t)))];
assert(auxbwdptr!=NULL);
b = new unsigned int[uint_len(nelems,1)];
for(i=0;i<uint_len(nelems,1);i++)
b[i]=0;
assert(b!=NULL);
baux = new unsigned int[uint_len(nelems,1)];
for(i=0;i<uint_len(nelems,1);i++)
baux[i] = 0;
assert(baux!=NULL);
nbwdptrs = 0;
for (i = 0; i < nelems; i++) {
if (bitget(baux,i) == 0) {
nextelem = j = bptr = antbptr = i;
aux = 0;
bitset(baux, j);
cyclesize = 0;
firstelem = j;
while ((elem=elems[j]) != nextelem) {//P->elems[j]
j = elem;
bitset(baux, j);
aux++;
if (aux >= t) {
auxbwdptr[nbwdptrs].key = j;
auxbwdptr[nbwdptrs++].pointer = bptr;
antbptr = bptr;
bptr = j;
aux = 0;
bitset(b, j);
}
cyclesize++;
}
if (cyclesize >= t) {
auxbwdptr[nbwdptrs].key = nextelem;
auxbwdptr[nbwdptrs++].pointer = bptr;
bitset(b, nextelem);
}
}
}
qsort(auxbwdptr, nbwdptrs, sizeof(auxbwd2), &compare2);
aux = uint_len(nbwdptrs,P->nbits);
P->bwdptrs = new unsigned int[aux];
assert(P->bwdptrs!=NULL);
for(i=0;i<aux;i++) P->bwdptrs[i] = 0;
P->nbwdptrs = nbwdptrs;
for (i = 0; i < nbwdptrs; i++) {
set_field(P->bwdptrs, nbits, i, auxbwdptr[i].pointer);
//if(i<5)
// printf(" %d ",get_field(P->bwdptrs,nbits,i));
}
//printf("\n");
P->bmap = bmb->build(b, nelems);
//delete [] P->bmap;
delete [] b;
delete [] (baux);
delete [] (auxbwdptr);
}
return P;
}
开发者ID:bojifengyu,项目名称:uiHRDC,代码行数:84,代码来源:perm2.cpp
示例15: msContourLayerReadRaster
//.........这里部分代码省略.........
/* Compute overlap between source and target views */
copyRect = mapRect;
if (copyRect.minx < GEO_TRANS(adfGeoTransform,0,src_ysize))
copyRect.minx = GEO_TRANS(adfGeoTransform,0,src_ysize);
if (copyRect.maxx > GEO_TRANS(adfGeoTransform,src_xsize,0))
copyRect.maxx = GEO_TRANS(adfGeoTransform,src_xsize,0);
if (copyRect.miny < GEO_TRANS(adfGeoTransform+3,0,src_ysize))
copyRect.miny = GEO_TRANS(adfGeoTransform+3,0,src_ysize);
if (copyRect.maxy > GEO_TRANS(adfGeoTransform+3,src_xsize,0))
copyRect.maxy = GEO_TRANS(adfGeoTransform+3,src_xsize,0);
if (copyRect.minx >= copyRect.maxx || copyRect.miny >= copyRect.maxy) {
if (layer->debug)
msDebug("msContourLayerReadRaster(): Error in overlap calculation.\n");
return MS_FAILURE;
}
/*
* Convert extraction window to raster coordinates
*/
llx = GEO_TRANS(adfInvGeoTransform+0,copyRect.minx,copyRect.miny);
lly = GEO_TRANS(adfInvGeoTransform+3,copyRect.minx,copyRect.miny);
urx = GEO_TRANS(adfInvGeoTransform+0,copyRect.maxx,copyRect.maxy);
ury = GEO_TRANS(adfInvGeoTransform+3,copyRect.maxx,copyRect.maxy);
/*
* Align extraction window with virtual grid
* (keep in mind raster coordinates origin is at upper-left)
* We also add an extra buffer to fix tile boundarie issues when zoomed
*/
llx = floor(llx / virtual_grid_step_x) * virtual_grid_step
|
请发表评论